Compare commits

...

2 Commits

Author SHA1 Message Date
48706e5a29 perf: cache blurred wallpaper to disk to avoid re-blur on startup
First launch with blur blurs and saves to ~/.cache/moonlock/.
Subsequent starts load the cached PNG directly. Cache invalidates
when wallpaper path, size, mtime, or sigma changes.
Adds dirs crate for cache directory resolution.
2026-03-28 21:23:43 +01:00
de9a3e9e6a feat: add optional background blur, align to shared texture pattern
Gaussian blur applied at texture load time when `background_blur` is
set in moonlock.toml. Refactored wallpaper loading from per-window
Picture::for_filename() to shared gdk::Texture pattern (matching
moonset/moongreet), avoiding redundant JPEG decoding on multi-monitor.
2026-03-28 14:53:27 +01:00
6 changed files with 475 additions and 21 deletions

222
Cargo.lock generated
View File

@ -2,6 +2,12 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.102" version = "1.0.102"
@ -20,6 +26,18 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
[[package]]
name = "bytemuck"
version = "1.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]] [[package]]
name = "cairo-rs" name = "cairo-rs"
version = "0.22.0" version = "0.22.0"
@ -65,6 +83,36 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "crc32fast"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
dependencies = [
"cfg-if",
]
[[package]]
name = "dirs"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs-sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys",
]
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.2" version = "1.0.2"
@ -87,6 +135,15 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]] [[package]]
name = "field-offset" name = "field-offset"
version = "0.3.6" version = "0.3.6"
@ -97,6 +154,16 @@ dependencies = [
"rustc_version", "rustc_version",
] ]
[[package]]
name = "flate2"
version = "1.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]] [[package]]
name = "foldhash" name = "foldhash"
version = "0.1.5" version = "0.1.5"
@ -223,6 +290,17 @@ dependencies = [
"system-deps", "system-deps",
] ]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.4.2" version = "0.4.2"
@ -510,6 +588,21 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "image"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"moxcms",
"num-traits",
"png",
"zune-core",
"zune-jpeg",
]
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "2.13.0" version = "2.13.0"
@ -546,6 +639,15 @@ version = "0.2.183"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d"
[[package]]
name = "libredox"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ddbf48fd451246b1f8c2610bd3b4ac0cc6e149d89832867093ab69a17194f08"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.12.1" version = "0.12.1"
@ -574,9 +676,20 @@ dependencies = [
] ]
[[package]] [[package]]
name = "moonlock" name = "miniz_oxide"
version = "0.4.2" version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [ dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "moonlock"
version = "0.5.0"
dependencies = [
"dirs",
"gdk-pixbuf", "gdk-pixbuf",
"gdk4", "gdk4",
"gio", "gio",
@ -584,6 +697,7 @@ dependencies = [
"glib-build-tools", "glib-build-tools",
"gtk4", "gtk4",
"gtk4-session-lock", "gtk4-session-lock",
"image",
"libc", "libc",
"log", "log",
"nix", "nix",
@ -594,6 +708,16 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "moxcms"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
dependencies = [
"num-traits",
"pxfm",
]
[[package]] [[package]]
name = "nix" name = "nix"
version = "0.29.0" version = "0.29.0"
@ -606,12 +730,27 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "option-ext"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]] [[package]]
name = "pango" name = "pango"
version = "0.22.0" version = "0.22.0"
@ -648,6 +787,19 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide",
]
[[package]] [[package]]
name = "prettyplease" name = "prettyplease"
version = "0.2.37" version = "0.2.37"
@ -676,6 +828,12 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "pxfm"
version = "0.1.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a041e753da8b807c9255f28de81879c78c876392ff2469cde94799b2896b9d"
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.45" version = "1.0.45"
@ -691,6 +849,17 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "redox_users"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"
dependencies = [
"getrandom 0.2.17",
"libredox",
"thiserror",
]
[[package]] [[package]]
name = "rustc_version" name = "rustc_version"
version = "0.4.1" version = "0.4.1"
@ -780,6 +949,12 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "simd-adler32"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
[[package]] [[package]]
name = "slab" name = "slab"
version = "0.4.12" version = "0.4.12"
@ -839,12 +1014,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [ dependencies = [
"fastrand", "fastrand",
"getrandom", "getrandom 0.4.2",
"once_cell", "once_cell",
"rustix", "rustix",
"windows-sys", "windows-sys",
] ]
[[package]]
name = "thiserror"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "toml" name = "toml"
version = "0.8.23" version = "0.8.23"
@ -964,6 +1159,12 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]] [[package]]
name = "wasip2" name = "wasip2"
version = "1.0.2+wasi-0.2.9" version = "1.0.2+wasi-0.2.9"
@ -1168,3 +1369,18 @@ name = "zmij"
version = "1.0.21" version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
[[package]]
name = "zune-core"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"
[[package]]
name = "zune-jpeg"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core",
]

