4 Commits

Author SHA1 Message Date
nevaforget 4d8e306b74 feat: add fade-out animation on dismiss for smooth visual exit
Without this, app.quit() destroys windows instantly, creating a jarring
pop-out. Now all windows fade out over 250ms (matching the fade-in)
before the app exits. Uses the same CSS opacity transition — just
removes the "visible" class and defers quit via glib timeout.
2026-03-28 21:50:03 +01:00
nevaforget 2e88a9b6c4 feat: activate fade-in animation for panel and wallpaper windows
The Rust code already adds a "visible" CSS class on map, but the
stylesheet had no corresponding opacity transition. Add 250ms ease-in
fade via GPU-accelerated CSS opacity to eliminate the visual pop-in.
2026-03-28 21:46:08 +01:00
nevaforget 412ed159a4 fix: address audit findings — blur channel mismatch, logout quit, config error logging
- Fix BGRA→RGBA channel swap in apply_blur so image::RgbaImage semantics
  match the actual pixel data from GDK texture download
- Logout now calls app.quit() like lock does, via new quit_after field on
  ActionDef (replaces fragile magic string comparison)
- Log TOML parse errors to stderr instead of silently ignoring
- Remove pointless zlib compression of JPEG wallpaper in GResource
- Add tests for quit_after behavior and config error handling
2026-03-28 21:39:34 +01:00
nevaforget 478caed8e0 perf: cache blurred wallpaper to disk to avoid re-blur on startup
First launch with blur blurs and saves to ~/.cache/moonset/. Subsequent
starts load the cached PNG directly (~9x faster). Cache invalidates
when wallpaper path, size, mtime, or sigma changes.
2026-03-28 21:22:48 +01:00
8 changed files with 295 additions and 16 deletions
+18
View File
@@ -3,11 +3,29 @@
All notable changes to this project will be documented in this file.
Format based on [Keep a Changelog](https://keepachangelog.com/).
## [0.4.1] - 2026-03-28
### Added
- Fade-in/fade-out animation (250ms ease-in) for panel and wallpaper windows via CSS opacity transition
### Fixed
- Fix pixel format mismatch in blur path — `texture.download()` yields BGRA but was passed to `RgbaImage` without channel swap, now explicitly converts B↔R
- Logout action now calls `app.quit()` to dismiss the menu immediately (previously only Lock did)
- Log TOML parse errors to stderr instead of silently falling back to defaults
### Changed
- Replace magic string `"lock"` comparison with `quit_after` field on `ActionDef` for type-safe action dispatch
- Remove `compressed="true"` from JPEG wallpaper in GResource — JPEG is already compressed, zlib overhead hurts startup for negligible size savings
## [0.4.0] - 2026-03-28
### Added
- Optional background blur via `background_blur` config option (Gaussian blur, `image` crate)
- Disk cache for blurred wallpaper (`~/.cache/moonset/`) — avoids re-blurring on subsequent starts
## [0.1.1] - 2026-03-28
Generated
+1 -1
View File
@@ -805,7 +805,7 @@ dependencies = [
[[package]]
name = "moonset"
version = "0.1.1"
version = "0.4.1"
dependencies = [
"dirs",
"env_logger",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "moonset"
version = "0.4.0"
version = "0.4.1"
edition = "2024"
description = "Wayland session power menu with GTK4 and Layer Shell"
license = "MIT"
+7
View File
@@ -2,6 +2,13 @@
Architectural and design decisions for Moonset, in reverse chronological order.
## 2026-03-28 Replace action name dispatch with `quit_after` field
- **Who**: Hekate, Dom
- **Why**: Post-action behavior (quit the app or not) was controlled by comparing `action_name == "lock"` — a magic string duplicated from the action definition. Renaming an action would silently break the dispatch.
- **Tradeoffs**: Adds a field to `ActionDef` that most actions set to `false`. Acceptable because it makes the contract explicit and testable.
- **How**: `ActionDef.quit_after: bool``true` for lock and logout, `false` for hibernate/reboot/shutdown.
## 2026-03-28 Optional background blur via `image` crate
- **Who**: Hekate, Dom
+1 -1
View File
@@ -2,7 +2,7 @@
<gresources>
<gresource prefix="/dev/moonarch/moonset">
<file>style.css</file>
<file compressed="true">wallpaper.jpg</file>
<file>wallpaper.jpg</file>
<file>default-avatar.svg</file>
</gresource>
</gresources>
+12
View File
@@ -6,11 +6,23 @@ window.panel {
background-color: @theme_bg_color;
background-size: cover;
background-position: center;
opacity: 0;
transition: opacity 250ms ease-in;
}
window.panel.visible {
opacity: 1;
}
/* Wallpaper-only window for secondary monitors */
window.wallpaper {
background-color: @theme_bg_color;
opacity: 0;
transition: opacity 250ms ease-in;
}
window.wallpaper.visible {
opacity: 1;
}
/* Round avatar image */
+41 -5
View File
@@ -31,12 +31,17 @@ pub fn load_config(config_paths: Option<&[PathBuf]>) -> Config {
let mut merged = Config::default();
for path in paths {
if let Ok(content) = fs::read_to_string(path) {
if let Ok(parsed) = toml::from_str::<Config>(&content) {
if parsed.background_path.is_some() {
merged.background_path = parsed.background_path;
match toml::from_str::<Config>(&content) {
Ok(parsed) => {
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 parsed.background_blur.is_some() {
merged.background_blur = parsed.background_blur;
Err(e) => {
eprintln!("Warning: failed to parse {}: {e}", path.display());
}
}
}
@@ -185,4 +190,35 @@ mod tests {
let result = resolve_background_path_with(&config, Path::new("/nonexistent"));
assert!(result.to_str().unwrap().contains("wallpaper.jpg"));
}
#[test]
fn load_config_ignores_invalid_toml_syntax() {
let dir = tempfile::tempdir().unwrap();
let conf = dir.path().join("bad.toml");
fs::write(&conf, "this is not valid [[[ toml").unwrap();
let paths = vec![conf];
let config = load_config(Some(&paths));
assert!(config.background_path.is_none());
assert!(config.background_blur.is_none());
}
#[test]
fn load_config_ignores_wrong_field_types() {
let dir = tempfile::tempdir().unwrap();
let conf = dir.path().join("wrong_type.toml");
fs::write(&conf, "background_blur = \"not_a_number\"\n").unwrap();
let paths = vec![conf];
let config = load_config(Some(&paths));
assert!(config.background_blur.is_none());
}
#[test]
fn load_config_accepts_negative_blur() {
let dir = tempfile::tempdir().unwrap();
let conf = dir.path().join("negative.toml");
fs::write(&conf, "background_blur = -5.0\n").unwrap();
let paths = vec![conf];
let config = load_config(Some(&paths));
assert_eq!(config.background_blur, Some(-5.0));
}
}
+214 -8
View File
@@ -8,8 +8,12 @@ use gtk4::prelude::*;
use gtk4::{self as gtk, gio};
use image::imageops;
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::time::{Duration, SystemTime};
use crate::i18n::{load_strings, Strings};
use crate::power::{self, PowerError};
@@ -27,6 +31,7 @@ pub struct ActionDef {
pub label_attr: fn(&Strings) -> &'static str,
pub error_attr: fn(&Strings) -> &'static str,
pub confirm_attr: Option<fn(&Strings) -> &'static str>,
pub quit_after: bool,
}
/// All 5 power action definitions.
@@ -40,6 +45,7 @@ pub fn action_definitions() -> Vec<ActionDef> {
label_attr: |s| s.lock_label,
error_attr: |s| s.lock_failed,
confirm_attr: None,
quit_after: true,
},
ActionDef {
name: "logout",
@@ -49,6 +55,7 @@ pub fn action_definitions() -> Vec<ActionDef> {
label_attr: |s| s.logout_label,
error_attr: |s| s.logout_failed,
confirm_attr: Some(|s| s.logout_confirm),
quit_after: true,
},
ActionDef {
name: "hibernate",
@@ -58,6 +65,7 @@ pub fn action_definitions() -> Vec<ActionDef> {
label_attr: |s| s.hibernate_label,
error_attr: |s| s.hibernate_failed,
confirm_attr: Some(|s| s.hibernate_confirm),
quit_after: false,
},
ActionDef {
name: "reboot",
@@ -67,6 +75,7 @@ pub fn action_definitions() -> Vec<ActionDef> {
label_attr: |s| s.reboot_label,
error_attr: |s| s.reboot_failed,
confirm_attr: Some(|s| s.reboot_confirm),
quit_after: false,
},
ActionDef {
name: "shutdown",
@@ -76,6 +85,7 @@ pub fn action_definitions() -> Vec<ActionDef> {
label_attr: |s| s.shutdown_label,
error_attr: |s| s.shutdown_failed,
confirm_attr: Some(|s| s.shutdown_confirm),
quit_after: false,
},
]
}
@@ -96,19 +106,132 @@ pub fn load_background_texture(bg_path: &Path, blur_radius: Option<f32>) -> gdk:
};
match blur_radius {
Some(sigma) if sigma > 0.0 => apply_blur(&texture, sigma),
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("moonset"))
}
/// 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)?;
// Meta last — incomplete cache is treated as a miss on next start
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];
// download() yields GDK_MEMORY_DEFAULT = B8G8R8A8_PREMULTIPLIED (BGRA byte order).
texture.download(&mut pixel_data, stride);
// Swap B↔R so image::RgbaImage channel semantics are correct.
for pixel in pixel_data.chunks_exact_mut(4) {
pixel.swap(0, 2);
}
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);
@@ -117,13 +240,24 @@ fn apply_blur(texture: &gdk::Texture, sigma: f32) -> gdk::Texture {
let mem_texture = gdk::MemoryTexture::new(
width as i32,
height as i32,
gdk::MemoryFormat::B8g8r8a8Premultiplied,
gdk::MemoryFormat::R8g8b8a8Premultiplied,
&bytes,
stride,
);
mem_texture.upcast()
}
/// Fade out all windows and quit the app after the CSS transition completes.
fn fade_out_and_quit(app: &gtk::Application) {
for window in app.windows() {
window.remove_css_class("visible");
}
let app = app.clone();
glib::timeout_add_local_once(Duration::from_millis(250), move || {
app.quit();
});
}
/// Create a wallpaper-only window for secondary monitors.
pub fn create_wallpaper_window(texture: &gdk::Texture, app: &gtk::Application) -> gtk::ApplicationWindow {
let window = gtk::ApplicationWindow::builder()
@@ -180,7 +314,7 @@ pub fn create_panel_window(texture: &gdk::Texture, app: &gtk::Application) -> gt
#[weak]
app,
move |_, _, _, _| {
app.quit();
fade_out_and_quit(&app);
}
));
background.add_controller(click_controller);
@@ -250,7 +384,7 @@ pub fn create_panel_window(texture: &gdk::Texture, app: &gtk::Application) -> gt
glib::Propagation::Proceed,
move |_, keyval, _, _| {
if keyval == gdk::Key::Escape {
app.quit();
fade_out_and_quit(&app);
glib::Propagation::Stop
} else {
glib::Propagation::Proceed
@@ -453,6 +587,7 @@ fn execute_action(
let action_fn = action_def.action_fn;
let action_name = action_def.name;
let quit_after = action_def.quit_after;
let error_message = (action_def.error_attr)(strings).to_string();
// Use glib::spawn_future_local + gio::spawn_blocking to avoid Send issues
@@ -468,9 +603,8 @@ fn execute_action(
match result {
Ok(Ok(())) => {
// Lock action: quit after successful execution
if action_name == "lock" {
app.quit();
if quit_after {
fade_out_and_quit(&app);
}
}
Ok(Err(e)) => {
@@ -627,4 +761,76 @@ mod tests {
let confirm_fn = defs[1].confirm_attr.unwrap();
assert_eq!(confirm_fn(strings), "Wirklich abmelden?");
}
#[test]
fn lock_and_logout_quit_after() {
let defs = action_definitions();
assert!(defs[0].quit_after, "lock should quit after");
assert!(defs[1].quit_after, "logout should quit after");
}
#[test]
fn destructive_actions_do_not_quit_after() {
let defs = action_definitions();
for def in &defs[2..] {
assert!(!def.quit_after, "{} should not quit after", def.name);
}
}
// -- 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"));
assert!(meta.contains("mtime="));
}
#[test]
fn build_cache_meta_for_gresource() {
let path = Path::new("/dev/moonarch/moonset/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());
}
}