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.
This commit is contained in:
LGUG2Z committed 2025-09-30 11:02:38 -07:00
1 parent f4d9734655
commit 801be91508
9 files changed
+256 -34

No files matched your search

+2 -1
View File
@@ -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<KomorebiTheme>),
Theme(Box<KomorebiTheme>),
// Animation(bool, Option<AnimationPrefix>),
// AnimationDuration(u64, Option<AnimationPrefix>),
// AnimationFps(u64),
+43
View File
@@ -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::<NSNumber>()
&& 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> {
+8 -1
View File
@@ -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<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_focused_workspace: Option<usize>,
pub wallpaper: Option<Wallpaper>,
pub floating_layer_behaviour: Option<FloatingLayerBehaviour>,
}
@@ -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)?;
}
+1 -1
View File
@@ -381,7 +381,7 @@ pub fn handle_notifications(wm: Arc<Mutex<WindowManager>>) -> 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,
};
+4
View File
@@ -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();
+2 -2
View File
@@ -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::<VecDeque<_>>();
@@ -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::<VecDeque<_>>();
+26 -26
View File
@@ -121,20 +121,20 @@ pub struct ThemeOptions {
pub bar_accent: Option<komorebi_themes::Base16Value>,
}
// #[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<bool>,
// /// Specify Light or Dark variant for theme generation (default: Dark)
// #[serde(skip_serializing_if = "Option::is_none")]
// pub theme_options: Option<ThemeOptions>,
// }
#[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<bool>,
/// Specify Light or Dark variant for theme generation (default: Dark)
#[serde(skip_serializing_if = "Option::is_none")]
pub theme_options: Option<ThemeOptions>,
}
// 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<FloatingLayerBehaviour>,
// /// Specify a wallpaper for this workspace
// #[serde(skip_serializing_if = "Option::is_none")]
// pub wallpaper: Option<Wallpaper>,
/// Specify a wallpaper for this workspace
#[serde(skip_serializing_if = "Option::is_none")]
pub wallpaper: Option<Wallpaper>,
}
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<i32>,
// /// Specify a wallpaper for this monitor
// #[serde(skip_serializing_if = "Option::is_none")]
// pub wallpaper: Option<Wallpaper>,
/// Specify a wallpaper for this monitor
#[serde(skip_serializing_if = "Option::is_none")]
pub wallpaper: Option<Wallpaper>,
/// 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<FloatingLayerBehaviour>,
@@ -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
+30
View File
@@ -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)
}
}
+140 -3
View File
@@ -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<FloatingLayerBehaviour>,
pub wallpaper: Option<Wallpaper>,
#[serde(skip_serializing_if = "Option::is_none")]
pub workspace_config: Option<WorkspaceConfig>,
}
@@ -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<Wallpaper>,
) -> 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<Container> {
@@ -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<Wallpaper>,
) -> 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::<Base16ColourPalette>(
&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 {