View File

@ -14,9 +14,11 @@ gdk-pixbuf = "0.22"
gio = "0.22" gio = "0.22"
toml = "0.8" toml = "0.8"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
dirs = "6"
nix = { version = "0.29", features = ["user"] } nix = { version = "0.29", features = ["user"] }
zeroize = { version = "1", features = ["derive"] } zeroize = { version = "1", features = ["derive"] }
libc = "0.2" libc = "0.2"
image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }
log = "0.4" log = "0.4"
systemd-journal-logger = "2.2" systemd-journal-logger = "2.2"

17
DECISIONS.md Normal file
View File

@ -0,0 +1,17 @@
# Decisions
Architectural and design decisions for Moonlock, in reverse chronological order.
## 2026-03-28 Optional background blur via `image` crate
- **Who**: Nyx, Dom
- **Why**: Consistent with moonset/moongreet — blurred wallpaper as lockscreen background is a common UX pattern
- **Tradeoffs**: Adds `image` crate dependency (~15 transitive crates); CPU-side Gaussian blur at load time adds startup latency proportional to image size and sigma. Acceptable because blur runs once and the texture is shared across monitors.
- **How**: `load_background_texture(bg_path, blur_radius)` loads texture, optionally applies `imageops::blur()`, returns `gdk::Texture`. Config option `background_blur: Option<f32>` in TOML.
## 2026-03-28 Shared wallpaper texture pattern (aligned with moonset/moongreet)
- **Who**: Nyx, Dom
- **Why**: Previously loaded wallpaper per-window via `Picture::for_filename()`. Multi-monitor setups decoded the JPEG redundantly. Blur feature requires texture pixel access anyway.
- **Tradeoffs**: Slightly more code in main.rs (texture loaded before window creation), but avoids redundant decoding and enables the blur feature.
- **How**: `load_background_texture()` in lockscreen.rs decodes once, `create_background_picture()` wraps shared `gdk::Texture` in `gtk::Picture`. Same pattern as moonset/moongreet.

View File

