From 801be9150810803229a97bfe0c08324e6119dfbe Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 30 Sep 2025 11:02:37 -0700 Subject: [PATCH] feat(wm): implement monitor/ws wallpapers This commit implements per-monitor and per-workspace wallpapers and integrates with the theme manager to optionally generate themes based on the palette of the wallpaper image. Mostly a lift-and-shift from komorebi for Windows. --- komorebi/src/core/mod.rs | 3 +- komorebi/src/macos_api.rs | 43 ++++++++ komorebi/src/monitor.rs | 9 +- komorebi/src/monitor_reconciliator.rs | 2 +- komorebi/src/process_command.rs | 4 + komorebi/src/state.rs | 4 +- komorebi/src/static_config.rs | 52 +++++----- komorebi/src/window_manager.rs | 30 ++++++ komorebi/src/workspace.rs | 143 +++++++++++++++++++++++++- 9 files changed, 256 insertions(+), 34 deletions(-) diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 9a1e0af2..87430cb4 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -4,6 +4,7 @@ use crate::core::default_layout::DefaultLayout; use crate::core::operation_direction::OperationDirection; use crate::core::pathext::ResolvedPathBuf; use crate::core::rect::Rect; +use crate::static_config::KomorebiTheme; use clap::ValueEnum; use color_eyre::eyre; use serde::Deserialize; @@ -361,7 +362,7 @@ pub enum SocketMessage { // WatchConfiguration(bool), // CompleteConfiguration, // AltFocusHack(bool), - // Theme(Box), + Theme(Box), // Animation(bool, Option), // AnimationDuration(u64, Option), // AnimationFps(u64), diff --git a/komorebi/src/macos_api.rs b/komorebi/src/macos_api.rs index 99ecde20..f4cd7829 100644 --- a/komorebi/src/macos_api.rs +++ b/komorebi/src/macos_api.rs @@ -19,10 +19,13 @@ use crate::window::RuleDebug; use crate::window::WindowInfo; use crate::window_manager::WindowManager; use color_eyre::eyre; +use color_eyre::eyre::OptionExt; +use dispatch2::DispatchQueue; use objc2::MainThreadMarker; use objc2_app_kit::NSDeviceDescriptionKey; use objc2_app_kit::NSEvent; use objc2_app_kit::NSScreen; +use objc2_app_kit::NSWorkspace; use objc2_application_services::AXUIElement; use objc2_application_services::AXValue; use objc2_application_services::AXValueType; @@ -36,14 +39,54 @@ use objc2_core_graphics::CGEvent; use objc2_core_graphics::CGEventSource; use objc2_core_graphics::CGEventSourceStateID; use objc2_core_graphics::CGMainDisplayID; +use objc2_foundation::NSDictionary; use objc2_foundation::NSNumber; +use objc2_foundation::NSString; +use objc2_foundation::NSURL; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::ffi::c_void; +use std::path::Path; use std::ptr::NonNull; pub struct MacosApi; +impl MacosApi { + pub fn set_wallpaper(path: &Path, display_id: u32) -> eyre::Result<()> { + let path_str = path.to_str().ok_or_eyre("Invalid path encoding")?; + + DispatchQueue::main().exec_sync(|| { + let ns_path = NSString::from_str(path_str); + let url = unsafe { NSURL::fileURLWithPath(&ns_path) }; + + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + let screens = NSScreen::screens(mtm); + + for screen in &screens { + if let Some(did) = screen + .deviceDescription() + .objectForKey(&NSDeviceDescriptionKey::from_str("NSScreenNumber")) + && let Ok(did) = did.downcast::() + && did.as_u32() == display_id + { + let workspace = unsafe { NSWorkspace::sharedWorkspace() }; + unsafe { + if let Err(error) = workspace.setDesktopImageURL_forScreen_options_error( + &url, + &screen, + &NSDictionary::new(), + ) { + tracing::warn!("failed to set wallpaper: {error}") + } + } + } + } + }); + + Ok(()) + } +} + impl MacosApi { #[tracing::instrument(skip_all)] pub fn load_monitor_information(wm: &mut WindowManager) -> Result<(), LibraryError> { diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 5b34e55e..b5401174 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -8,6 +8,7 @@ use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; use crate::macos_api::MacosApi; use crate::ring::Ring; +use crate::static_config::Wallpaper; use crate::workspace::Workspace; use crate::workspace::WorkspaceGlobals; use crate::workspace::WorkspaceLayer; @@ -67,6 +68,7 @@ pub struct Monitor { pub workspace_padding: Option, #[serde(skip_serializing_if = "Option::is_none")] pub last_focused_workspace: Option, + pub wallpaper: Option, pub floating_layer_behaviour: Option, } @@ -93,6 +95,7 @@ pub fn new( last_focused_workspace: None, container_padding: None, workspace_padding: None, + wallpaper: None, floating_layer_behaviour: None, } } @@ -122,6 +125,7 @@ impl Monitor { container_padding: None, workspace_padding: None, last_focused_workspace: None, + wallpaper: None, floating_layer_behaviour: None, } } @@ -141,6 +145,7 @@ impl Monitor { last_focused_workspace: None, container_padding: None, workspace_padding: None, + wallpaper: None, floating_layer_behaviour: None, } } @@ -211,9 +216,11 @@ impl Monitor { pub fn load_focused_workspace(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> { let focused_idx = self.focused_workspace_idx(); + let monitor_id = self.id; + let monitor_wp = self.wallpaper.clone(); for (i, workspace) in self.workspaces_mut().iter_mut().enumerate() { if i == focused_idx { - workspace.restore(mouse_follows_focus)?; + workspace.restore(mouse_follows_focus, monitor_id, &monitor_wp)?; } else { workspace.hide(None)?; } diff --git a/komorebi/src/monitor_reconciliator.rs b/komorebi/src/monitor_reconciliator.rs index cfa49d82..f44ceb0e 100644 --- a/komorebi/src/monitor_reconciliator.rs +++ b/komorebi/src/monitor_reconciliator.rs @@ -381,7 +381,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result // workspace_names: cached.workspace_names.clone(), container_padding: cached.container_padding, workspace_padding: cached.workspace_padding, - // wallpaper: cached.wallpaper.clone(), + wallpaper: cached.wallpaper.clone(), floating_layer_behaviour: cached.floating_layer_behaviour, }; diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 721a17b1..240607e8 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -38,6 +38,7 @@ use crate::notify_subscribers; use crate::state::GlobalState; use crate::state::State; use crate::static_config::StaticConfig; +use crate::theme_manager; use crate::window::AdhocWindow; use crate::window::RuleDebug; use crate::window::Window; @@ -1708,6 +1709,9 @@ impl WindowManager { border_manager::BORDER_OFFSET.store(offset, Ordering::SeqCst); border_manager::destroy_all_borders()?; } + SocketMessage::Theme(ref theme) => { + theme_manager::send_notification(*theme.clone()); + } } self.update_known_window_ids(); diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index d6627ff4..11c37b17 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -138,7 +138,7 @@ impl From<&WindowManager> for State { layer: workspace.layer, floating_layer_behaviour: workspace.floating_layer_behaviour, globals: workspace.globals, - // wallpaper: workspace.wallpaper.clone(), + wallpaper: workspace.wallpaper.clone(), workspace_config: None, }) .collect::>(); @@ -149,7 +149,7 @@ impl From<&WindowManager> for State { // workspace_names: monitor.workspace_names.clone(), container_padding: monitor.container_padding, workspace_padding: monitor.workspace_padding, - // wallpaper: monitor.wallpaper.clone(), + wallpaper: monitor.wallpaper.clone(), floating_layer_behaviour: monitor.floating_layer_behaviour, }) .collect::>(); diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index baae7867..e7a879be 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -121,20 +121,20 @@ pub struct ThemeOptions { pub bar_accent: Option, } -// #[serde_with::serde_as] -// #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -// pub struct Wallpaper { -// /// Path to the wallpaper image file -// #[serde_as(as = "ResolvedPathBuf")] -// pub path: PathBuf, -// /// Generate and apply Base16 theme for this wallpaper (default: true) -// #[serde(skip_serializing_if = "Option::is_none")] -// pub generate_theme: Option, -// /// Specify Light or Dark variant for theme generation (default: Dark) -// #[serde(skip_serializing_if = "Option::is_none")] -// pub theme_options: Option, -// } +#[serde_with::serde_as] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct Wallpaper { + /// Path to the wallpaper image file + #[serde_as(as = "ResolvedPathBuf")] + pub path: PathBuf, + /// Generate and apply Base16 theme for this wallpaper (default: true) + #[serde(skip_serializing_if = "Option::is_none")] + pub generate_theme: Option, + /// Specify Light or Dark variant for theme generation (default: Dark) + #[serde(skip_serializing_if = "Option::is_none")] + pub theme_options: Option, +} // serde_as must be before derive #[serde_with::serde_as] @@ -192,9 +192,9 @@ pub struct WorkspaceConfig { /// Determine what happens to a new window when the Floating workspace layer is active (default: Tile) #[serde(skip_serializing_if = "Option::is_none")] pub floating_layer_behaviour: Option, - // /// Specify a wallpaper for this workspace - // #[serde(skip_serializing_if = "Option::is_none")] - // pub wallpaper: Option, + /// Specify a wallpaper for this workspace + #[serde(skip_serializing_if = "Option::is_none")] + pub wallpaper: Option, } impl From<&Workspace> for WorkspaceConfig { @@ -274,7 +274,7 @@ impl From<&Workspace> for WorkspaceConfig { tile, layout_flip: value.layout_flip, floating_layer_behaviour: value.floating_layer_behaviour, - // wallpaper: None, + wallpaper: None, } } } @@ -299,9 +299,9 @@ pub struct MonitorConfig { /// Workspace padding (default: global) #[serde(skip_serializing_if = "Option::is_none")] pub workspace_padding: Option, - // /// Specify a wallpaper for this monitor - // #[serde(skip_serializing_if = "Option::is_none")] - // pub wallpaper: Option, + /// Specify a wallpaper for this monitor + #[serde(skip_serializing_if = "Option::is_none")] + pub wallpaper: Option, /// Determine what happens to a new window when the Floating workspace layer is active (default: Tile) #[serde(skip_serializing_if = "Option::is_none")] pub floating_layer_behaviour: Option, @@ -340,7 +340,7 @@ impl From<&Monitor> for MonitorConfig { window_based_work_area_offset_limit: Some(value.window_based_work_area_offset_limit), container_padding, workspace_padding, - // wallpaper: value.wallpaper.clone(), + wallpaper: value.wallpaper.clone(), floating_layer_behaviour: value.floating_layer_behaviour, } } @@ -1250,7 +1250,7 @@ impl StaticConfig { .unwrap_or(1); monitor.container_padding = monitor_config.container_padding; monitor.workspace_padding = monitor_config.workspace_padding; - // monitor.wallpaper = monitor_config.wallpaper.clone(); + monitor.wallpaper = monitor_config.wallpaper.clone(); monitor.floating_layer_behaviour = monitor_config.floating_layer_behaviour; monitor.update_workspaces_globals(offset); @@ -1416,7 +1416,7 @@ impl StaticConfig { .unwrap_or(1); monitor.container_padding = monitor_config.container_padding; monitor.workspace_padding = monitor_config.workspace_padding; - // monitor.wallpaper = monitor_config.wallpaper.clone(); + monitor.wallpaper = monitor_config.wallpaper.clone(); monitor.floating_layer_behaviour = monitor_config.floating_layer_behaviour; monitor.update_workspaces_globals(offset); @@ -1544,8 +1544,8 @@ impl StaticConfig { for i in 0..monitor_count { wm.update_focused_workspace_by_monitor_idx(i)?; - // let ws_idx = wm.focused_workspace_idx_for_monitor_idx(i)?; - // wm.apply_wallpaper_for_monitor_workspace(i, ws_idx)?; + let ws_idx = wm.focused_workspace_idx_for_monitor_idx(i)?; + wm.apply_wallpaper_for_monitor_workspace(i, ws_idx)?; } // to update the borders diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index a1064a78..0c11473a 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1558,6 +1558,8 @@ impl WindowManager { let focused_workspace_idx = monitor.focused_workspace_idx(); monitor.update_workspace_globals(focused_workspace_idx, offset); + let monitor_id = monitor.id; + let monitor_wp = monitor.wallpaper.clone(); let workspace = monitor .focused_workspace_mut() .ok_or_eyre("there is no workspace")?; @@ -1569,6 +1571,12 @@ impl WindowManager { } } + if (workspace.wallpaper.is_some() || monitor_wp.is_some()) + && let Err(error) = workspace.apply_wallpaper(monitor_id, &monitor_wp) + { + tracing::error!("failed to apply wallpaper: {}", error); + } + workspace.update()?; } @@ -3135,4 +3143,26 @@ impl WindowManager { Ok(()) } + + #[tracing::instrument(skip(self))] + pub fn apply_wallpaper_for_monitor_workspace( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + ) -> eyre::Result<()> { + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let monitor_id = monitor.id; + let monitor_wp = monitor.wallpaper.clone(); + + let workspace = monitor + .workspaces() + .get(workspace_idx) + .ok_or_eyre("there is no workspace")?; + + workspace.apply_wallpaper(monitor_id, &monitor_wp) + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index b0ffc544..fdf974ab 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -1,5 +1,7 @@ +use crate::DATA_DIR; use crate::container::Container; use crate::core::FloatingLayerBehaviour; +use crate::core::SocketMessage; use crate::core::WindowContainerBehaviour; use crate::core::arrangement::Axis; use crate::core::cycle_direction::CycleDirection; @@ -11,17 +13,23 @@ use crate::core::rect::Rect; use crate::lockable_sequence::LockableSequence; use crate::macos_api::MacosApi; use crate::ring::Ring; +use crate::static_config::KomorebiTheme; +use crate::static_config::Wallpaper; use crate::static_config::WorkspaceConfig; use crate::window::Window; use crate::window::WindowDetails; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use komorebi_themes::Base16ColourPalette; use serde::Deserialize; use serde::Serialize; use std::collections::HashMap; +use std::ffi::OsStr; use std::fmt::Display; use std::fmt::Formatter; +use std::io::Write; use std::num::NonZeroUsize; +use std::os::unix::net::UnixStream; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] @@ -53,6 +61,7 @@ pub struct Workspace { pub globals: WorkspaceGlobals, pub layer: WorkspaceLayer, pub floating_layer_behaviour: Option, + pub wallpaper: Option, #[serde(skip_serializing_if = "Option::is_none")] pub workspace_config: Option, } @@ -104,6 +113,7 @@ impl Default for Workspace { floating_windows: Default::default(), float_override: None, floating_layer_behaviour: None, + wallpaper: None, workspace_config: None, } } @@ -185,7 +195,7 @@ impl Workspace { self.float_override = config.float_override; self.layout_flip = config.layout_flip; self.floating_layer_behaviour = config.floating_layer_behaviour; - // self.wallpaper = config.wallpaper.clone(); + self.wallpaper = config.wallpaper.clone(); self.layout_options = config.layout_options; self.workspace_config = Some(config.clone()); @@ -678,13 +688,20 @@ impl Workspace { Ok(()) } - pub fn restore(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> { + pub fn restore( + &mut self, + mouse_follows_focus: bool, + monitor_id: u32, + monitor_wp: &Option, + ) -> eyre::Result<()> { if let Some(container) = &mut self.monocle_container { container.restore()?; if let Some(window) = container.focused_window() { window.focus(mouse_follows_focus)?; } + + return self.apply_wallpaper(monitor_id, monitor_wp); } let idx = self.focused_container_idx(); @@ -730,7 +747,7 @@ impl Workspace { floating_window.focus(mouse_follows_focus)?; } - Ok(()) + self.apply_wallpaper(monitor_id, monitor_wp) } pub fn remove_focused_container(&mut self) -> Option { @@ -1155,6 +1172,126 @@ impl Workspace { self.containers() .get(self.container_idx_for_window(window_id)?) } + + pub fn apply_wallpaper( + &self, + monitor_id: u32, + monitor_wp: &Option, + ) -> eyre::Result<()> { + if let Some(wallpaper) = self.wallpaper.as_ref().or(monitor_wp.as_ref()) { + if let Err(error) = MacosApi::set_wallpaper(&wallpaper.path, monitor_id) { + tracing::error!("failed to set wallpaper: {error}"); + } + + if wallpaper.generate_theme.unwrap_or(true) { + let variant = wallpaper + .theme_options + .as_ref() + .and_then(|t| t.theme_variant) + .unwrap_or_default(); + + let cached_palette = DATA_DIR.join(format!( + "{}.base16.{variant}.json", + wallpaper + .path + .file_name() + .unwrap_or(OsStr::new("tmp")) + .to_string_lossy() + )); + + let mut base16_palette = None; + + if cached_palette.is_file() { + tracing::info!( + "colour palette for wallpaper {} found in cache", + cached_palette.display() + ); + + // this code is VERY slow on debug builds - should only be a one-time issue when loading + // an uncached wallpaper + if let Ok(palette) = serde_json::from_str::( + &std::fs::read_to_string(&cached_palette)?, + ) { + base16_palette = Some(palette); + } + }; + + if base16_palette.is_none() { + base16_palette = + komorebi_themes::generate_base16_palette(&wallpaper.path, variant).ok(); + + std::fs::write( + &cached_palette, + serde_json::to_string_pretty(&base16_palette)?, + )?; + + tracing::info!( + "colour palette for wallpaper {} cached", + cached_palette.display() + ); + } + + if let Some(palette) = base16_palette { + let komorebi_theme = KomorebiTheme::Custom { + colours: Box::new(palette), + single_border: wallpaper + .theme_options + .as_ref() + .and_then(|o| o.single_border), + stack_border: wallpaper + .theme_options + .as_ref() + .and_then(|o| o.stack_border), + monocle_border: wallpaper + .theme_options + .as_ref() + .and_then(|o| o.monocle_border), + floating_border: wallpaper + .theme_options + .as_ref() + .and_then(|o| o.floating_border), + unfocused_border: wallpaper + .theme_options + .as_ref() + .and_then(|o| o.unfocused_border), + unfocused_locked_border: wallpaper + .theme_options + .as_ref() + .and_then(|o| o.unfocused_locked_border), + stackbar_focused_text: wallpaper + .theme_options + .as_ref() + .and_then(|o| o.stackbar_focused_text), + stackbar_unfocused_text: wallpaper + .theme_options + .as_ref() + .and_then(|o| o.stackbar_unfocused_text), + stackbar_background: wallpaper + .theme_options + .as_ref() + .and_then(|o| o.stackbar_background), + bar_accent: wallpaper.theme_options.as_ref().and_then(|o| o.bar_accent), + }; + + let bytes = SocketMessage::Theme(Box::new(komorebi_theme)).as_bytes()?; + + let socket = DATA_DIR.join("komorebi.sock"); + match UnixStream::connect(socket) { + Ok(mut stream) => { + if let Err(error) = stream.write_all(&bytes) { + tracing::error!("failed to send theme update message: {error}") + } + } + Err(error) => { + tracing::error!("{error}") + } + } + } + } + } + + Ok(()) + } } impl Workspace {