diff --git a/.github/workflows/speech.yml b/.github/workflows/speech.yml index cc91c40..b34caf5 100644 --- a/.github/workflows/speech.yml +++ b/.github/workflows/speech.yml @@ -24,7 +24,7 @@ jobs: strategy: fail-fast: false matrix: - os: [macos-14, macos-15-intel, windows-2022, ubuntu-latest] + os: [macos-15, macos-15-intel, windows-2022, ubuntu-latest] env: MACOSX_DEPLOYMENT_TARGET: '11.0' steps: @@ -39,16 +39,16 @@ jobs: if: runner.os == 'macOS' run: bash crates/speech/swift/tests/run.sh - name: Compile iOS backends - if: matrix.os == 'macos-14' + if: matrix.os == 'macos-15' run: | rustup target add aarch64-apple-ios aarch64-apple-ios-sim cargo check -p robius-speech --target aarch64-apple-ios cargo check -p robius-speech --target aarch64-apple-ios-sim - uses: actions/setup-java@v4 - if: matrix.os == 'macos-14' + if: matrix.os == 'macos-15' with: distribution: temurin java-version: '17' - name: Android speech lifecycle regressions - if: matrix.os == 'macos-14' + if: matrix.os == 'macos-15' run: python3 crates/speech/tests/android_retry_test.py diff --git a/.github/workflows/theme.yml b/.github/workflows/theme.yml new file mode 100644 index 0000000..68b19e3 --- /dev/null +++ b/.github/workflows/theme.yml @@ -0,0 +1,51 @@ +name: System theme + +on: + # Only on main: a branch pushed to this repo would otherwise also run every + # job a second time through its pull request. + push: + branches: [main] + paths: + - crates/theme/** + - Cargo.toml + - Cargo.lock + - .github/workflows/theme.yml + pull_request: + paths: + - crates/theme/** + - Cargo.toml + - Cargo.lock + - .github/workflows/theme.yml + +jobs: + # The Android backend is checked by android.yml, along with every other crate. + native: + name: Theme (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-15, macos-15-intel, windows-2022, ubuntu-latest] + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - uses: Swatinem/rust-cache@v2 + - run: cargo clippy -p robius-theme --all-targets -- -D warnings + - run: cargo test -p robius-theme + # This flips the runner's own app theme and back, so it only runs when asked for. + - name: Follow a real theme change + if: runner.os == 'Windows' + run: cargo test -p robius-theme --test windows -- --ignored + - name: Compile the iOS backend + if: matrix.os == 'macos-15' + run: | + rustup target add aarch64-apple-ios aarch64-apple-ios-sim + cargo clippy -p robius-theme --target aarch64-apple-ios -- -D warnings + cargo clippy -p robius-theme --target aarch64-apple-ios-sim -- -D warnings + - name: Compile for a platform without a system theme + if: runner.os == 'Linux' + run: | + rustup target add wasm32-unknown-unknown + cargo clippy -p robius-theme --target wasm32-unknown-unknown -- -D warnings diff --git a/Cargo.lock b/Cargo.lock index da4d5e6..50cb152 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1093,6 +1093,19 @@ dependencies = [ "windows 0.61.3", ] +[[package]] +name = "robius-theme" +version = "0.3.1" +dependencies = [ + "dispatch2", + "jni", + "objc2", + "objc2-foundation", + "objc2-ui-kit", + "robius-android-env", + "zbus", +] + [[package]] name = "robius-web-auth-session" version = "0.3.1" diff --git a/README.md b/README.md index 9cad7b1..40c7eb7 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,9 @@ There's also a [status table](#crate--platform-status-table) that shows what eac * [`robius-speech`](crates/speech/): streams native speech-to-text results and microphone levels on macOS, iOS, Android, and Windows. * Provides recording sessions with partial/final transcripts, graceful stop, and cancellation, independently of the UI toolkit. * Linux doesn't offer any OS-provided speech-to-text functionality, so this crate can't do anything on Linux. +* [`robius-theme`](crates/theme/): gets the system's light or dark theme, and allows you to subscribe and receive a callback whenever it changes. + * This reads the `AppleInterfaceStyle` preference on macOS, the main `UIScreen`'s traits on iOS, `Configuration.uiMode` on Android, the `AppsUseLightTheme` registry value on Windows, and the XDG Settings portal on Linux. + * The system reports each change, so nothing is checked on a timer. On macOS and Windows it has no dependencies at all. * [`robius-web-auth-session`](crates/web_auth_session/): runs an OAuth/SSO login process in the OS's own in-app browser session, and then sends the result back to your app. * Currently this is for iOS only, based on `ASWebAuthenticationSession`. There's no other safe/supported way to do web login on iOS, because otherwise iOS will suspend your app while showing the browser. @@ -53,6 +56,7 @@ Symbol legend: ✅ fully supported · ⚠️ partial, or has issues · 🚧 unde | [`robius-open`](crates/open/) | ✅ `NSWorkspace.openURL` | ✅ `UIApplication.openURL` | ✅ `Intent` (`ACTION_VIEW`) | ✅ `Launcher.LaunchUriAsync` (WinRT) | ✅ `xdg-open` | | [`robius-share`](crates/share/) | ✅ `NSSharingServicePicker` | ✅ `UIActivityViewController` | ✅ `ACTION_SEND` / `ACTION_SEND_MULTIPLE` via `Intent.createChooser` | ✅ WinRT Share UI (`DataTransferManager`) | ✅ XDG portal "Open With" chooser (`OpenURI` / `OpenFile`), or its `SaveFiles` dialog for multi-item payloads; `xdg-open` fallback | | [`robius-speech`](crates/speech/) | ✅ `SFSpeechRecognizer` + `AVAudioEngine` | ✅ `SFSpeechRecognizer` + `AVAudioEngine` | ✅ `SpeechRecognizer` (needs an installed recognition service) | ✅ SAPI dictation (needs an installed speech language) | ❌ no OS-native speech-to-text service exists | +| [`robius-theme`](crates/theme/) | ✅ `AppleInterfaceStyle` preference + `AppleInterfaceThemeChangedNotification` | ✅ `UIScreen` traits + `registerForTraitChanges` (`traitCollectionDidChange` before iOS 17) | ✅ `Configuration.uiMode` + `ComponentCallbacks` | ✅ `AppsUseLightTheme` registry value + `RegNotifyChangeKeyValue` | ✅ XDG Settings portal (`color-scheme`) | | [`robius-web-auth-session`](crates/web_auth_session/) | ❌ not supported | ✅ `ASWebAuthenticationSession` | 🚧 planned (custom chrome tabs) | ❌ not supported | ❌ not supported | @@ -70,6 +74,7 @@ On Android, most crates support API Level 26 and up (Android 8.0), but we're alw | `robius-location` | 1.77 | 26 | | `robius-open` | 1.72 | None | | `robius-share` | 1.77 | 26) | +| `robius-theme` | 1.77 | 26 | | `robius-web-auth-session` | 1.71 | Unsupported | diff --git a/crates/theme/Cargo.toml b/crates/theme/Cargo.toml new file mode 100644 index 0000000..9798e15 --- /dev/null +++ b/crates/theme/Cargo.toml @@ -0,0 +1,52 @@ +[package] +name = "robius-theme" +version.workspace = true +edition.workspace = true +rust-version = "1.77.0" +authors.workspace = true +description = "Rust abstractions for getting the system's light or dark theme and subscribing to changes" +documentation = "https://docs.rs/robius-theme" +homepage.workspace = true +keywords = ["robius", "theme", "dark-mode", "appearance"] +categories.workspace = true +license.workspace = true +repository.workspace = true +readme = "README.md" + +## macOS and Windows need no dependencies: they call a few system functions directly. + +[target.'cfg(target_os = "android")'.dependencies] +jni.workspace = true +robius-android-env.workspace = true + +[target.'cfg(target_os = "ios")'.dependencies] +dispatch2.workspace = true +objc2.workspace = true +objc2-foundation = { workspace = true, features = [ + "NSArray", + "NSEnumerator", + "NSNotification", + "NSSet", + "NSString", +] } +objc2-ui-kit = { workspace = true, features = [ + "UIApplication", + "UIInterface", + "UIResponder", + "UIScene", + "UIScreen", + "UITraitCollection", + "UIView", + "UIWindow", + "UIWindowScene", +] } + +[target.'cfg(target_os = "linux")'.dependencies] +zbus = { workspace = true, features = ["async-io"] } + +## The example needs an `NSApplication`, since macOS only reports changes to apps. +[target.'cfg(target_os = "macos")'.dev-dependencies] +objc2.workspace = true + +[lints.rust] +unsafe_op_in_unsafe_fn = "forbid" diff --git a/crates/theme/README.md b/crates/theme/README.md new file mode 100644 index 0000000..9ab641f --- /dev/null +++ b/crates/theme/README.md @@ -0,0 +1,114 @@ +# robius-theme + +Get the system's appearance setting (light/dark theme) and subscribe to appearance changes, all from Rust without depending on a UI toolkit. + +```rust +use robius_theme::{query, subscribe, Subscription, Theme}; + +fn follow_the_system() -> robius_theme::Result { + let theme = query()?.unwrap_or(Theme::Light); + println!("System appearance: {theme:?}"); + + subscribe(|theme| { + // Runs on a system thread, so send the theme to your UI thread. + println!("System appearance: {theme:?}"); + }) +} +``` + +`Some(Theme::Light)` and `Some(Theme::Dark)` are concrete preferences. +`None` means no preference is available; your application should choose a fallback. +`Err` means that the system couldn't be asked, so your app should keep whichever theme it already has. + +## Receiving updates + +Keep the `Subscription` alive for as long as you want updates, and drop it to stop them. + +The callback receives the current theme first, possibly before `subscribe()` returns, and then each change. +It never receives the same theme twice in a row. + +The system reports each change, so this crate never checks the theme on a timer. +All of your subscriptions share one system subscription per process. + +The callback runs on a thread that the system picks. +That is your main thread on macOS, iOS, and Android, and a background thread on Linux and Windows. +Keep it short and send the theme to your UI thread or event loop. +A call that is already running may still finish after you drop the subscription. + +## Platforms + +| Platform | Where the theme comes from | Requirements | +| --- | --- | --- | +| macOS | ✅ the `AppleInterfaceStyle` preference and `AppleInterfaceThemeChangedNotification` | macOS 11+; updates need an `NSApplication` | +| iOS | ✅ the main `UIScreen`'s `userInterfaceStyle` and UIKit's trait changes | iOS 13+ | +| Android | ✅ `Configuration.uiMode` and the application's `onConfigurationChanged` | API 26+; an Android SDK and JDK to build | +| Windows | ✅ the `AppsUseLightTheme` registry value, or the contrast theme's colors | Windows 10+ | +| Linux | ✅ the XDG Settings portal's `color-scheme` | a desktop that offers it through `xdg-desktop-portal` | +| others | ❌ | `Error::Unsupported` | + +macOS and Windows need no dependencies at all. iOS uses `objc2`, Android uses `jni`, and Linux uses `zbus`. + +### macOS + +Apple documents neither the preference nor the change it posts, but AppKit itself and Apple's own apps rely on both. + +* Your app's own `NSApp.appearance` has no effect on what this crate reports. +* The system only reports changes to processes that have an `NSApplication`. A command-line tool can `query()`, but its callback is only called once. +* On macOS 11 to 13 with the Auto appearance, the preference can be a day out of date after the Mac was shut down across sunrise or sunset. This is a macOS bug that later releases fixed. + +### iOS + +The main screen always has the system's theme, whatever your windows and views override. + +* On iOS 17 and later, changes are reported even while a window has `overrideUserInterfaceStyle` set. +* On iOS 13 to 16, a change that happens while your key window overrides its style is reported when your app next becomes active, or as soon as you call `query()` on the main thread. +* If your `Info.plist` sets `UIUserInterfaceStyle`, the system hides its theme from your app, so this crate reports the value you set there. +* `query()` works on any thread, but before your app's UI has started, a background thread gets `None`. + +### Android + +Android 8 and 9 have a night mode, and the system-wide dark theme arrived in Android 10. This crate reports whichever one the device has. + +* From Android 12, `UiModeManager.setApplicationNightMode(YES/NO)` replaces the system's theme in everything your app can see, so this crate reports the theme you forced. Call it with `MODE_NIGHT_AUTO` to follow the system again, and the callback then receives the system's theme. +* The app's Android context must be set up before you use this crate, which `robius-android-env` does. A Makepad app must depend on `robius-use-makepad` for that. +* Building for Android needs the Android SDK (a platform and build-tools) and a JDK, because a small Java class is compiled into the crate. Set `ANDROID_HOME` and `JAVA_HOME` if they aren't found, and `ANDROID_PLATFORM` or `ANDROID_BUILD_TOOLS_VERSION` to choose versions other than the newest installed ones. + +### Windows + +Windows keeps the app theme in the registry value that this crate reads, and it's the value that the `UISettings` API reads too. + +* While a contrast theme is on, the theme is dark if that theme's window background is dark. +* An app that forces its own title bars or menus to light or dark has no effect on what this crate reports. + +### Linux + +The [Settings portal](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Settings.html) is the one source that every modern desktop shares, and the only one that works inside Flatpak and Snap. +GNOME 42+, KDE Plasma 5.24+, Cinnamon, Xfce 4.18+, MATE, COSMIC, and elementary OS all offer its `color-scheme`, and `darkman` adds it to any other desktop. + +Older desktops only name a theme, so where the portal has no `color-scheme` (or one that the desktop doesn't keep current), this crate reads the desktop's own setting: + +* GNOME before 42 (like Ubuntu 20.04) and KDE Plasma before 5.24: the GTK theme's name, or KDE's window color, through the same portal. +* Cinnamon, MATE and Xfce: their own GTK theme setting. +* Window managers without a desktop (i3, sway, Openbox, LXDE and others), and systems without the portal: GTK's `settings.ini`. + +A theme whose name has "dark" in it (like `Yaru-dark`, but not `Arc-Darker`) counts as dark. +Changes to all of these are followed too, but only on desktops that need them: on a current desktop, none of this runs. + +* GNOME 42+ reports its default light style as no preference (`None`). +* `query()` can wait up to a second while the desktop starts the portal. Once a subscription has received the theme, `query()` answers from memory. + +## Following the system in an app with its own theme setting + +Most apps let the user choose Light, Dark, or Auto. For Auto, your app should stop forcing a theme on the parts that the system draws for it: +that is required on Android 12+ (see above), and it lets title bars and keyboards change together with the system on macOS and iOS. +In Makepad, that is `NativeAppearance::System`. + +When the user goes back to Auto, call `query()` again for the theme to show right away. + +## Example + +This prints the system theme and then each change: + +```sh +cargo run -p robius-theme --example subscribe +``` diff --git a/crates/theme/build.rs b/crates/theme/build.rs new file mode 100644 index 0000000..e7df1e9 --- /dev/null +++ b/crates/theme/build.rs @@ -0,0 +1,107 @@ +//! Compiles `NativeTheme.java` into the DEX file that `src/android.rs` embeds. +//! +//! That takes an Android SDK and a JDK. `ANDROID_HOME`, `ANDROID_PLATFORM`, +//! `ANDROID_BUILD_TOOLS_VERSION` and `JAVA_HOME` say which ones to use. Without +//! them it's the SDK in its default place, the newest platform and build tools +//! in it, and the system's JDK. + +use std::{ + env::{self, consts::EXE_SUFFIX}, + fs, + path::{Path, PathBuf}, + process::Command, +}; + +const JAVA_FILE: &str = "java/dev/robius/theme/NativeTheme.java"; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("android") { + return; + } + println!("cargo:rerun-if-changed={JAVA_FILE}"); + + let sdk = var("ANDROID_HOME").or_else(|| var("ANDROID_SDK_ROOT")).or_else(default_sdk).unwrap_or_default(); + assert!(sdk.is_dir(), "no Android SDK at `{}`: set ANDROID_HOME", sdk.display()); + let android_jar = installed(&sdk.join("platforms"), "ANDROID_PLATFORM", "android.jar"); + let d8_jar = installed(&sdk.join("build-tools"), "ANDROID_BUILD_TOOLS_VERSION", "lib/d8.jar"); + let jdk = jdk().expect("no JDK found: set JAVA_HOME"); + let tool = |name: &str| jdk.join(format!("{name}{EXE_SUFFIX}")); + + let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); + let classes = out_dir.join("classes"); + fs::create_dir_all(&classes).unwrap(); + // Every d8 can read Java 8 class files, whichever JDK compiles them. + let mut javac = Command::new(tool("javac")); + javac.args(["-source", "8", "-target", "8", "-Xlint:-options", "-classpath"]).arg(&android_jar); + run(javac.arg("-d").arg(&classes).arg(JAVA_FILE)); + let mut d8 = Command::new(tool("java")); + d8.arg("-cp").arg(d8_jar).args(["com.android.tools.r8.D8", "--min-api", "26", "--lib"]).arg(&android_jar); + run(d8.arg("--output").arg(&out_dir).arg(classes.join("dev/robius/theme/NativeTheme.class"))); +} + +/// Reads a variable, and has cargo run this script again when it changes. An empty one counts as unset. +fn var(name: &str) -> Option { + println!("cargo:rerun-if-env-changed={name}"); + env::var_os(name).filter(|value| !value.is_empty()).map(PathBuf::from) +} + +/// Where Android Studio puts the SDK. +fn default_sdk() -> Option { + match env::consts::OS { + "macos" => Some(var("HOME")?.join("Library/Android/sdk")), + "windows" => Some(var("LOCALAPPDATA")?.join("Android/Sdk")), + _ => Some(var("HOME")?.join("Android/Sdk")), + } +} + +/// The `file` of the version that `variable` names, or else of the newest version in `dir` that has one. +fn installed(dir: &Path, variable: &str, file: &str) -> PathBuf { + let Some(version) = var(variable) else { + return newest(dir, file).unwrap_or_else(|| panic!("nothing in `{}` has {file}", dir.display())); + }; + let path = dir.join(version).join(file); + assert!(path.is_file(), "`{}` not found: check {variable}", path.display()); + path +} + +fn newest(dir: &Path, file: &str) -> Option { + let names = fs::read_dir(dir).ok()?.filter_map(|entry| entry.ok()?.file_name().into_string().ok()); + let newest = names.filter(|name| dir.join(name).join(file).is_file()).max_by_key(|name| rank(name))?; + Some(dir.join(newest).join(file)) +} + +/// Orders names like `android-33`, `android-33-ext4`, `android-36.1`, `36.0.0-rc5` and `36.0.0`. +/// A release comes after its own previews, and before its extensions. +fn rank(name: &str) -> (Vec, bool, u32) { + let name = name.strip_prefix("android-").unwrap_or(name); + let (version, suffix) = name.split_once('-').unwrap_or((name, "")); + let number = |digits: &str| digits.parse::().ok(); + let is_release = suffix.is_empty() || suffix.starts_with("ext"); + let suffix = number(suffix.trim_start_matches(char::is_alphabetic)).unwrap_or(0); + (version.split('.').filter_map(number).collect(), is_release, suffix) +} + +/// The directory that has `javac` and `java`. +fn jdk() -> Option { + if let Some(home) = var("JAVA_HOME") { + return Some(home.join("bin")); + } + // On macOS the ones in `/usr/bin` may be stubs that open an installer, so the system is asked for a JDK. + let is_macos = cfg!(target_os = "macos"); + let java_home = if is_macos { Command::new("/usr/libexec/java_home").output().ok() } else { None }; + if let Some(output) = java_home.filter(|output| output.status.success()) { + return Some(Path::new(String::from_utf8_lossy(&output.stdout).trim()).join("bin")); + } + let javac = format!("javac{EXE_SUFFIX}"); + let is_stub_dir = |dir: &Path| is_macos && dir == Path::new("/usr/bin"); + env::split_paths(&var("PATH")?).find(|dir| dir.join(&javac).is_file() && !is_stub_dir(dir)) +} + +/// Runs a JDK tool, and fails the build with what it printed if it fails. +fn run(command: &mut Command) { + let tool = Path::new(command.get_program()).display().to_string(); + let output = command.output().unwrap_or_else(|error| panic!("could not run `{tool}`: {error}")); + let printed = [output.stdout, output.stderr].concat(); + assert!(output.status.success(), "`{tool}` failed:\n{}", String::from_utf8_lossy(&printed)); +} diff --git a/crates/theme/examples/subscribe.rs b/crates/theme/examples/subscribe.rs new file mode 100644 index 0000000..e7170b2 --- /dev/null +++ b/crates/theme/examples/subscribe.rs @@ -0,0 +1,30 @@ +//! Prints the system theme, and then each change until you press Ctrl+C. + +fn main() -> robius_theme::Result<()> { + println!("Right now: {:?}", robius_theme::query()?); + let _subscription = robius_theme::subscribe(|theme| println!("Subscribed: {theme:?}"))?; + run(); + Ok(()) +} + +/// macOS only reports changes to an app that is running its event loop. +#[cfg(target_os = "macos")] +fn run() { + use objc2::{class, msg_send, runtime::AnyObject}; + + #[link(name = "AppKit", kind = "framework")] + extern "C" {} + + // SAFETY: this is the main thread, and both messages take no arguments. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let _: () = msg_send![app, run]; + } +} + +#[cfg(not(target_os = "macos"))] +fn run() { + loop { + std::thread::park(); + } +} diff --git a/crates/theme/java/dev/robius/theme/NativeTheme.java b/crates/theme/java/dev/robius/theme/NativeTheme.java new file mode 100644 index 0000000..6743f04 --- /dev/null +++ b/crates/theme/java/dev/robius/theme/NativeTheme.java @@ -0,0 +1,17 @@ +package dev.robius.theme; + +import android.content.ComponentCallbacks; +import android.content.res.Configuration; + +/** Passes the `uiMode` of each new configuration to `changed` in `src/android.rs`. */ +public final class NativeTheme implements ComponentCallbacks { + private static native void changed(int uiMode); + + @Override + public void onConfigurationChanged(Configuration configuration) { + changed(configuration.uiMode); + } + + @Override + public void onLowMemory() {} +} diff --git a/crates/theme/src/android.rs b/crates/theme/src/android.rs new file mode 100644 index 0000000..6b85692 --- /dev/null +++ b/crates/theme/src/android.rs @@ -0,0 +1,139 @@ +//! Android keeps the theme in the night bits of `Configuration.uiMode`, and gives +//! each new configuration to the `ComponentCallbacks` that are registered with +//! the `Application`, on the main thread. +//! +//! `NativeTheme.java` is one of those. `build.rs` compiles it into a DEX file, +//! which is embedded here and loaded by the first subscription. It then stays +//! registered for the life of the process. +//! +//! The configuration is the app's own. Since Android 12, an app that has called +//! `UiModeManager.setApplicationNightMode` gets the mode it chose, not the system's. + +use std::{ + ffi::c_void, + panic::{catch_unwind, resume_unwind, AssertUnwindSafe}, + sync::{Mutex, PoisonError}, +}; + +use jni::{ + objects::{JClass, JObject, JValue}, + sys::jint, + JNIEnv, NativeMethod, +}; + +use crate::{Error, Result, Theme}; + +type JniResult = jni::errors::Result; + +/// `NativeTheme.java`, as compiled by `build.rs`. +const DEX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/classes.dex")); + +pub(crate) fn query() -> Result> { + with_context(|env, context| { + let application = application(env, context)?; + let resources = env.call_method(application, "getResources", "()Landroid/content/res/Resources;", &[])?.l()?; + let configuration = env.call_method(resources, "getConfiguration", "()Landroid/content/res/Configuration;", &[])?.l()?; + Ok(theme(env.get_field(configuration, "uiMode", "I")?.i()?)) + }) +} + +pub(crate) fn read_now() -> Option> { + query().ok() +} + +pub(crate) fn start() -> Result<()> { + static IS_STARTED: Mutex = Mutex::new(false); + let mut is_started = IS_STARTED.lock().unwrap_or_else(PoisonError::into_inner); + if !*is_started { + with_context(register)?; + *is_started = true; + } + Ok(()) +} + +/// Loads `NativeTheme` and registers one with the `Application`, which keeps it from then on. +fn register(env: &mut JNIEnv<'_>, context: &JObject<'_>) -> JniResult<()> { + let application = application(env, context)?; + let dex = env.byte_array_from_slice(DEX)?; + let dex = env.call_static_method("java/nio/ByteBuffer", "wrap", "([B)Ljava/nio/ByteBuffer;", &[JValue::Object(&dex)])?.l()?; + // With a null parent, Android 8 and 9 can't resolve even `java.lang.Object`. + let parent = env.call_static_method("java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", &[])?.l()?; + let loader = env.new_object( + "dalvik/system/InMemoryDexClassLoader", + "(Ljava/nio/ByteBuffer;Ljava/lang/ClassLoader;)V", + &[JValue::Object(&dex), JValue::Object(&parent)], + )?; + let name = env.new_string("dev.robius.theme.NativeTheme")?; + let class = env.call_method(loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", &[JValue::Object(&name)])?.l()?; + let class = JClass::from(class); + let changed = NativeMethod { name: "changed".into(), sig: "(I)V".into(), fn_ptr: changed as *mut c_void }; + env.register_native_methods(&class, &[changed])?; + let callbacks = env.new_object(&class, "()V", &[])?; + let callbacks = [JValue::Object(&callbacks)]; + env.call_method(application, "registerComponentCallbacks", "(Landroid/content/ComponentCallbacks;)V", &callbacks)?; + Ok(()) +} + +/// `NativeTheme.onConfigurationChanged` calls this on the main thread, whatever it was that changed. +extern "system" fn changed(_env: JNIEnv<'_>, _class: JClass<'_>, ui_mode: jint) { + crate::refresh(|| theme(ui_mode)); +} + +/// The night bits are `UI_MODE_NIGHT_NO` or `UI_MODE_NIGHT_YES`, or else undefined. +fn theme(ui_mode: jint) -> Option { + match ui_mode & 0x30 { + 0x10 => Some(Theme::Light), + 0x20 => Some(Theme::Dark), + _ => None, + } +} + +/// The `Application`, which outlives every `Activity` and has none of their overrides. +fn application<'local>(env: &mut JNIEnv<'local>, context: &JObject<'_>) -> JniResult> { + env.call_method(context, "getApplicationContext", "()Landroid/content/Context;", &[])?.l() +} + +/// Runs `run` with the JNI environment and the host app's `Context`, and frees the references it makes. +fn with_context(run: impl FnOnce(&mut JNIEnv<'_>, &JObject<'_>) -> JniResult) -> Result { + let failed = |error| Error::Unavailable(format!("a JNI call failed: {error}")); + let mut was_called = false; + let outcome = catch_unwind(AssertUnwindSafe(|| { + robius_android_env::with_activity(|env, context| { + was_called = true; + if context.is_null() { + return Err(Error::Unavailable("the app has no Android context yet".into())); + } + // An exception that was already pending is the caller's: it stays, and JNI can't be used. + if env.exception_check().map_err(failed)? { + return Err(Error::Unavailable("a Java exception is pending".into())); + } + let result = env.with_local_frame(16, |env| run(env, context)); + if result.is_err() { + // Whatever is pending now is ours, so the caller mustn't be left with it. + let _ = env.exception_clear(); + } + result.map_err(failed) + }) + })); + match outcome { + Ok(result) => result.map_err(failed)?, + // Before it calls us, only the `ndk-context` backend can panic: the app gave it no context. + Err(_) if !was_called => Err(Error::Unavailable("the app has not set its Android context".into())), + Err(panic) => resume_unwind(panic), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_night_bits_decide_the_theme() { + for other_bits in [0, 0x01, 0x0f, 0xc0] { + assert_eq!(theme(other_bits | 0x10), Some(Theme::Light)); + assert_eq!(theme(other_bits | 0x20), Some(Theme::Dark)); + assert_eq!(theme(other_bits), None); + assert_eq!(theme(other_bits | 0x30), None); + } + } +} diff --git a/crates/theme/src/apple/ios.rs b/crates/theme/src/apple/ios.rs new file mode 100644 index 0000000..ba0c114 --- /dev/null +++ b/crates/theme/src/apple/ios.rs @@ -0,0 +1,203 @@ +//! iOS keeps the system theme in the main screen's traits, which a window or +//! scene with its own style doesn't change. UIKit reports a change to each +//! window scene (iOS 17 and later) or to a view in a window (before that), and +//! a scene hears of it before the screen has the new theme. So every report +//! only schedules a read of the screen on a later pass of the main run loop. +//! +//! Only the main thread may read the screen. Other threads get the theme that +//! subscribers were last given, or else the copy of the screen's traits that +//! UIKit keeps for them, which is unset until the app has used the screen. + +use std::{ + ptr, + sync::{ + atomic::{AtomicPtr, Ordering}, + Once, + }, +}; + +use dispatch2::DispatchQueue; +use objc2::{ + define_class, msg_send, + rc::{autoreleasepool, Retained}, + runtime::{AnyClass, AnyObject}, + sel, ClassType, MainThreadMarker, MainThreadOnly, +}; +use objc2_foundation::{NSArray, NSNotification, NSNotificationCenter}; +use objc2_ui_kit::{ + UIApplication, UIApplicationDidBecomeActiveNotification, UISceneWillConnectNotification, UIScreen, UITraitCollection, + UITraitEnvironment, UIUserInterfaceStyle, UIView, UIWindow, UIWindowDidBecomeKeyNotification, UIWindowScene, +}; + +use crate::{Result, Theme}; + +/// The object that receives the system's updates, once the main thread has installed it. +static UPDATES: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + +pub(crate) fn query() -> Result> { + let Some(mtm) = MainThreadMarker::new() else { + return Ok(crate::latest().unwrap_or_else(read_off_main)); + }; + let theme = read(mtm); + // SAFETY: the object is never released, and only the main thread uses it. + if let Some(updates) = unsafe { UPDATES.load(Ordering::Relaxed).as_ref() } { + // Before iOS 17, a window with its own style keeps changes from us. + if crate::latest() != Some(theme) { + updates.check_later(); + } + } + Ok(theme) +} + +pub(crate) fn read_now() -> Option> { + MainThreadMarker::new().map(read) +} + +pub(crate) fn start() -> Result<()> { + static START: Once = Once::new(); + START.call_once(|| match MainThreadMarker::new() { + Some(mtm) => install(mtm), + None => DispatchQueue::main().exec_async(|| { + if let Some(mtm) = MainThreadMarker::new() { + install(mtm); + } + }), + }); + Ok(()) +} + +fn read(mtm: MainThreadMarker) -> Option { + // Its replacement needs a window or a scene, and there may be none yet. + #[allow(deprecated)] + let traits = UIScreen::mainScreen(mtm).traitCollection(); + theme_of(&traits) +} + +fn read_off_main() -> Option { + autoreleasepool(|_| { + // SAFETY: each thread has its own current traits. + let traits = unsafe { UITraitCollection::currentTraitCollection() }; + theme_of(&traits) + }) +} + +fn theme_of(traits: &UITraitCollection) -> Option { + // SAFETY: traits never change once made, so any thread may read them. + match unsafe { traits.userInterfaceStyle() } { + UIUserInterfaceStyle::Light => Some(Theme::Light), + UIUserInterfaceStyle::Dark => Some(Theme::Dark), + _ => None, + } +} + +/// The trait to register for, which exists on iOS 17 and later. +fn style_trait() -> Option<&'static AnyClass> { + AnyClass::get(c"UITraitUserInterfaceStyle") +} + +/// Makes the object that receives the system's updates. It's never removed. +fn install(mtm: MainThreadMarker) { + let updates = ThemeUpdates::alloc(mtm).set_ivars(()); + // SAFETY: `init` is how UIView makes a view of no size. + let updates: Retained = unsafe { msg_send![super(updates), init] }; + updates.setHidden(true); + updates.setUserInteractionEnabled(false); + + let center = NSNotificationCenter::defaultCenter(); + // SAFETY: each selector is a method of `updates` that takes the one object the center passes. + unsafe { + center.addObserver_selector_name_object( + &updates, + sel!(robiusThemeMayHaveChanged:), + Some(UIApplicationDidBecomeActiveNotification), + None, + ); + let (selector, name) = match style_trait() { + Some(_) => (sel!(robiusThemeSceneWillConnect:), UISceneWillConnectNotification), + None => (sel!(robiusThemeWindowDidBecomeKey:), UIWindowDidBecomeKeyNotification), + }; + center.addObserver_selector_name_object(&updates, selector, Some(name), None); + } + // SAFETY: `sharedApplication` returns the app, or nil before `UIApplicationMain`. + let app: Option> = unsafe { msg_send![UIApplication::class(), sharedApplication] }; + if let Some(app) = app { + for scene in app.connectedScenes().iter() { + updates.follow(&scene); + } + } + // Subscribers still need their first theme if `read_now` couldn't give it. + updates.check_later(); + UPDATES.store(Retained::into_raw(updates), Ordering::Relaxed); +} + +define_class!( + // SAFETY: UIView may be subclassed, the one override calls it, and nothing here implements `Drop`. + #[unsafe(super(UIView))] + #[thread_kind = MainThreadOnly] + struct ThemeUpdates; + + impl ThemeUpdates { + /// A scene's theme changed (iOS 17 and later), or the app became active. + #[unsafe(method(robiusThemeMayHaveChanged:))] + fn may_have_changed(&self, _: Option<&AnyObject>) { + self.check_later(); + } + + /// Before iOS 17, the window tells its views like this that any trait changed. + #[unsafe(method(traitCollectionDidChange:))] + fn trait_collection_did_change(&self, previous: Option<&UITraitCollection>) { + // SAFETY: this passes UIView's own method the argument it was meant to get. + let _: () = unsafe { msg_send![super(self), traitCollectionDidChange: previous] }; + self.check_later(); + } + + #[unsafe(method(robiusThemeSceneWillConnect:))] + fn scene_will_connect(&self, event: &NSNotification) { + if let Some(scene) = event.object() { + self.follow(&scene); + } + } + + #[unsafe(method(robiusThemeWindowDidBecomeKey:))] + fn window_did_become_key(&self, event: &NSNotification) { + if let Some(window) = event.object().and_then(|window| window.downcast::().ok()) { + window.addSubview(self); + } + } + + #[unsafe(method(robiusThemeCheck))] + fn check(&self) { + crate::refresh(|| read(self.mtm())); + } + } +); + +impl ThemeUpdates { + /// Starts receiving the changes that `scene` is told about. + fn follow(&self, scene: &AnyObject) { + let Some(scene) = scene.downcast_ref::() else { + return; + }; + let Some(style) = style_trait() else { + // Before iOS 17, only a view in a window is told, so sit in the key one. + for window in scene.windows().iter().filter(|window| window.isKeyWindow()) { + window.addSubview(self); + } + return; + }; + let style: &AnyObject = style.as_ref(); + let traits = NSArray::from_slice(&[style]); + // SAFETY: a scene has this method wherever the trait exists, and passes the action one object. + let _: Option> = unsafe { + msg_send![scene, registerForTraitChanges: &*traits, withTarget: self, action: sel!(robiusThemeMayHaveChanged:)] + }; + } + + /// Reads the screen on a later pass of the main run loop, when it has the new theme. + fn check_later(&self) { + // SAFETY: `robiusThemeCheck` takes no arguments and returns nothing. + let _: () = unsafe { + msg_send![self, performSelectorOnMainThread: sel!(robiusThemeCheck), withObject: None::<&AnyObject>, waitUntilDone: false] + }; + } +} diff --git a/crates/theme/src/apple/macos.rs b/crates/theme/src/apple/macos.rs new file mode 100644 index 0000000..b531597 --- /dev/null +++ b/crates/theme/src/apple/macos.rs @@ -0,0 +1,126 @@ +//! macOS mirrors its theme in the `AppleInterfaceStyle` preference and posts +//! `AppleInterfaceThemeChangedNotification` after each change. Apple documents +//! neither, but AppKit and Apple's own apps depend on both. +//! +//! An app's own `NSApp.appearance` doesn't affect either one. The system only +//! posts the change inside processes that are connected to the window server, +//! which every app with an `NSApplication` is. + +use std::{ + ffi::{c_char, c_void, CStr}, + ptr, + sync::Once, +}; + +use crate::{Result, Theme}; + +type CFStringRef = *const c_void; +type CFTypeRef = *const c_void; +type CFNotificationCallback = + extern "C" fn(center: *const c_void, token: *mut c_void, name: CFStringRef, object: *const c_void, user_info: *const c_void); + +/// `kCFStringEncodingUTF8` +const UTF8: u32 = 0x0800_0100; +/// `CFNotificationSuspensionBehaviorDeliverImmediately`: don't wait until the app is active. +const DELIVER_IMMEDIATELY: isize = 4; + +#[link(name = "CoreFoundation", kind = "framework")] +#[allow(non_upper_case_globals)] +extern "C" { + static kCFPreferencesAnyApplication: CFStringRef; + static kCFPreferencesCurrentUser: CFStringRef; + static kCFPreferencesAnyHost: CFStringRef; + fn CFPreferencesCopyValue(key: CFStringRef, application: CFStringRef, user: CFStringRef, host: CFStringRef) -> CFTypeRef; + fn CFStringCreateWithCString(allocator: *const c_void, text: *const c_char, encoding: u32) -> CFStringRef; + fn CFStringGetTypeID() -> usize; + fn CFGetTypeID(value: CFTypeRef) -> usize; + fn CFEqual(a: CFTypeRef, b: CFTypeRef) -> u8; + fn CFRelease(value: CFTypeRef); + fn CFNotificationCenterGetDistributedCenter() -> *const c_void; + fn CFNotificationCenterAddObserver( + center: *const c_void, + token: *const c_void, + callback: CFNotificationCallback, + name: CFStringRef, + object: *const c_void, + suspension_behavior: isize, + ); +} + +pub(crate) fn query() -> Result> { + Ok(Some(read())) +} + +pub(crate) fn read_now() -> Option> { + Some(Some(read())) +} + +pub(crate) fn start() -> Result<()> { + static START: Once = Once::new(); + START.call_once(|| { + // Only its address is used, to name this registration. + static TOKEN: u8 = 0; + // SAFETY: the name is a valid string that the center copies, and the + // callback is a plain function that stays registered for good. + unsafe { + let name = cf_string(c"AppleInterfaceThemeChangedNotification"); + CFNotificationCenterAddObserver( + CFNotificationCenterGetDistributedCenter(), + ptr::addr_of!(TOKEN).cast(), + on_change, + name, + ptr::null(), + DELIVER_IMMEDIATELY, + ); + CFRelease(name); + } + }); + Ok(()) +} + +/// The system calls this on the main thread, after it has saved the new theme. +extern "C" fn on_change(_: *const c_void, _: *mut c_void, _: CFStringRef, _: *const c_void, _: *const c_void) { + crate::refresh(|| Some(read())); +} + +/// The system itself only treats the string `Dark` as dark; anything else, or nothing, is light. +fn read() -> Theme { + // SAFETY: the three domain constants live as long as the process, and + // everything created or copied here is released exactly once. + let is_dark = unsafe { + let key = cf_string(c"AppleInterfaceStyle"); + let value = CFPreferencesCopyValue(key, kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); + CFRelease(key); + if value.is_null() { + return Theme::Light; + } + let dark = cf_string(c"Dark"); + let is_dark = CFGetTypeID(value) == CFStringGetTypeID() && CFEqual(value, dark) != 0; + CFRelease(dark); + CFRelease(value); + is_dark + }; + if is_dark { + Theme::Dark + } else { + Theme::Light + } +} + +/// Makes a string that the caller must release. +fn cf_string(text: &CStr) -> CFStringRef { + // SAFETY: `text` is a valid NUL-terminated UTF-8 string, which is copied. + unsafe { CFStringCreateWithCString(ptr::null(), text.as_ptr(), UTF8) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_the_same_theme_from_any_thread() { + let theme = read(); + assert_eq!(std::thread::spawn(read).join().unwrap(), theme); + assert_eq!(query(), Ok(Some(theme))); + } +} diff --git a/crates/theme/src/apple/mod.rs b/crates/theme/src/apple/mod.rs new file mode 100644 index 0000000..ff65f88 --- /dev/null +++ b/crates/theme/src/apple/mod.rs @@ -0,0 +1,9 @@ +#[cfg(target_os = "ios")] +mod ios; +#[cfg(target_os = "macos")] +mod macos; + +#[cfg(target_os = "ios")] +pub(crate) use ios::{query, read_now, start}; +#[cfg(target_os = "macos")] +pub(crate) use macos::{query, read_now, start}; diff --git a/crates/theme/src/lib.rs b/crates/theme/src/lib.rs new file mode 100644 index 0000000..c7f6beb --- /dev/null +++ b/crates/theme/src/lib.rs @@ -0,0 +1,373 @@ +//! Get the system's light or dark theme, and subscribe to changes. +//! +//! * [`query`] returns the current theme. +//! * [`subscribe`] calls you back with the current theme, and again each time +//! it changes, until you drop the returned [`Subscription`]. +//! +//! The system reports each change, so nothing here runs a timer or checks the +//! theme on a schedule. The crate doesn't depend on any UI toolkit. +//! +//! ```no_run +//! use robius_theme::Theme; +//! +//! let theme = robius_theme::query()?.unwrap_or(Theme::Light); +//! let _subscription = robius_theme::subscribe(|theme| { +//! // This runs on a system thread, so send the theme to your UI thread. +//! println!("System theme: {theme:?}"); +//! })?; +//! # Ok::<(), robius_theme::Error>(()) +//! ``` +//! +//! The callback runs on whichever thread the system reports changes on, which +//! is often the app's main thread, and its first call can happen inside +//! [`subscribe`] itself. So keep it short, and send the theme on to your UI thread. +//! +//! Each platform has one system-wide source for the theme, and one subscription +//! to it for the whole process, shared by every [`Subscription`]. The README +//! lists those sources and what each platform needs from your app. + +use std::{ + fmt, + panic::{catch_unwind, AssertUnwindSafe}, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Mutex, MutexGuard, PoisonError, + }, +}; + +#[cfg_attr(target_os = "android", path = "android.rs")] +#[cfg_attr(any(target_os = "ios", target_os = "macos"), path = "apple/mod.rs")] +#[cfg_attr(target_os = "linux", path = "linux/mod.rs")] +#[cfg_attr(target_os = "windows", path = "windows.rs")] +#[cfg_attr( + not(any( + target_os = "android", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "windows", + )), + path = "unsupported.rs" +)] +mod sys; + +/// The system's light or dark theme. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Theme { + Light, + Dark, +} + +/// Why the system theme couldn't be read or subscribed to. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Error { + /// This platform has no system theme that we know how to read. + Unsupported, + /// The system couldn't be asked right now. The message says why. + Unavailable(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Unsupported => f.write_str("the system theme is not supported on this platform"), + Self::Unavailable(reason) => write!(f, "the system theme is unavailable: {reason}"), + } + } +} + +impl std::error::Error for Error {} + +pub type Result = std::result::Result; + +/// Returns the current system theme, or `Ok(None)` if the system has no preference. +/// +/// Any thread can call this. On Linux it can wait up to a second for the desktop to answer. +pub fn query() -> Result> { + sys::query() +} + +/// Calls `on_change` with the current system theme, and again each time it changes. +/// +/// Updates stop once the returned [`Subscription`] is dropped. +pub fn subscribe(on_change: impl FnMut(Option) + Send + 'static) -> Result { + UPDATES.subscribe(Box::new(on_change), sys::start, sys::read_now) +} + +/// Keeps a [`subscribe`] callback receiving updates until it's dropped. +/// +/// A call that is already running on another thread may still finish after the drop. +#[must_use = "updates stop when the subscription is dropped"] +pub struct Subscription { + updates: &'static Updates, + subscriber: Arc, +} + +impl Drop for Subscription { + fn drop(&mut self) { + self.subscriber.is_active.store(false, Ordering::Release); + lock(&self.updates.0).subscribers.retain(|other| !Arc::ptr_eq(other, &self.subscriber)); + } +} + +impl fmt::Debug for Subscription { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Subscription").finish_non_exhaustive() + } +} + +// A subscription must be usable from any thread on every platform. +const _: fn() = || { + fn assert_send_sync() {} + assert_send_sync::(); +}; + +/// Gives every subscriber the theme that `read` returns, if it's a new one. +/// `read` runs while other reads are held off, so the newest theme always wins. +#[allow(dead_code)] // Not every platform has a backend that calls this. +pub(crate) fn refresh(read: impl FnOnce() -> Option) { + UPDATES.refresh(read); +} + +/// The theme that subscribers were last given, if there is one yet. +#[allow(dead_code)] // Only some backends need this. +pub(crate) fn latest() -> Option> { + lock(&UPDATES.0).latest +} + +static UPDATES: Updates = Updates::new(); + +type OnChange = Box) + Send>; + +/// The theme and its subscribers, shared by the whole process. +struct Updates(Mutex); + +struct State { + /// The newest theme, once the system has told us one. + latest: Option>, + /// How many themes there have been, so that an older one never follows a newer one. + version: u64, + subscribers: Vec>, +} + +struct Subscriber { + is_active: AtomicBool, + delivery: Mutex, +} + +struct Delivery { + /// The version and theme that `on_change` was last called with. + version: u64, + theme: Option>, + on_change: OnChange, +} + +impl Updates { + const fn new() -> Self { + Self(Mutex::new(State { latest: None, version: 0, subscribers: Vec::new() })) + } + + /// `start` begins the platform's updates, and `read_now` returns the theme + /// if it can be read without waiting. + fn subscribe( + &'static self, + on_change: OnChange, + start: impl FnOnce() -> Result<()>, + read_now: impl FnOnce() -> Option>, + ) -> Result { + let subscriber = Arc::new(Subscriber { + is_active: AtomicBool::new(true), + delivery: Mutex::new(Delivery { version: 0, theme: None, on_change }), + }); + let (version, latest, recipients) = { + let mut state = lock(&self.0); + // Start before reading, so that a change between the two still reaches us. + start()?; + state.subscribers.push(subscriber.clone()); + if state.latest.is_some() { + (state.version, state.latest, vec![subscriber.clone()]) + } else { + // Earlier subscribers haven't been given a theme yet either. + state.latest = read_now(); + state.version += u64::from(state.latest.is_some()); + (state.version, state.latest, state.subscribers.clone()) + } + }; + if let Some(theme) = latest { + for recipient in &recipients { + recipient.deliver(version, theme); + } + } + Ok(Subscription { updates: self, subscriber }) + } + + fn refresh(&self, read: impl FnOnce() -> Option) { + let (version, theme, subscribers) = { + let mut state = lock(&self.0); + let theme = read(); + if state.latest == Some(theme) { + return; + } + state.latest = Some(theme); + state.version += 1; + (state.version, theme, state.subscribers.clone()) + }; + for subscriber in &subscribers { + subscriber.deliver(version, theme); + } + } +} + +impl Subscriber { + fn deliver(&self, version: u64, theme: Option) { + let mut delivery = lock(&self.delivery); + if delivery.version >= version || !self.is_active.load(Ordering::Acquire) { + return; + } + delivery.version = version; + if delivery.theme.replace(theme) == Some(theme) { + return; + } + // A panic in the app's callback must not unwind into the system code that called us. + let _ = catch_unwind(AssertUnwindSafe(|| (delivery.on_change)(theme))); + } +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc::{channel, Receiver}; + + use Theme::{Dark, Light}; + + fn updates() -> &'static Updates { + Box::leak(Box::new(Updates::new())) + } + + /// Subscribes with a callback that records every theme it's given. + fn subscribe(updates: &'static Updates, now: Option>) -> (Subscription, Receiver>) { + let (sender, themes) = channel(); + let on_change = Box::new(move |theme| sender.send(theme).unwrap()); + (updates.subscribe(on_change, || Ok(()), || now).unwrap(), themes) + } + + fn received(themes: &Receiver>) -> Vec> { + themes.try_iter().collect() + } + + #[test] + fn gives_the_current_theme_then_each_change_once() { + let updates = updates(); + let (_subscription, themes) = subscribe(updates, Some(Some(Dark))); + assert_eq!(received(&themes), [Some(Dark)]); + updates.refresh(|| Some(Dark)); + assert_eq!(received(&themes), []); + updates.refresh(|| Some(Light)); + updates.refresh(|| None); + updates.refresh(|| None); + assert_eq!(received(&themes), [Some(Light), None]); + } + + #[test] + fn a_later_subscriber_gets_the_latest_theme_without_reading_again() { + let updates = updates(); + let (_first, _) = subscribe(updates, Some(Some(Light))); + updates.refresh(|| Some(Dark)); + let (sender, themes) = channel(); + let on_change = Box::new(move |theme| sender.send(theme).unwrap()); + let _second = updates.subscribe(on_change, || Ok(()), || panic!("the theme is already known")).unwrap(); + assert_eq!(received(&themes), [Some(Dark)]); + } + + #[test] + fn a_theme_that_arrives_later_reaches_every_subscriber() { + let updates = updates(); + let (_first, first) = subscribe(updates, None); + let (_second, second) = subscribe(updates, None); + assert_eq!(received(&first), []); + updates.refresh(|| Some(Dark)); + assert_eq!(received(&first), [Some(Dark)]); + assert_eq!(received(&second), [Some(Dark)]); + } + + #[test] + fn a_theme_read_by_one_subscriber_reaches_those_still_waiting() { + let updates = updates(); + let (_first, first) = subscribe(updates, None); + let (_second, second) = subscribe(updates, Some(None)); + assert_eq!(received(&first), [None]); + assert_eq!(received(&second), [None]); + // The platform then reports the same theme, which isn't a change. + updates.refresh(|| None); + assert_eq!(received(&first), []); + } + + #[test] + fn dropping_a_subscription_stops_only_its_updates() { + let updates = updates(); + let (first, first_themes) = subscribe(updates, Some(Some(Light))); + let (_second, second_themes) = subscribe(updates, Some(Some(Light))); + drop(first); + updates.refresh(|| Some(Dark)); + assert_eq!(received(&first_themes), [Some(Light)]); + assert_eq!(received(&second_themes), [Some(Light), Some(Dark)]); + assert_eq!(lock(&updates.0).subscribers.len(), 1); + } + + #[test] + fn a_failed_start_subscribes_nothing() { + let updates = updates(); + let on_change = Box::new(|_| panic!("there is nothing to deliver")); + let result = updates.subscribe(on_change, || Err(Error::Unsupported), || Some(Some(Dark))); + assert_eq!(result.unwrap_err(), Error::Unsupported); + assert!(lock(&updates.0).subscribers.is_empty()); + assert_eq!(lock(&updates.0).latest, None); + } + + #[test] + fn a_panicking_callback_stops_nothing() { + let updates = updates(); + let on_change = Box::new(|theme| assert_ne!(theme, Some(Dark), "expected by this test")); + let _panics_on_dark = updates.subscribe(on_change, || Ok(()), || Some(Some(Light))).unwrap(); + let (_other, themes) = subscribe(updates, None); + updates.refresh(|| Some(Dark)); + updates.refresh(|| Some(Light)); + assert_eq!(received(&themes), [Some(Light), Some(Dark), Some(Light)]); + } + + #[test] + fn a_callback_can_drop_its_own_subscription() { + let updates = updates(); + let slot = Arc::new(Mutex::new(None::)); + let (own, sender) = (slot.clone(), channel()); + let on_change = Box::new(move |theme| { + sender.0.send(theme).unwrap(); + if theme == Some(Dark) { + own.lock().unwrap().take(); + } + }); + *slot.lock().unwrap() = Some(updates.subscribe(on_change, || Ok(()), || Some(Some(Light))).unwrap()); + updates.refresh(|| Some(Dark)); + updates.refresh(|| Some(Light)); + assert_eq!(received(&sender.1), [Some(Light), Some(Dark)]); + assert!(lock(&updates.0).subscribers.is_empty()); + } + + #[test] + fn an_older_theme_never_follows_a_newer_one() { + let updates = updates(); + let (subscription, themes) = subscribe(updates, Some(Some(Light))); + // Two threads can deliver out of order: version 3 arrives before version 2. + subscription.subscriber.deliver(3, Some(Dark)); + subscription.subscriber.deliver(2, None); + assert_eq!(received(&themes), [Some(Light), Some(Dark)]); + // A skipped change can leave the newest theme equal to the last one given. + subscription.subscriber.deliver(5, Some(Dark)); + assert_eq!(received(&themes), []); + } +} diff --git a/crates/theme/src/linux/desktop.rs b/crates/theme/src/linux/desktop.rs new file mode 100644 index 0000000..9474894 --- /dev/null +++ b/crates/theme/src/linux/desktop.rs @@ -0,0 +1,309 @@ +//! The theme that a desktop's own settings name. Desktops older than the portal's +//! `color-scheme` only name a GTK theme (or, on KDE, a window color), and window +//! managers without a desktop keep it in GTK's `settings.ini`. +//! +//! Their settings files are followed with inotify, so a change reaches subscribers +//! even where the portal doesn't report it. + +use std::{ + env, + ffi::{c_char, c_int, CString}, + fs::{self, File}, + io::Read, + os::{fd::FromRawFd, unix::ffi::OsStrExt}, + path::PathBuf, + process::{Command, Stdio}, + sync::atomic::{AtomicBool, Ordering}, + thread, + time::{Duration, Instant}, +}; + +use crate::Theme; + +/// Where Xfce's settings daemon keeps the GTK theme's name, in `xsettings.xml`. +const XFCE_SETTINGS_DIR: &str = "xfce4/xfconf/xfce-perchannel-xml"; +/// The files whose changes can change the theme: KDE's, dconf's (GNOME, Cinnamon, MATE), GTK's and Xfce's. +const SETTINGS_FILES: [&[u8]; 4] = [b"kdeglobals", b"user", b"settings.ini", b"xsettings.xml"]; + +const IN_CLOEXEC: c_int = 0o2000000; +const IN_CLOSE_WRITE: u32 = 0x08; +const IN_MOVED_TO: u32 = 0x80; +const IN_DELETE: u32 = 0x200; + +extern "C" { + fn inotify_init1(flags: c_int) -> c_int; + fn inotify_add_watch(fd: c_int, path: *const c_char, mask: u32) -> c_int; +} + +/// The desktops whose settings are read differently. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Desktop { + Gnome, + Kde, + Xfce, + Cinnamon, + Mate, + Deepin, + Other, +} + +impl Desktop { + /// The desktop that `XDG_CURRENT_DESKTOP` names. + pub(super) fn current() -> Self { + let names = env::var("XDG_CURRENT_DESKTOP").or_else(|_| env::var("DESKTOP_SESSION")).unwrap_or_default(); + Self::named(&names) + } + + /// The first known desktop in a list like `ubuntu:GNOME`. + fn named(names: &str) -> Self { + let names = names.to_ascii_lowercase(); + for name in names.split(':') { + match name { + "kde" | "plasma" => return Self::Kde, + "xfce" | "xubuntu" => return Self::Xfce, + "x-cinnamon" | "cinnamon" => return Self::Cinnamon, + "mate" => return Self::Mate, + "deepin" | "dde" => return Self::Deepin, + "gnome" | "gnome-classic" | "gnome-flashback" | "ubuntu" | "unity" | "budgie" | "pantheon" | "pop" => { + return Self::Gnome + } + _ => {} + } + } + Self::Other + } + + /// Whether a `color-scheme` of "no preference" is this desktop's own answer, rather than a default + /// that it never changes. GNOME 42+ keeps it current, and KDE always says light or dark. + pub(super) fn is_color_scheme_kept(self) -> bool { + matches!(self, Self::Gnome | Self::Kde) + } + + /// The portal setting, besides `color-scheme`, that this desktop keeps its theme in. + pub(super) fn portal_setting(self) -> Option<(&'static str, &'static str)> { + match self { + Self::Gnome => Some(("org.gnome.desktop.interface", "gtk-theme")), + Self::Kde => Some(("org.kde.kdeglobals.Colors:Window", "BackgroundNormal")), + _ => None, + } + } + + /// The theme that this desktop's own settings name, read without the portal. + pub(super) fn theme(self) -> Option { + let setting = match self { + Self::Gnome => gsettings("org.gnome.desktop.interface"), + Self::Cinnamon => gsettings("org.cinnamon.desktop.interface"), + Self::Mate => gsettings("org.mate.interface"), + Self::Deepin => gsettings("com.deepin.dde.appearance"), + Self::Xfce => xfce_theme_name(), + Self::Kde => kde_window_color(), + Self::Other => None, + }; + setting.as_deref().and_then(theme_of).or_else(gtk_settings_theme) + } +} + +/// The theme that a GTK or KDE theme's name, or KDE's `r,g,b` window color, stands for. +pub(super) fn theme_of(text: &str) -> Option { + let text = text.trim().trim_matches(|c| c == '\'' || c == '"'); + if let Some(gray) = gray(text) { + // The same test as KDE's own portal. + return Some(if gray < 192 { Theme::Dark } else { Theme::Light }); + } + if text.is_empty() { + return None; + } + let name = text.to_ascii_lowercase(); + // A "darker" theme (like Arc-Darker) only has dark title bars. + let is_dark = (name.contains("dark") && !name.contains("darker")) || DARK_THEMES.iter().any(|dark| name.contains(dark)); + Some(if is_dark { Theme::Dark } else { Theme::Light }) +} + +/// Popular dark themes whose names don't say "dark". +const DARK_THEMES: [&str; 6] = ["highcontrastinverse", "dracula", "nordic", "nokto", "noir", "equilux"]; + +/// The gray level of an `r,g,b` color, as Qt's `qGray` computes it. +fn gray(text: &str) -> Option { + let mut channels = text.split(',').map(|channel| channel.trim().parse::().ok().map(u32::from)); + let (red, green, blue) = (channels.next()??, channels.next()??, channels.next()??); + Some((red * 11 + green * 16 + blue * 5) / 32) +} + +/// The `gtk-theme` of a GSettings schema, as the `gsettings` tool prints it. +fn gsettings(schema: &str) -> Option { + let mut child = Command::new("gsettings") + .args(["get", schema, "gtk-theme"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + // It answers in a few milliseconds, but a stuck one must not hold up the theme. + let deadline = Instant::now() + Duration::from_secs(1); + while child.try_wait().ok()?.is_none() { + if Instant::now() > deadline { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + thread::sleep(Duration::from_millis(5)); + } + let output = child.wait_with_output().ok()?; + output.status.success().then(|| String::from_utf8_lossy(&output.stdout).into_owned()) +} + +/// Xfce's GTK theme name, from the file that its settings daemon keeps it in. +fn xfce_theme_name() -> Option { + let xml = fs::read_to_string(config_home()?.join(XFCE_SETTINGS_DIR).join("xsettings.xml")).ok()?; + let property = &xml[xml.find(r#"name="ThemeName""#)?..]; + let value = &property[property.find(r#"value=""#)? + r#"value=""#.len()..]; + Some(value[..value.find('"')?].to_owned()) +} + +/// KDE's window background color, from its `kdeglobals` file. +fn kde_window_color() -> Option { + let kdeglobals = fs::read_to_string(config_home()?.join("kdeglobals")).ok()?; + ini_value(&kdeglobals, "Colors:Window", "BackgroundNormal").map(str::to_owned) +} + +/// The theme in GTK's `settings.ini` files: the user's, then the system's. +fn gtk_settings_theme() -> Option { + let system_dirs = env::var("XDG_CONFIG_DIRS").ok().filter(|dirs| !dirs.is_empty()).unwrap_or_else(|| "/etc/xdg".into()); + let system_dirs = env::split_paths(&system_dirs).chain([PathBuf::from("/etc")]).collect::>(); + for dir in config_home().into_iter().chain(system_dirs) { + for gtk in ["gtk-3.0", "gtk-4.0"] { + let Ok(ini) = fs::read_to_string(dir.join(gtk).join("settings.ini")) else { + continue; + }; + let prefer_dark = ini_value(&ini, "Settings", "gtk-application-prefer-dark-theme"); + if prefer_dark.is_some_and(|value| matches!(value, "1" | "true")) { + return Some(Theme::Dark); + } + if let Some(theme) = ini_value(&ini, "Settings", "gtk-theme-name").and_then(theme_of) { + return Some(theme); + } + } + } + None +} + +/// The user's configuration directory. +fn config_home() -> Option { + let config_home = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).filter(|dir| dir.is_absolute()); + config_home.or_else(|| Some(PathBuf::from(env::var_os("HOME")?).join(".config"))) +} + +/// The last value of `key` in `[section]` of an INI file. +fn ini_value<'a>(ini: &'a str, section: &str, key: &str) -> Option<&'a str> { + let mut is_in_section = false; + let mut found = None; + for line in ini.lines().map(str::trim) { + if let Some(name) = line.strip_prefix('[').and_then(|line| line.strip_suffix(']')) { + is_in_section = name == section; + } else if let Some((name, value)) = line.split_once('=').filter(|_| is_in_section) { + if name.trim() == key { + found = Some(value.trim()); + } + } + } + found +} + +/// Whether `follow_files` has started. +static IS_FOLLOWING: AtomicBool = AtomicBool::new(false); + +pub(super) fn is_following_files() -> bool { + IS_FOLLOWING.load(Ordering::Acquire) +} + +/// Calls `on_change` from a thread of its own each time one of the settings files above changes. +/// It does this once per process; a directory that doesn't exist yet isn't followed. +pub(super) fn follow_files(on_change: fn()) { + if IS_FOLLOWING.swap(true, Ordering::AcqRel) { + return; + } + let Some(config) = config_home() else { return }; + // SAFETY: this only makes a new descriptor. + let fd = unsafe { inotify_init1(IN_CLOEXEC) }; + if fd < 0 { + return; + } + // SAFETY: `fd` is new, and this `File` is its only owner. + let mut events = unsafe { File::from_raw_fd(fd) }; + for dir in [config.clone(), config.join("dconf"), config.join("gtk-3.0"), config.join("gtk-4.0"), config.join(XFCE_SETTINGS_DIR)] { + let Ok(path) = CString::new(dir.as_os_str().as_bytes()) else { continue }; + // SAFETY: `path` is NUL-terminated and outlives the call. A missing directory just fails. + unsafe { inotify_add_watch(fd, path.as_ptr(), IN_CLOSE_WRITE | IN_MOVED_TO | IN_DELETE) }; + } + let follow = move || { + let mut buffer = [0u8; 4096]; + while let Ok(length) = events.read(&mut buffer) { + if file_names(&buffer[..length]).any(|name| SETTINGS_FILES.contains(&name)) { + on_change(); + } + } + }; + let _ = thread::Builder::new().name("robius-theme-files".into()).spawn(follow); +} + +/// The file names in a buffer of inotify events. +fn file_names(mut events: &[u8]) -> impl Iterator { + std::iter::from_fn(move || { + // Each event is `wd`, `mask`, `cookie` and `len`, then a name padded with NULs to `len` bytes. + let length = u32::from_ne_bytes(events.get(12..16)?.try_into().ok()?) as usize; + let name = events.get(16..16 + length)?; + events = &events[16 + length..]; + Some(name.split(|&byte| byte == 0).next().unwrap_or_default()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn desktops_are_known_by_any_of_their_names() { + assert_eq!(Desktop::named("ubuntu:GNOME"), Desktop::Gnome); + assert_eq!(Desktop::named("Budgie:GNOME"), Desktop::Gnome); + assert_eq!(Desktop::named("KDE"), Desktop::Kde); + assert_eq!(Desktop::named("X-Cinnamon"), Desktop::Cinnamon); + assert_eq!(Desktop::named("MATE"), Desktop::Mate); + assert_eq!(Desktop::named("XFCE"), Desktop::Xfce); + assert_eq!(Desktop::named("Deepin"), Desktop::Deepin); + assert_eq!(Desktop::named("i3"), Desktop::Other); + assert_eq!(Desktop::named(""), Desktop::Other); + } + + #[test] + fn theme_names_and_window_colors() { + assert_eq!(theme_of("'Yaru-dark'"), Some(Theme::Dark)); + assert_eq!(theme_of("Mint-Y-Dark-Aqua"), Some(Theme::Dark)); + assert_eq!(theme_of("BreezeDark"), Some(Theme::Dark)); + assert_eq!(theme_of("Yaru"), Some(Theme::Light)); + assert_eq!(theme_of("Arc-Darker"), Some(Theme::Light)); + assert_eq!(theme_of("HighContrastInverse"), Some(Theme::Dark)); + assert_eq!(theme_of("Dracula"), Some(Theme::Dark)); + assert_eq!(theme_of("Adapta-Nokto-Eta"), Some(Theme::Dark)); + assert_eq!(theme_of("239,240,241"), Some(Theme::Light)); + assert_eq!(theme_of("32, 35, 38"), Some(Theme::Dark)); + assert_eq!(theme_of(" "), None); + } + + #[test] + fn ini_values_come_from_their_own_section() { + let ini = "[Other]\ngtk-theme-name=Wrong\n[Settings]\n# gtk-theme-name=Commented\ngtk-theme-name = Adwaita-dark\n"; + assert_eq!(ini_value(ini, "Settings", "gtk-theme-name"), Some("Adwaita-dark")); + assert_eq!(ini_value(ini, "Settings", "gtk-application-prefer-dark-theme"), None); + } + + #[test] + fn file_names_are_read_from_inotify_events() { + let mut events = Vec::new(); + for name in [&b"user\0\0\0\0"[..], &b"settings.ini\0\0\0\0"[..]] { + events.extend_from_slice(&[0; 12]); + events.extend_from_slice(&(name.len() as u32).to_ne_bytes()); + events.extend_from_slice(name); + } + assert_eq!(file_names(&events).collect::>(), [&b"user"[..], &b"settings.ini"[..]]); + } +} diff --git a/crates/theme/src/linux/mod.rs b/crates/theme/src/linux/mod.rs new file mode 100644 index 0000000..3400105 --- /dev/null +++ b/crates/theme/src/linux/mod.rs @@ -0,0 +1,391 @@ +//! Linux desktops share the theme through the XDG Desktop Portal: the +//! `color-scheme` setting of `org.freedesktop.portal.Settings` on the session bus. +//! Desktops from before that setting (such as GNOME before 42, KDE Plasma before +//! 5.24, and older Cinnamon, MATE and Xfce) only name a theme, and window managers +//! without a desktop use GTK's own settings file, so `desktop.rs` reads those. +//! +//! One thread, `robius-theme`, keeps a bus connection and reads the theme again +//! each time the portal or one of those settings files says that it changed. zbus +//! is only used inside `zbus::block_on` on our own threads, and subscribers are only +//! called between two such calls, which works the same with zbus on async-io or on Tokio. + +mod desktop; + +use std::{ + future::{poll_fn, Future}, + panic::catch_unwind, + pin::{pin, Pin}, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc, Mutex, PoisonError, + }, + task::{Poll, Waker}, + thread, + time::Duration, +}; + +use zbus::{connection::Builder, export::futures_core::Stream, zvariant::Value, Connection, Message, MessageStream}; + +use crate::{Error, Result, Theme}; +use desktop::Desktop; + +const BUS: &str = "org.freedesktop.DBus"; +const PORTAL: &str = "org.freedesktop.portal.Desktop"; +const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop"; +const SETTINGS: &str = "org.freedesktop.portal.Settings"; +const COLOR_SCHEME: (&str, &str) = ("org.freedesktop.appearance", "color-scheme"); + +/// The bus sends this when the portal starts, exits or is replaced. +const PORTAL_OWNER_CHANGED: &str = "type='signal',sender='org.freedesktop.DBus',\ + path='/org/freedesktop/DBus',interface='org.freedesktop.DBus',\ + member='NameOwnerChanged',arg0='org.freedesktop.portal.Desktop'"; + +/// How long `query` lets the portal take to answer, which can include starting it. +const QUERY_TIMEOUT: Duration = Duration::from_secs(1); + +/// Whether the worker thread is alive. It ends if the session bus goes away. +static IS_RUNNING: AtomicBool = AtomicBool::new(false); +/// Whether that worker has given subscribers a theme, which it then keeps current. +static IS_LATEST_CURRENT: AtomicBool = AtomicBool::new(false); +/// Whether one of the desktop's settings files changed since the worker last read the theme. +/// Only older desktops need those files, so on others nothing follows them. +static ARE_FILES_CHANGED: AtomicBool = AtomicBool::new(false); +/// Wakes the worker, for when the settings files change. +static WORKER: Mutex> = Mutex::new(None); + +pub(crate) fn query() -> Result> { + // The worker keeps the latest theme current, so the bus isn't asked again. + if IS_LATEST_CURRENT.load(Ordering::Acquire) { + if let Some(theme) = crate::latest() { + return Ok(theme); + } + } + let (sender, receiver) = mpsc::channel(); + spawn("robius-theme-query", move || { + let _ = sender.send(zbus::block_on(read_once())); + })?; + // zbus has no time limit for connecting, so a little extra covers that. + let theme = receiver.recv_timeout(QUERY_TIMEOUT + Duration::from_millis(250)); + theme.unwrap_or_else(|_| Err(Error::Unavailable("the session bus did not answer in time".into()))) +} + +pub(crate) fn read_now() -> Option> { + // The worker gives subscribers the first theme once the portal has answered. + None +} + +pub(crate) fn start() -> Result<()> { + if IS_RUNNING.swap(true, Ordering::AcqRel) { + return Ok(()); + } + let run = || { + // Even a panic inside zbus must let a later `start` try again. + let _ = catch_unwind(work); + IS_LATEST_CURRENT.store(false, Ordering::Release); + IS_RUNNING.store(false, Ordering::Release); + }; + spawn("robius-theme", run).inspect_err(|_| IS_RUNNING.store(false, Ordering::Release)) +} + +fn spawn(name: &str, run: impl FnOnce() + Send + 'static) -> Result<()> { + let thread = thread::Builder::new().name(name.into()).spawn(run); + thread.map(drop).map_err(|error| Error::Unavailable(format!("could not start a thread: {error}"))) +} + +/// Called from the thread that follows the desktop's settings files, when one of them changed. +fn files_changed() { + if IS_RUNNING.load(Ordering::Acquire) { + // The worker reads the theme again, starting with the portal. + ARE_FILES_CHANGED.store(true, Ordering::Release); + if let Some(worker) = WORKER.lock().unwrap_or_else(PoisonError::into_inner).take() { + worker.wake(); + } + } else { + // Without a session bus, there are only the files. + crate::refresh(|| Desktop::current().theme()); + } +} + +/// Runs on the worker thread until the session bus goes away. +fn work() { + let Ok(mut portal) = zbus::block_on(Portal::subscribe()) else { + // Without a session bus, subscribers get the theme from the desktop's own settings. + desktop::follow_files(files_changed); + crate::refresh(|| Desktop::current().theme()); + return; + }; + // Subscribers are called here, between two `block_on` calls. + while let Some(theme) = zbus::block_on(portal.next_theme()) { + crate::refresh(|| { + // Set before subscribers are called, so that a `query` from one of them is answered at once. + IS_LATEST_CURRENT.store(true, Ordering::Release); + theme + }); + } +} + +/// Reads the theme once over a connection of its own, for `query`. +async fn read_once() -> Result> { + match connect(Some(QUERY_TIMEOUT)).await { + Ok(conn) => drive(&conn, read(conn.clone(), false)).await, + // Without a session bus, there are only the desktop's own settings. + Err(_) => Ok(Desktop::current().theme()), + } +} + +/// Connects to the session bus. zbus starts no thread for the connection: `drive` runs it. +async fn connect(method_timeout: Option) -> zbus::Result { + let mut builder = Builder::session()?.internal_executor(false); + if let Some(timeout) = method_timeout { + builder = builder.method_timeout(timeout); + } + builder.build().await +} + +/// Awaits `future` while running the connection's own tasks, such as reading its socket. +async fn drive(conn: &Connection, future: F) -> F::Output { + let mut future = pin!(future); + let mut tasks = pin!(async { + loop { + conn.executor().tick().await; + } + }); + poll_fn(|cx| { + let _ = tasks.as_mut().poll(cx); + future.as_mut().poll(cx) + }) + .await +} + +/// Reads the portal's `color-scheme`, or else the theme that the desktop's own settings name. +/// With `is_following`, it also starts following those other settings, the first time they're needed. +async fn read(conn: Connection, is_following: bool) -> Result> { + let desktop = Desktop::current(); + match read_setting(&conn, COLOR_SCHEME).await? { + Some(Setting::Number(1)) => return Ok(Some(Theme::Dark)), + Some(Setting::Number(2)) => return Ok(Some(Theme::Light)), + // Those desktops keep this setting current, so no preference is their answer. + Some(_) if desktop.is_color_scheme_kept() => return Ok(None), + // An older desktop: no such setting, or one that this desktop doesn't keep current. + _ => {} + } + if let Some((namespace, key)) = desktop.portal_setting() { + if is_following { + add_match(&conn, &setting_changed(namespace, key)).await?; + } + if let Some(Setting::Text(text)) = read_setting(&conn, (namespace, key)).await? { + if let Some(theme) = desktop::theme_of(&text) { + return Ok(Some(theme)); + } + } + } + if is_following { + desktop::follow_files(files_changed); + } + Ok(desktop.theme()) +} + +/// A rule for the bus to pass on changes of one setting, and only from the portal. +fn setting_changed(namespace: &str, key: &str) -> String { + format!( + "type='signal',sender='{PORTAL}',path='{PORTAL_PATH}',interface='{SETTINGS}',\ + member='SettingChanged',arg0='{namespace}',arg1='{key}'" + ) +} + +/// Asks the bus to pass on the messages that `rule` describes. +async fn add_match(conn: &Connection, rule: &str) -> Result<()> { + let reply = conn.call_method(Some(BUS), "/org/freedesktop/DBus", Some(BUS), "AddMatch", &rule).await; + reply.map(drop).map_err(|error| Error::Unavailable(format!("could not subscribe to the desktop portal: {error}"))) +} + +/// A setting's value: `color-scheme` is a number, and the older settings are text. +enum Setting { + Number(u32), + Text(String), +} + +/// Reads one setting with `ReadOne`, or with `Read` from a portal too old to have that. +async fn read_setting(conn: &Connection, setting: (&str, &str)) -> Result> { + for method in ["ReadOne", "Read"] { + let reply = conn.call_method(Some(PORTAL), PORTAL_PATH, Some(SETTINGS), method, &setting).await; + let error = match reply { + Ok(reply) => return setting_in(&reply).map(Some), + Err(error) => error, + }; + let name = match &error { + zbus::Error::MethodError(name, ..) => name.as_str(), + _ => "", + }; + match name { + "org.freedesktop.DBus.Error.UnknownMethod" => {} + // No portal, or no such setting in it. + "org.freedesktop.DBus.Error.ServiceUnknown" + | "org.freedesktop.DBus.Error.NameHasNoOwner" + | "org.freedesktop.DBus.Error.UnknownInterface" + | "org.freedesktop.DBus.Error.UnknownObject" + | "org.freedesktop.portal.Error.NotFound" => return Ok(None), + _ => return Err(Error::Unavailable(format!("could not read the desktop portal's settings: {error}"))), + } + } + // A portal with neither method has no settings at all. + Ok(None) +} + +/// The setting that a reply from the portal holds. +fn setting_in(reply: &Message) -> Result { + let body = reply.body(); + // `Read` wraps the value in one more variant than `ReadOne` does. + let mut value = body.deserialize::>().ok(); + while let Some(Value::Value(inner)) = value { + value = Some(*inner); + } + match value { + Some(Value::U32(number)) => Ok(Setting::Number(number)), + Some(Value::Str(text)) => Ok(Setting::Text(text.as_str().to_owned())), + _ => Err(Error::Unavailable("the desktop portal's answer was not a theme setting".into())), + } +} + +/// A call to `read` that hasn't finished yet. +type Reading = Pin>>>>; + +/// The worker's connection to the session bus, subscribed to the portal's changes. +struct Portal { + conn: Connection, + /// Everything that the bus sends us. + messages: MessageStream, + reading: Option, + /// Whether to read the setting (again) once no read is in flight. + is_stale: bool, +} + +enum Event { + /// The portal or a settings file says that the theme may have changed. + Changed, + /// The portal started, or another one replaced it. + PortalStarted, + Read(Result>), + /// The session bus is gone. + Closed, +} + +impl Portal { + async fn subscribe() -> zbus::Result { + let conn = connect(None).await?; + // This exists before the bus is asked for anything, so no change can be missed. + let messages = MessageStream::from(&conn); + for rule in [setting_changed(COLOR_SCHEME.0, COLOR_SCHEME.1), PORTAL_OWNER_CHANGED.to_owned()] { + let add_match = conn.call_method(Some(BUS), "/org/freedesktop/DBus", Some(BUS), "AddMatch", &rule); + drive(&conn, add_match).await?; + } + Ok(Self { conn, messages, reading: None, is_stale: true }) + } + + /// The next theme to give to subscribers, or `None` once the session bus is gone. + async fn next_theme(&mut self) -> Option> { + loop { + if self.is_stale && self.reading.is_none() { + self.is_stale = false; + self.reading = Some(Box::pin(read(self.conn.clone(), true))); + } + match self.next_event().await { + Event::Changed => self.is_stale = true, + Event::PortalStarted => { + // The portal that was asked may never answer now. + self.reading = None; + self.is_stale = true; + } + Event::Read(theme) => { + self.reading = None; + match theme { + // The setting changed during the read, so this answer may be old. + _ if self.is_stale => {} + Ok(theme) => return Some(theme), + // Nothing was learned, so subscribers keep the theme they have. + Err(_) => {} + } + } + Event::Closed => return None, + } + } + } + + async fn next_event(&mut self) -> Event { + let Self { conn, messages, reading, .. } = self; + let event = poll_fn(|cx| { + if desktop::is_following_files() { + *WORKER.lock().unwrap_or_else(PoisonError::into_inner) = Some(cx.waker().clone()); + if ARE_FILES_CHANGED.swap(false, Ordering::AcqRel) { + return Poll::Ready(Event::Changed); + } + } + // zbus stops reading the socket once 64 messages wait here, so take them all. + loop { + match Pin::new(&mut *messages).poll_next(cx) { + Poll::Ready(Some(Ok(message))) => { + if let Some(event) = signal(&message) { + return Poll::Ready(event); + } + } + Poll::Ready(_) => return Poll::Ready(Event::Closed), + Poll::Pending => break, + } + } + match reading { + Some(reading) => reading.as_mut().poll(cx).map(Event::Read), + None => Poll::Pending, + } + }); + drive(conn, event).await + } +} + +/// What a message from the bus means for the theme, if it's one of the two signals. +fn signal(message: &Message) -> Option { + if message.message_type() != zbus::message::Type::Signal { + return None; + } + match message.header().member()?.as_str() { + // The setting is read again, as portals also pass on values that aren't in effect. + "SettingChanged" => Some(Event::Changed), + "NameOwnerChanged" => { + // An empty new owner means that the portal exited, which changes nothing. + let owners = message.body(); + let is_started = owners.deserialize::<(&str, &str, &str)>().is_ok_and(|(_, _, new)| !new.is_empty()); + is_started.then_some(Event::PortalStarted) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A reply from the portal that holds `value`. + fn reply(value: Value<'_>) -> Message { + let call = Message::method_call(PORTAL_PATH, "ReadOne").unwrap().build(&()).unwrap(); + Message::method_return(&call.header()).unwrap().build(&value).unwrap() + } + + #[test] + fn a_reply_holds_a_number_or_text() { + let setting = |value| setting_in(&reply(value)); + assert!(matches!(setting(Value::U32(1)), Ok(Setting::Number(1)))); + assert!(matches!(setting(Value::Value(Box::new(Value::U32(2)))), Ok(Setting::Number(2)))); + assert!(matches!(setting(Value::from("Yaru-dark")), Ok(Setting::Text(text)) if text == "Yaru-dark")); + assert!(matches!(setting(Value::Value(Box::new(Value::from("Adwaita")))), Ok(Setting::Text(text)) if text == "Adwaita")); + assert!(setting(Value::Bool(true)).is_err()); + } + + #[test] + fn a_rule_names_its_setting_and_the_portal() { + assert_eq!( + setting_changed("org.freedesktop.appearance", "color-scheme"), + "type='signal',sender='org.freedesktop.portal.Desktop',path='/org/freedesktop/portal/desktop',\ + interface='org.freedesktop.portal.Settings',member='SettingChanged',\ + arg0='org.freedesktop.appearance',arg1='color-scheme'" + ); + } +} diff --git a/crates/theme/src/unsupported.rs b/crates/theme/src/unsupported.rs new file mode 100644 index 0000000..8b956d0 --- /dev/null +++ b/crates/theme/src/unsupported.rs @@ -0,0 +1,15 @@ +//! Platforms with no system theme that we know how to read. + +use crate::{Error, Result, Theme}; + +pub(crate) fn query() -> Result> { + Err(Error::Unsupported) +} + +pub(crate) fn start() -> Result<()> { + Err(Error::Unsupported) +} + +pub(crate) fn read_now() -> Option> { + None +} diff --git a/crates/theme/src/windows.rs b/crates/theme/src/windows.rs new file mode 100644 index 0000000..736aaf5 --- /dev/null +++ b/crates/theme/src/windows.rs @@ -0,0 +1,258 @@ +//! Windows keeps its app theme in the registry, as the `AppsUseLightTheme` value +//! of the current user's `Personalize` key. Microsoft doesn't document it, but +//! the system's own theme API reads it the same way as `read` does here. While +//! a contrast theme is on, the theme is the one that its window color has. +//! +//! The system sets an event when a registry key changes, and one of its +//! thread-pool threads then calls `on_change`. A key that is followed stays +//! followed for good: nothing is ever unregistered or closed again. + +use std::{ + ffi::c_void, + io, + mem::size_of, + ptr, + sync::{Mutex, PoisonError}, +}; + +use crate::{Error, Result, Theme}; + +/// `HANDLE` and `HKEY` +type Handle = *mut c_void; +/// `WAITORTIMERCALLBACK`. Its second argument is a `BOOLEAN`. +type WaitCallback = unsafe extern "system" fn(context: *mut c_void, was_timed_out: u8); + +/// `HIGHCONTRASTW` +#[repr(C)] +struct HighContrast { + size: u32, + flags: u32, + /// The system points this at a buffer that it keeps, so it must not be freed. + default_scheme: *mut u16, +} + +/// `0x8000_0001` as a `LONG`, sign-extended to the size of a pointer. +const HKEY_CURRENT_USER: Handle = 0x8000_0001_u32 as i32 as isize as Handle; +const KEY_NOTIFY: u32 = 0x0010; +const REG_OPTION_NON_VOLATILE: u32 = 0; +const RRF_RT_REG_DWORD: u32 = 0x0010; +const REG_NOTIFY_CHANGE_NAME: u32 = 0x0001; +const REG_NOTIFY_CHANGE_LAST_SET: u32 = 0x0004; +/// Lets a thread-pool thread, which may exit at any time, ask for the next change. +const REG_NOTIFY_THREAD_AGNOSTIC: u32 = 0x1000_0000; +const INFINITE: u32 = u32::MAX; +const WT_EXECUTEDEFAULT: u32 = 0; +const SPI_GETHIGHCONTRAST: u32 = 0x0042; +const HCF_HIGHCONTRASTON: u32 = 0x0001; +const COLOR_WINDOW: i32 = 5; + +#[link(name = "advapi32")] +extern "system" { + fn RegCreateKeyExW( + key: Handle, + sub_key: *const u16, + reserved: u32, + class: *const u16, + options: u32, + access: u32, + security: *const c_void, + result: *mut Handle, + disposition: *mut u32, + ) -> i32; + fn RegGetValueW(key: Handle, sub_key: *const u16, value: *const u16, flags: u32, kind: *mut u32, data: *mut c_void, size: *mut u32) -> i32; + fn RegNotifyChangeKeyValue(key: Handle, is_for_subtree: i32, filter: u32, event: Handle, is_asynchronous: i32) -> i32; + fn RegCloseKey(key: Handle) -> i32; +} + +#[link(name = "kernel32")] +extern "system" { + fn CreateEventW(security: *const c_void, is_manual_reset: i32, is_set: i32, name: *const u16) -> Handle; + fn RegisterWaitForSingleObject( + wait: *mut Handle, + object: Handle, + callback: WaitCallback, + context: *mut c_void, + milliseconds: u32, + flags: u32, + ) -> i32; + fn CloseHandle(handle: Handle) -> i32; +} + +#[link(name = "user32")] +extern "system" { + fn SystemParametersInfoW(action: u32, param: u32, data: *mut c_void, update: u32) -> i32; + fn GetSysColor(index: i32) -> u32; +} + +/// The key of the app theme, and the key of the colors that a contrast theme sets. +static PERSONALIZE: [u16; 64] = wide(r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"); +static COLORS: [u16; 64] = wide(r"Control Panel\Colors"); +static APPS_USE_LIGHT_THEME: [u16; 64] = wide("AppsUseLightTheme"); + +pub(crate) fn query() -> Result> { + Ok(Some(read())) +} + +pub(crate) fn read_now() -> Option> { + Some(Some(read())) +} + +pub(crate) fn start() -> Result<()> { + // How many of the two keys are followed so far, so that none is followed twice. + static FOLLOWED: Mutex = Mutex::new(0); + let mut followed = FOLLOWED.lock().unwrap_or_else(PoisonError::into_inner); + for path in [&PERSONALIZE, &COLORS].into_iter().skip(*followed) { + follow(path).map_err(|error| Error::Unavailable(format!("couldn't subscribe to registry changes: {error}")))?; + *followed += 1; + } + Ok(()) +} + +/// A registry key, and the event that the system sets when the key changes. +struct FollowedKey { + key: Handle, + event: Handle, +} + +impl FollowedKey { + /// Asks for the event to be set at the key's next change. The system reports one change per call. + fn arm(&self) -> io::Result<()> { + const FILTER: u32 = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_THREAD_AGNOSTIC; + // SAFETY: both handles are open, and the call keeps no pointer of ours. + let status = unsafe { RegNotifyChangeKeyValue(self.key, 0, FILTER, self.event, 1) }; + if status == 0 { + Ok(()) + } else { + Err(io::Error::from_raw_os_error(status)) + } + } +} + +impl Drop for FollowedKey { + /// Only runs if following the key failed, because a followed key is leaked. + fn drop(&mut self) { + // SAFETY: no wait is registered for the event, so nothing else uses either handle. + unsafe { + RegCloseKey(self.key); + if !self.event.is_null() { + CloseHandle(self.event); + } + } + } +} + +/// Follows one of the current user's registry keys for good, creating the key if it's missing. +fn follow(path: &[u16]) -> io::Result<()> { + let mut key = ptr::null_mut(); + // SAFETY: `path` is NUL-terminated, `key` receives the handle, and the null arguments are optional. + let status = unsafe { + RegCreateKeyExW(HKEY_CURRENT_USER, path.as_ptr(), 0, ptr::null(), REG_OPTION_NON_VOLATILE, KEY_NOTIFY, ptr::null(), &mut key, ptr::null_mut()) + }; + if status != 0 { + return Err(io::Error::from_raw_os_error(status)); + } + // SAFETY: both pointers are optional. The event has no name, resets itself and starts unset. + let followed = FollowedKey { key, event: unsafe { CreateEventW(ptr::null(), 0, 0, ptr::null()) } }; + if followed.event.is_null() { + return Err(io::Error::last_os_error()); + } + followed.arm()?; + let event = followed.event; + let followed = Box::into_raw(Box::new(followed)); + let mut wait = ptr::null_mut(); + // SAFETY: `followed` is leaked, so it outlives every call of `on_change`, which only reads it. + if unsafe { RegisterWaitForSingleObject(&mut wait, event, on_change, followed.cast(), INFINITE, WT_EXECUTEDEFAULT) } == 0 { + let error = io::Error::last_os_error(); + // SAFETY: the system didn't take the pointer, which `Box::into_raw` made just above. + drop(unsafe { Box::from_raw(followed) }); + return Err(error); + } + Ok(()) +} + +/// The system calls this on a thread-pool thread each time the key has changed. +// Nothing in here panics, which matters because a panic must not unwind into the system. +unsafe extern "system" fn on_change(context: *mut c_void, _was_timed_out: u8) { + // SAFETY: `context` is the leaked `FollowedKey` that `follow` registered. + let followed = unsafe { &*context.cast::() }; + // Ask for the next change before reading, so that none is missed. If that fails, this was the last one. + let _ = followed.arm(); + crate::refresh(|| Some(read())); +} + +fn read() -> Theme { + let is_light = match contrast_window_color() { + Some(color) => is_light_color(color), + None => is_app_theme_light(), + }; + if is_light { + Theme::Light + } else { + Theme::Dark + } +} + +/// The window color of the contrast theme, if one is on. Windows then ignores the app theme. +fn contrast_window_color() -> Option { + let mut contrast = HighContrast { size: size_of::() as u32, flags: 0, default_scheme: ptr::null_mut() }; + // SAFETY: `contrast` is the structure that this action fills in, and it states its own size. + let is_filled = unsafe { SystemParametersInfoW(SPI_GETHIGHCONTRAST, contrast.size, ptr::addr_of_mut!(contrast).cast(), 0) } != 0; + if !is_filled || contrast.flags & HCF_HIGHCONTRASTON == 0 { + return None; + } + // SAFETY: this only takes a number. + Some(unsafe { GetSysColor(COLOR_WINDOW) }) +} + +/// Windows itself takes the app theme for light unless a 0 is stored, so a failed read is light too. +fn is_app_theme_light() -> bool { + let (mut number, mut size) = (1_u32, size_of::() as u32); + // SAFETY: both strings are NUL-terminated, and `size` is the size of `number`, which receives the value. + let status = unsafe { + RegGetValueW(HKEY_CURRENT_USER, PERSONALIZE.as_ptr(), APPS_USE_LIGHT_THEME.as_ptr(), RRF_RT_REG_DWORD, ptr::null_mut(), ptr::addr_of_mut!(number).cast(), &mut size) + }; + status != 0 || number != 0 +} + +/// Microsoft's test of whether a color is a light one. A `COLORREF` is `0x00BBGGRR`. +fn is_light_color(color: u32) -> bool { + let [red, green, blue, _] = color.to_le_bytes().map(u32::from); + 5 * green + 2 * red + blue > 8 * 128 +} + +/// Makes a NUL-terminated UTF-16 string from ASCII text of fewer than 64 characters. +const fn wide(text: &str) -> [u16; 64] { + let (text, mut wide, mut i) = (text.as_bytes(), [0; 64], 0); + assert!(text.len() < wide.len()); + while i < text.len() { + assert!(text[i].is_ascii()); + wide[i] = text[i] as u16; + i += 1; + } + wide +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tells_light_colors_from_dark_ones() { + assert!(is_light_color(0x00FF_FFFF)); + assert!(!is_light_color(0x0000_0000)); + // Grey 128 is exactly on the limit, which still counts as dark. + assert!(!is_light_color(0x0080_8080)); + assert!(is_light_color(0x0081_8181)); + // Green counts five times, red twice and blue once, so the order of the bytes matters. + assert!(is_light_color(0x0000_99FF)); + assert!(!is_light_color(0x00FF_9900)); + } + + #[test] + fn reads_the_same_theme_from_any_thread() { + let theme = read(); + assert_eq!(std::thread::spawn(read).join().unwrap(), theme); + assert_eq!(query(), Ok(Some(theme))); + assert_eq!(read_now(), Some(Some(theme))); + } +} diff --git a/crates/theme/tests/windows.rs b/crates/theme/tests/windows.rs new file mode 100644 index 0000000..1b80021 --- /dev/null +++ b/crates/theme/tests/windows.rs @@ -0,0 +1,59 @@ +//! Follows a real change of the Windows app theme from end to end. +#![cfg(windows)] + +use std::{process::Command, sync::mpsc, time::Duration}; + +use robius_theme::Theme; + +const KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"; +const VALUE: &str = "AppsUseLightTheme"; +/// How long a change may take to reach the subscriber. +const TIMEOUT: Duration = Duration::from_secs(5); + +/// This changes the current user's app theme setting for a moment, so it only +/// runs when asked for, as CI does. +#[test] +#[ignore = "changes the current user's app theme setting for a moment"] +fn a_change_of_the_app_theme_reaches_a_subscriber() { + // `reg` prints the stored number after its type, and fails if nothing is stored. + let original = reg("query", &[]).map(|printed| { + let mut words = printed.split_whitespace().skip_while(|word| *word != "REG_DWORD"); + words.nth(1).expect("the setting should be stored as a number").to_owned() + }); + + let (sender, themes) = mpsc::channel(); + let _subscription = robius_theme::subscribe(move |theme| { + let _ = sender.send(theme); + }) + .unwrap(); + let before = themes.recv_timeout(TIMEOUT).unwrap(); + assert_eq!(robius_theme::query(), Ok(before)); + let (opposite, number) = if before == Some(Theme::Dark) { (Theme::Light, "1") } else { (Theme::Dark, "0") }; + + let restore = Restore(original); + assert!(reg("add", &["/t", "REG_DWORD", "/d", number, "/f"]).is_some()); + assert_eq!(themes.recv_timeout(TIMEOUT), Ok(Some(opposite))); + assert_eq!(robius_theme::query(), Ok(Some(opposite))); + + drop(restore); + assert_eq!(themes.recv_timeout(TIMEOUT), Ok(before)); + assert_eq!(robius_theme::query(), Ok(before)); +} + +/// Puts the setting back when it's dropped, which also happens when the test fails. +struct Restore(Option); + +impl Drop for Restore { + fn drop(&mut self) { + match &self.0 { + Some(number) => reg("add", &["/t", "REG_DWORD", "/d", number, "/f"]), + None => reg("delete", &["/f"]), + }; + } +} + +/// Runs the `reg` tool on the setting, and returns what it printed if it succeeded. +fn reg(action: &str, more: &[&str]) -> Option { + let output = Command::new("reg").args([action, KEY, "/v", VALUE]).args(more).output().ok()?; + output.status.success().then(|| String::from_utf8_lossy(&output.stdout).into_owned()) +}