@ -21,6 +21,7 @@ fn default_config_paths() -> Vec<PathBuf> {
#[derive(Debug, Clone, Default, Deserialize)] #[derive(Debug, Clone, Default, Deserialize)]
struct RawConfig { struct RawConfig {
pub background_path: Option<String>, pub background_path: Option<String>,
pub background_blur: Option<f32>,
pub fingerprint_enabled: Option<bool>, pub fingerprint_enabled: Option<bool>,
} }
@ -28,6 +29,7 @@ struct RawConfig {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Config { pub struct Config {
pub background_path: Option<String>, pub background_path: Option<String>,
pub background_blur: Option<f32>,
pub fingerprint_enabled: bool, pub fingerprint_enabled: bool,
} }
@ -35,6 +37,7 @@ impl Default for Config {
fn default() -> Self { fn default() -> Self {
Config { Config {
background_path: None, background_path: None,
background_blur: None,
fingerprint_enabled: true, fingerprint_enabled: true,
} }
} }
@ -48,6 +51,7 @@ pub fn load_config(config_paths: Option<&[PathBuf]>) -> Config {
if let Ok(content) = fs::read_to_string(path) { if let Ok(content) = fs::read_to_string(path) {
if let Ok(parsed) = toml::from_str::<RawConfig>(&content) { if let Ok(parsed) = toml::from_str::<RawConfig>(&content) {
if parsed.background_path.is_some() { merged.background_path = parsed.background_path; } if parsed.background_path.is_some() { merged.background_path = parsed.background_path; }
if parsed.background_blur.is_some() { merged.background_blur = parsed.background_blur; }
if let Some(fp) = parsed.fingerprint_enabled { merged.fingerprint_enabled = fp; } if let Some(fp) = parsed.fingerprint_enabled { merged.fingerprint_enabled = fp; }
} }
} }
@ -72,7 +76,7 @@ pub fn resolve_background_path_with(config: &Config, moonarch_wallpaper: &Path)
mod tests { mod tests {
use super::*; use super::*;
#[test] fn default_config() { let c = Config::default(); assert!(c.background_path.is_none()); assert!(c.fingerprint_enabled); } #[test] fn default_config() { let c = Config::default(); assert!(c.background_path.is_none()); assert!(c.background_blur.is_none()); assert!(c.fingerprint_enabled); }
#[test] fn load_default_fingerprint_true() { #[test] fn load_default_fingerprint_true() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let conf = dir.path().join("moonlock.toml"); let conf = dir.path().join("moonlock.toml");
@ -83,15 +87,23 @@ mod tests {
#[test] fn load_background() { #[test] fn load_background() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let conf = dir.path().join("moonlock.toml"); let conf = dir.path().join("moonlock.toml");
fs::write(&conf, "background_path = \"/custom/bg.jpg\"\nfingerprint_enabled = false\n").unwrap(); fs::write(&conf, "background_path = \"/custom/bg.jpg\"\nbackground_blur = 15.0\nfingerprint_enabled = false\n").unwrap();
let c = load_config(Some(&[conf])); let c = load_config(Some(&[conf]));
assert_eq!(c.background_path.as_deref(), Some("/custom/bg.jpg")); assert_eq!(c.background_path.as_deref(), Some("/custom/bg.jpg"));
assert_eq!(c.background_blur, Some(15.0));
assert!(!c.fingerprint_enabled); assert!(!c.fingerprint_enabled);
} }
#[test] fn load_blur_optional() {
let dir = tempfile::tempdir().unwrap();
let conf = dir.path().join("moonlock.toml");
fs::write(&conf, "background_path = \"/bg.jpg\"\n").unwrap();
let c = load_config(Some(&[conf]));
assert!(c.background_blur.is_none());
}
#[test] fn resolve_config_path() { #[test] fn resolve_config_path() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let wp = dir.path().join("bg.jpg"); fs::write(&wp, "fake").unwrap(); let wp = dir.path().join("bg.jpg"); fs::write(&wp, "fake").unwrap();
let c = Config { background_path: Some(wp.to_str().unwrap().to_string()), fingerprint_enabled: true }; let c = Config { background_path: Some(wp.to_str().unwrap().to_string()), ..Config::default() };
assert_eq!(resolve_background_path_with(&c, Path::new("/nonexistent")), wp); assert_eq!(resolve_background_path_with(&c, Path::new("/nonexistent")), wp);
} }
#[test] fn empty_user_config_preserves_system_fingerprint() { #[test] fn empty_user_config_preserves_system_fingerprint() {

View File

@ -6,9 +6,14 @@ use gdk_pixbuf::Pixbuf;
use glib::clone; use glib::clone;
use gtk4::prelude::*; use gtk4::prelude::*;
use gtk4::{self as gtk, gio}; use gtk4::{self as gtk, gio};
use image::imageops;
use std::cell::RefCell; use std::cell::RefCell;
use std::path::Path; use std::fs;
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::rc::Rc; use std::rc::Rc;
use std::time::SystemTime;
use zeroize::Zeroizing; use zeroize::Zeroizing;
@ -41,7 +46,7 @@ struct LockscreenState {
/// Create a lockscreen window for a single monitor. /// Create a lockscreen window for a single monitor.
/// Fingerprint is not initialized here — use `wire_fingerprint()` after async init. /// Fingerprint is not initialized here — use `wire_fingerprint()` after async init.
pub fn create_lockscreen_window( pub fn create_lockscreen_window(
bg_path: &Path, bg_texture: &gdk::Texture,
_config: &Config, _config: &Config,
app: &gtk::Application, app: &gtk::Application,
unlock_callback: Rc<dyn Fn()>, unlock_callback: Rc<dyn Fn()>,
@ -82,7 +87,7 @@ pub fn create_lockscreen_window(
window.set_child(Some(&overlay)); window.set_child(Some(&overlay));
// Background wallpaper // Background wallpaper
let background = create_background_picture(bg_path); let background = create_background_picture(bg_texture);
overlay.set_child(Some(&background)); overlay.set_child(Some(&background));
// Centered vertical box // Centered vertical box
@ -413,13 +418,159 @@ pub fn start_fingerprint(
}); });
} }
/// Create a Picture widget for the wallpaper background. /// Load the wallpaper as a texture once, for sharing across all windows.
fn create_background_picture(bg_path: &Path) -> gtk::Picture { /// When `blur_radius` is `Some(sigma)` with sigma > 0, a Gaussian blur is applied.
let background = if bg_path.starts_with("/dev/moonarch/moonlock") { pub fn load_background_texture(bg_path: &Path, blur_radius: Option<f32>) -> gdk::Texture {
gtk::Picture::for_resource(bg_path.to_str().unwrap_or("")) let fallback = "/dev/moonarch/moonlock/wallpaper.jpg";
let texture = if bg_path.starts_with("/dev/moonarch/moonlock") {
let resource_path = bg_path.to_str().unwrap_or(fallback);
gdk::Texture::from_resource(resource_path)
} else { } else {
gtk::Picture::for_filename(bg_path.to_str().unwrap_or("")) let file = gio::File::for_path(bg_path);
gdk::Texture::from_file(&file).unwrap_or_else(|_| {
gdk::Texture::from_resource(fallback)
})
}; };
match blur_radius {
Some(sigma) if sigma > 0.0 => load_blurred_with_cache(bg_path, &texture, sigma),
_ => texture,
}
}
// -- Blur cache ----------------------------------------------------------------
const CACHE_PNG: &str = "blur-cache.png";
const CACHE_META: &str = "blur-cache.meta";
fn blur_cache_dir() -> Option<PathBuf> {
dirs::cache_dir().map(|d| d.join("moonlock"))
}
/// Build the cache key string for the current wallpaper + sigma.
fn build_cache_meta(bg_path: &Path, sigma: f32) -> Option<String> {
if bg_path.starts_with("/dev/moonarch/") {
let binary = std::env::current_exe().ok()?;
let binary_mtime = fs::metadata(&binary)
.ok()?
.modified()
.ok()?
.duration_since(SystemTime::UNIX_EPOCH)
.ok()?
.as_secs();
Some(format!(
"path={}\nbinary_mtime={}\nsigma={}\n",
bg_path.display(), binary_mtime, sigma,
))
} else {
let meta = fs::metadata(bg_path).ok()?;
let mtime = meta
.modified()
.ok()?
.duration_since(SystemTime::UNIX_EPOCH)
.ok()?
.as_secs();
Some(format!(
"path={}\nsize={}\nmtime={}\nsigma={}\n",
bg_path.display(), meta.len(), mtime, sigma,
))
}
}
/// Try to load a cached blurred texture if the cache key matches.
fn load_cached_blur(cache_dir: &Path, expected_meta: &str) -> Option<gdk::Texture> {
let stored_meta = fs::read_to_string(cache_dir.join(CACHE_META)).ok()?;
if stored_meta != expected_meta {
log::debug!("Blur cache meta mismatch, will re-blur");
return None;
}
let file = gio::File::for_path(cache_dir.join(CACHE_PNG));
match gdk::Texture::from_file(&file) {
Ok(texture) => {
log::debug!("Loaded blurred wallpaper from cache");
Some(texture)
}
Err(e) => {
log::debug!("Failed to load cached blur PNG: {e}");
None
}
}
}
/// Save a blurred texture to the cache directory.
fn save_blur_cache(cache_dir: &Path, texture: &gdk::Texture, meta: &str) {
if let Err(e) = save_blur_cache_inner(cache_dir, texture, meta) {
log::debug!("Failed to save blur cache: {e}");
}
}
fn save_blur_cache_inner(
cache_dir: &Path,
texture: &gdk::Texture,
meta: &str,
) -> Result<(), Box<dyn std::error::Error>> {
fs::create_dir_all(cache_dir)?;
let png_bytes = texture.save_to_png_bytes();
let mut f = fs::OpenOptions::new()
.create(true).write(true).truncate(true).mode(0o600)
.open(cache_dir.join(CACHE_PNG))?;
f.write_all(&png_bytes)?;
let mut f = fs::OpenOptions::new()
.create(true).write(true).truncate(true).mode(0o600)
.open(cache_dir.join(CACHE_META))?;
f.write_all(meta.as_bytes())?;
log::debug!("Saved blur cache to {}", cache_dir.display());
Ok(())
}
/// Load blurred texture, using disk cache when available.
fn load_blurred_with_cache(bg_path: &Path, texture: &gdk::Texture, sigma: f32) -> gdk::Texture {
if let Some(cache_dir) = blur_cache_dir() {
if let Some(meta) = build_cache_meta(bg_path, sigma) {
if let Some(cached) = load_cached_blur(&cache_dir, &meta) {
return cached;
}
let blurred = apply_blur(texture, sigma);
save_blur_cache(&cache_dir, &blurred, &meta);
return blurred;
}
}
apply_blur(texture, sigma)
}
// -- Blur implementation -------------------------------------------------------
/// Apply Gaussian blur to a texture and return a blurred texture.
fn apply_blur(texture: &gdk::Texture, sigma: f32) -> gdk::Texture {
let width = texture.width() as u32;
let height = texture.height() as u32;
let stride = width as usize * 4;
let mut pixel_data = vec![0u8; stride * height as usize];
texture.download(&mut pixel_data, stride);
let img = image::RgbaImage::from_raw(width, height, pixel_data)
.expect("pixel buffer size matches texture dimensions");
let blurred = imageops::blur(&image::DynamicImage::ImageRgba8(img), sigma);
let bytes = glib::Bytes::from(blurred.as_raw());
let mem_texture = gdk::MemoryTexture::new(
width as i32,
height as i32,
gdk::MemoryFormat::B8g8r8a8Premultiplied,
&bytes,
stride,
);
mem_texture.upcast()
}
/// Create a Picture widget for the wallpaper background from a shared texture.
fn create_background_picture(texture: &gdk::Texture) -> gtk::Picture {
let background = gtk::Picture::for_paintable(texture);
background.set_content_fit(gtk::ContentFit::Cover); background.set_content_fit(gtk::ContentFit::Cover);
background.set_hexpand(true); background.set_hexpand(true);
background.set_vexpand(true); background.set_vexpand(true);
@ -576,4 +727,60 @@ mod tests {
fn avatar_size_matches_css() { fn avatar_size_matches_css() {
assert_eq!(AVATAR_SIZE, 128); assert_eq!(AVATAR_SIZE, 128);
} }
// -- Blur cache tests --
#[test]
fn build_cache_meta_for_file() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("wallpaper.jpg");
fs::write(&file, b"fake image").unwrap();
let meta = build_cache_meta(&file, 20.0);
assert!(meta.is_some());
let meta = meta.unwrap();
assert!(meta.contains("path="));
assert!(meta.contains("size=10"));
assert!(meta.contains("sigma=20"));
}
#[test]
fn build_cache_meta_for_gresource() {
let path = Path::new("/dev/moonarch/moonlock/wallpaper.jpg");
let meta = build_cache_meta(path, 15.0);
assert!(meta.is_some());
let meta = meta.unwrap();
assert!(meta.contains("binary_mtime="));
assert!(meta.contains("sigma=15"));
assert!(!meta.contains("size="));
}
#[test]
fn build_cache_meta_missing_file() {
let meta = build_cache_meta(Path::new("/nonexistent/wallpaper.jpg"), 20.0);
assert!(meta.is_none());
}
#[test]
fn cache_meta_mismatch_returns_none() {
let dir = tempfile::tempdir().unwrap();
fs::write(
dir.path().join(CACHE_META),
"path=/old.jpg\nsize=100\nmtime=1\nsigma=20\n",
).unwrap();
let result = load_cached_blur(
dir.path(),
"path=/new.jpg\nsize=200\nmtime=2\nsigma=20\n",
);
assert!(result.is_none());
}
#[test]
fn cache_missing_meta_returns_none() {
let dir = tempfile::tempdir().unwrap();
let result = load_cached_blur(
dir.path(),
"path=/any.jpg\nsize=1\nmtime=1\nsigma=20\n",
);
assert!(result.is_none());
}
} }

View File

@ -14,7 +14,6 @@ use gtk4::prelude::*;
use gtk4::{self as gtk, gio}; use gtk4::{self as gtk, gio};
use gtk4_session_lock; use gtk4_session_lock;
use std::cell::RefCell; use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc; use std::rc::Rc;
use crate::fingerprint::FingerprintListener; use crate::fingerprint::FingerprintListener;
@ -42,14 +41,15 @@ fn activate(app: &gtk::Application) {
let config = config::load_config(None); let config = config::load_config(None);
let bg_path = config::resolve_background_path(&config); let bg_path = config::resolve_background_path(&config);
let bg_texture = lockscreen::load_background_texture(&bg_path, config.background_blur);
if gtk4_session_lock::is_supported() { if gtk4_session_lock::is_supported() {
activate_with_session_lock(app, &display, &bg_path, &config); activate_with_session_lock(app, &display, &bg_texture, &config);
} else { } else {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
{ {
log::warn!("ext-session-lock-v1 not supported — running in development mode"); log::warn!("ext-session-lock-v1 not supported — running in development mode");
activate_without_lock(app, &bg_path, &config); activate_without_lock(app, &bg_texture, &config);
} }
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
{ {
@ -62,7 +62,7 @@ fn activate(app: &gtk::Application) {
fn activate_with_session_lock( fn activate_with_session_lock(
app: &gtk::Application, app: &gtk::Application,
display: &gdk::Display, display: &gdk::Display,
bg_path: &PathBuf, bg_texture: &gdk::Texture,
config: &config::Config, config: &config::Config,
) { ) {
let lock = gtk4_session_lock::Instance::new(); let lock = gtk4_session_lock::Instance::new();
@ -87,7 +87,7 @@ fn activate_with_session_lock(
.and_then(|obj| obj.downcast::<gdk::Monitor>().ok()) .and_then(|obj| obj.downcast::<gdk::Monitor>().ok())
{ {
let handles = lockscreen::create_lockscreen_window( let handles = lockscreen::create_lockscreen_window(
bg_path, bg_texture,
config, config,
app, app,
unlock_callback.clone(), unlock_callback.clone(),
@ -144,7 +144,7 @@ fn init_fingerprint_async(all_handles: Vec<lockscreen::LockscreenHandles>) {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
fn activate_without_lock( fn activate_without_lock(
app: &gtk::Application, app: &gtk::Application,
bg_path: &PathBuf, bg_texture: &gdk::Texture,
config: &config::Config, config: &config::Config,
) { ) {
let app_clone = app.clone(); let app_clone = app.clone();
@ -153,7 +153,7 @@ fn activate_without_lock(
}); });
let handles = lockscreen::create_lockscreen_window( let handles = lockscreen::create_lockscreen_window(
bg_path, bg_texture,
config, config,
app, app,
unlock_callback, unlock_callback,