feat(wm): migrate ipc and impl basic socket messages

This commit migrates another bunch of code from komorebi to start
implementing inter-process communication using Unix domain sockets.

For this commit a small subsection of the SocketMessage with maximum
utility has been migrated: FocusWindow, MoveWindow, ChangeLayout, and
TogglePause.

This includes migrating their handlers in process_command, and setting
up a UnixListener when creating a WindowManager instance.

To be able to test this functionality I also implemented a basic
skeleton of komorebic and migrated the komorebi-client library.

There are some random fixes included here now that we are listening to a
UnixListener on a separate thread, which includes wrapping structs from
the objc2 crate which don't have Send and Sync implemented, so that they
can be implemented in the komorebi lib.

I also took the time to figure out how to calculate a monitor's work
area size, excluding the dock and the menu bar, and started to split out
Workspace and Monitor into their own modules.

It looks like a lot of changes but most if this is just pulling in stuff
from the Windows implementation.
This commit is contained in:
LGUG2Z committed 2025-09-17 16:18:06 -07:00
1 parent b6d19e6a12
commit df9ceee17e
26 files changed
+2375 -103

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
/target
/result
/result*
/.idea
/.direnv
Generated
+911 -11
View File
File diff suppressed because it is too large. Load diff
+14 -2
View File
@@ -2,5 +2,17 @@
resolver = "2"
members = [
"komorebi",
]
"komorebi", "komorebi-client",
"komorebic",
]
[workspace.dependencies]
clap = { version = "4", features = ["derive", "wrap_help"] }
color-eyre = "0.6"
dirs = "6"
lazy_static = "1"
pastey = "0.1"
serde = { version = "1", features = ["derive"] }
serde_json = { package = "serde_json_lenient", version = "0.2" }
thiserror = "2"
+23 -14
View File
@@ -13,6 +13,7 @@
overlays = [
(import rust-overlay)
];
pkgs = (import nixpkgs) {
inherit system overlays;
};
@@ -21,15 +22,12 @@
toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
craneLib = (crane.mkLib pkgs).overrideToolchain toolchain;
pname = "komorebi";
src = craneLib.cleanCargoSource ./.;
version = "0.1.0";
commonArgs = {
inherit pname version;
nativeBuildInputs = with pkgs; [
# pkg-config
];
inherit src;
nativeBuildInputs = with pkgs; [];
doCheck = false;
buildInputs = with pkgs; [
gcc
@@ -37,23 +35,34 @@
];
};
cargoArtifacts = craneLib.buildDepsOnly (commonArgs
// {
src = craneLib.cleanCargoSource (craneLib.path ./.);
});
cargoArtifacts = craneLib.buildDepsOnly commonArgs;
komorebi = craneLib.buildPackage (commonArgs
komorebi = craneLib.buildPackage (
commonArgs
// {
inherit cargoArtifacts;
inherit version;
pname = "komorebi";
cargoExtraArgs = "-p komorebi";
src = ./.;
});
}
);
komorebic = craneLib.buildPackage (
commonArgs
// {
inherit version;
pname = "komorebic";
cargoExtraArgs = "-p komorebic";
src = ./.;
}
);
in {
devShells = flake-utils.lib.flattenTree {
default = import ./shell.nix {inherit pkgs;};
};
packages = flake-utils.lib.flattenTree rec {
inherit komorebi;
inherit komorebi komorebic;
default = komorebi;
};
}
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "komorebi-client"
version = "0.1.0"
edition = "2024"
[dependencies]
komorebi = { path = "../komorebi", default-features = false }
serde_json = { workspace = true }
+54
View File
@@ -0,0 +1,54 @@
pub use komorebi::DATA_DIR;
pub use komorebi::core::SocketMessage;
pub use komorebi::core::default_layout::DefaultLayout;
pub use komorebi::core::operation_direction::OperationDirection;
pub use komorebi::core::pathext::PathExt;
use std::borrow::Borrow;
use std::io::BufReader;
use std::io::Read;
use std::io::Write;
use std::net::Shutdown;
use std::os::unix::net::UnixStream;
use std::time::Duration;
const KOMOREBI: &str = "komorebi.sock";
pub fn send_message(message: &SocketMessage) -> std::io::Result<()> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
stream.write_all(serde_json::to_string(message)?.as_bytes())
}
pub fn send_batch<Q>(messages: impl IntoIterator<Item = Q>) -> std::io::Result<()>
where
Q: Borrow<SocketMessage>,
{
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
let msgs = messages.into_iter().fold(String::new(), |mut s, m| {
if let Ok(m_str) = serde_json::to_string(m.borrow()) {
s.push_str(&m_str);
s.push('\n');
}
s
});
stream.write_all(msgs.as_bytes())
}
pub fn send_query(message: &SocketMessage) -> std::io::Result<String> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
stream.write_all(serde_json::to_string(message)?.as_bytes())?;
stream.shutdown(Shutdown::Write)?;
let mut reader = BufReader::new(stream);
let mut response = String::new();
reader.read_to_string(&mut response)?;
Ok(response)
}
+11 -4
View File
@@ -4,15 +4,22 @@ version = "0.1.0"
edition = "2024"
[dependencies]
color-eyre = { version = "0.6" }
clap = { workspace = true }
color-eyre = { workspace = true }
ctrlc = { version = "3", features = ["termination"] }
dirs = { workspace = true }
lazy_static = { workspace = true }
objc2 = "0.6"
objc2-app-kit = "0.3"
objc2-application-services = "0.3"
objc2-core-foundation = { version = "0.3", features = ["CFDictionary", "CFString"] }
objc2-core-graphics = { version = "0.3", features = ["CGWindow", "alloc"] }
pastey = "0.1"
serde = { version = "1", features = ["derive"]}
thiserror = "2"
parking_lot = "0.12"
pastey = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
serde_with = "3"
strum = { version = "0.27", features = ["derive"] }
thiserror = { workspace = true }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+1 -1
View File
@@ -134,7 +134,7 @@ impl AccessibilityApi {
observer: &AXObserver,
element: &AXUIElement,
notifications: &[&'static str],
run_loop: &CFRetained<CFRunLoop>,
run_loop: &CFRunLoop,
) -> Result<(), AccessibilityError> {
AccessibilityApi::add_notifications_to_observer(observer, element, notifications)?;
+8 -6
View File
@@ -1,3 +1,5 @@
use crate::AccessibilityObserver;
use crate::AccessibilityUiElement;
use crate::accessibility::AccessibilityApi;
use crate::accessibility::attribute_constants::kAXTitleAttribute;
use crate::accessibility::attribute_constants::kAXWindowsAttribute;
@@ -36,9 +38,9 @@ const NOTIFICATIONS: &[&str] = &[
#[derive(Debug, Clone)]
pub struct Application {
element: CFRetained<AXUIElement>,
element: AccessibilityUiElement,
pub process_id: i32,
pub observer: CFRetained<AXObserver>,
pub observer: AccessibilityObserver,
}
#[instrument(skip_all)]
@@ -84,12 +86,12 @@ impl Drop for Application {
impl Application {
pub fn new(process_id: i32) -> Result<Self, AccessibilityError> {
Ok(Self {
element: AccessibilityApi::create_application(process_id),
element: AccessibilityUiElement(AccessibilityApi::create_application(process_id)),
process_id,
observer: AccessibilityApi::create_observer(
observer: AccessibilityObserver(AccessibilityApi::create_observer(
process_id,
Some(application_observer_callback),
)?,
)?),
})
}
@@ -99,7 +101,7 @@ impl Application {
}
#[tracing::instrument(skip_all)]
pub fn observe(&self, run_loop: &CFRetained<CFRunLoop>) -> Result<(), AccessibilityError> {
pub fn observe(&self, run_loop: &CFRunLoop) -> Result<(), AccessibilityError> {
tracing::info!(
"registering observer for process: {}, name: {}",
self.process_id,
+2 -1
View File
@@ -1,10 +1,11 @@
use crate::core::Sizing;
use crate::core::operation_direction::OperationDirection;
use crate::core::rect::Rect;
use clap::ValueEnum;
use serde::Deserialize;
use serde::Serialize;
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq, ValueEnum)]
pub enum DefaultLayout {
BSP,
Columns,
+31
View File
@@ -1,11 +1,17 @@
use crate::core::default_layout::DefaultLayout;
use crate::core::operation_direction::OperationDirection;
use color_eyre::eyre;
use serde::Deserialize;
use serde::Serialize;
use std::str::FromStr;
use strum::Display;
pub mod arrangement;
pub mod default_layout;
pub mod direction;
pub mod layout;
pub mod operation_direction;
pub mod pathext;
pub mod rect;
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
@@ -13,3 +19,28 @@ pub enum Sizing {
Increase,
Decrease,
}
#[serde_with::serde_as]
#[derive(Clone, Debug, Serialize, Deserialize, Display)]
#[serde(tag = "type", content = "content")]
pub enum SocketMessage {
// Window / Container Commands
FocusWindow(OperationDirection),
MoveWindow(OperationDirection),
ChangeLayout(DefaultLayout),
TogglePause,
}
impl SocketMessage {
pub fn as_bytes(&self) -> eyre::Result<Vec<u8>> {
Ok(serde_json::to_string(self)?.as_bytes().to_vec())
}
}
impl FromStr for SocketMessage {
type Err = serde_json::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
serde_json::from_str(s)
}
}
+3 -3
View File
@@ -1,11 +1,11 @@
use std::num::NonZeroUsize;
use crate::core::arrangement::Axis;
use crate::core::direction::Direction;
use clap::ValueEnum;
use serde::Deserialize;
use serde::Serialize;
use std::num::NonZeroUsize;
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, Serialize, Deserialize, ValueEnum)]
pub enum OperationDirection {
Left,
Right,
+196
View File
@@ -0,0 +1,196 @@
use std::collections::HashMap;
use std::env;
use std::ffi::OsStr;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use serde::Deserialize;
use serde::Serialize;
/// Path extension trait
pub trait PathExt {
/// Resolve environment variable components in a path.
///
/// Resolves the following formats:
/// - CMD: `%variable%`
/// - PowerShell: `$Env:variable`
/// - Bash: `$variable`.
fn replace_env(&self) -> PathBuf;
}
/// Blanket implementation for all types that can be converted to a `Path`.
impl<P: AsRef<Path>> PathExt for P {
fn replace_env(&self) -> PathBuf {
let mut out = PathBuf::new();
for c in self.as_ref().components() {
match c {
Component::Normal(mut c) => {
// Special case for ~ and $HOME, replace with $Env:USERPROFILE
if c == OsStr::new("~") || c.eq_ignore_ascii_case("$HOME") {
c = OsStr::new("$Env:USERPROFILE");
}
let bytes = c.as_encoded_bytes();
// %LOCALAPPDATA%
let var = if bytes[0] == b'%' && bytes[bytes.len() - 1] == b'%' {
Some(&bytes[1..bytes.len() - 1])
} else {
// prefix length is 5 for $Env: and 1 for $
// so we take the minimum of 5 and the length of the bytes
let prefix = &bytes[..5.min(bytes.len())];
let prefix = unsafe { OsStr::from_encoded_bytes_unchecked(prefix) };
// $Env:LOCALAPPDATA
if prefix.eq_ignore_ascii_case("$Env:") {
Some(&bytes[5..])
} else if bytes[0] == b'$' {
// $LOCALAPPDATA
Some(&bytes[1..])
} else {
// not a variable
None
}
};
// if component is a variable, get the value from the environment
if let Some(var) = var {
let var = unsafe { OsStr::from_encoded_bytes_unchecked(var) };
if let Some(value) = env::var_os(var) {
out.push(value);
continue;
}
}
// if not a variable, or a value couldn't be obtained from environemnt
// then push the component as is
out.push(c);
}
// other components are pushed as is
_ => out.push(c),
}
}
out
}
}
/// Replace environment variables in a path. This is a wrapper around
/// [`PathExt::replace_env`] to be used in Clap arguments parsing.
pub fn replace_env_in_path(input: &str) -> Result<PathBuf, std::convert::Infallible> {
Ok(input.replace_env())
}
/// A wrapper around [`PathBuf`] that has a custom [Deserialize] implementation
/// that uses [`PathExt::replace_env`] to resolve environment variables
#[derive(Clone, Debug)]
pub struct ResolvedPathBuf(PathBuf);
impl ResolvedPathBuf {
/// Create a new [`ResolvedPathBuf`] from a [`PathBuf`]
pub fn new(path: PathBuf) -> Self {
Self(path.replace_env())
}
}
impl From<ResolvedPathBuf> for PathBuf {
fn from(path: ResolvedPathBuf) -> Self {
path.0
}
}
impl serde_with::SerializeAs<PathBuf> for ResolvedPathBuf {
fn serialize_as<S>(path: &PathBuf, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
path.serialize(serializer)
}
}
impl<'de> serde_with::DeserializeAs<'de, PathBuf> for ResolvedPathBuf {
fn deserialize_as<D>(deserializer: D) -> Result<PathBuf, D::Error>
where
D: serde::Deserializer<'de>,
{
let path = PathBuf::deserialize(deserializer)?;
Ok(path.replace_env())
}
}
// #[cfg(feature = "schemars")]
// impl serde_with::schemars_0_8::JsonSchemaAs<PathBuf> for ResolvedPathBuf {
// fn schema_name() -> String {
// "PathBuf".to_owned()
// }
//
// fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
// <PathBuf as schemars::JsonSchema>::json_schema(gen)
// }
// }
/// Custom deserializer for [`Option<HashMap<usize, PathBuf>>`] that uses
/// [`PathExt::replace_env`] to resolve environment variables in the paths.
///
/// This is used in `WorkspaceConfig` struct because we can't use
/// #[serde_with::serde_as] as it doesn't handle [`Option<HashMap<usize, ResolvedPathBuf>>`]
/// quite well and generated compiler errors that can't be fixed because of Rust's orphan rule.
pub fn resolve_option_hashmap_usize_path<'de, D>(
deserializer: D,
) -> Result<Option<HashMap<usize, PathBuf>>, D::Error>
where
D: serde::Deserializer<'de>,
{
let map = Option::<HashMap<usize, PathBuf>>::deserialize(deserializer)?;
Ok(map.map(|map| map.into_iter().map(|(k, v)| (k, v.replace_env())).collect()))
}
#[cfg(test)]
mod tests {
use super::*;
// helper functions
fn expected<P: AsRef<Path>>(p: P) -> PathBuf {
// Ensure that the path is using the correct path separator for the OS.
p.as_ref().components().collect::<PathBuf>()
}
fn resolve<P: AsRef<Path>>(p: P) -> PathBuf {
p.replace_env()
}
#[test]
fn resolves_env_vars() {
// Set a variable for testing
unsafe {
std::env::set_var("VAR", "VALUE");
}
// %VAR% format
assert_eq!(resolve("/path/%VAR%/d"), expected("/path/VALUE/d"));
// $env:VAR format
assert_eq!(resolve("/path/$env:VAR/d"), expected("/path/VALUE/d"));
// $VAR format
assert_eq!(resolve("/path/$VAR/d"), expected("/path/VALUE/d"));
// non-existent variable
assert_eq!(resolve("/path/%ASD%/to/d"), expected("/path/%ASD%/to/d"));
assert_eq!(
resolve("/path/$env:ASD/to/d"),
expected("/path/$env:ASD/to/d")
);
assert_eq!(resolve("/path/$ASD/to/d"), expected("/path/$ASD/to/d"));
// Set a $env:USERPROFILE variable for testing
unsafe {
std::env::set_var("USERPROFILE", "C:\\Users\\user");
}
// ~ and $HOME should be replaced with $Env:USERPROFILE
assert_eq!(resolve("~"), expected("C:\\Users\\user"));
assert_eq!(resolve("$HOME"), expected("C:\\Users\\user"));
}
}
+15
View File
@@ -1,10 +1,13 @@
use crate::core_graphics::error::CoreGraphicsError;
use objc2_core_foundation::CFArray;
use objc2_core_foundation::CFRetained;
use objc2_core_foundation::CGFloat;
use objc2_core_foundation::CGPoint;
use objc2_core_foundation::CGRect;
use objc2_core_graphics::CGDisplayBounds;
use objc2_core_graphics::CGGetOnlineDisplayList;
use objc2_core_graphics::CGRectIntersectsRect;
use objc2_core_graphics::CGWarpMouseCursorPosition;
use objc2_core_graphics::CGWindowListCopyWindowInfo;
use objc2_core_graphics::CGWindowListOption;
use objc2_core_graphics::kCGNullWindowID;
@@ -14,6 +17,18 @@ pub mod error;
pub struct CoreGraphicsApi;
impl CoreGraphicsApi {
pub fn warp_mouse_cursor_position(x: i32, y: i32) -> Result<(), CoreGraphicsError> {
match unsafe {
CoreGraphicsError::from(CGWarpMouseCursorPosition(CGPoint::new(
x as CGFloat,
y as CGFloat,
)))
} {
CoreGraphicsError::Success => Ok(()),
error => Err(error),
}
}
pub fn contains_rect(smaller: CGRect, bigger: CGRect) -> bool {
unsafe { CGRectIntersectsRect(smaller, bigger) }
}
+70
View File
@@ -2,10 +2,19 @@
use crate::accessibility::error::AccessibilityError;
use crate::core_graphics::error::CoreGraphicsError;
use core::pathext::PathExt;
use lazy_static::lazy_static;
use objc2_application_services::AXObserver;
use objc2_application_services::AXUIElement;
use objc2_core_foundation::CFArray;
use objc2_core_foundation::CFDictionary;
use objc2_core_foundation::CFRetained;
use objc2_core_foundation::CFRunLoop;
use objc2_core_foundation::CFString;
use std::ops::Deref;
use std::path::PathBuf;
use std::ptr::NonNull;
use std::sync::atomic::AtomicI32;
#[macro_use]
pub mod ring;
@@ -14,11 +23,72 @@ pub mod accessibility;
pub mod application;
pub mod core;
pub mod core_graphics;
pub mod lockable_sequence;
pub mod macos_api;
mod monitor;
pub mod process_command;
pub mod window;
pub mod window_manager;
pub mod workspace;
lazy_static! {
pub static ref HOME_DIR: PathBuf = {
std::env::var("KOMOREBI_CONFIG_HOME").map_or_else(|_| dirs::home_dir().expect("there is no home directory"), |home_path| {
let home = home_path.replace_env();
assert!(
home.is_dir(),
"$Env:KOMOREBI_CONFIG_HOME is set to '{home_path}', which is not a valid directory"
);
home
})
};
pub static ref DATA_DIR: PathBuf = dirs::data_local_dir()
.expect("there is no local data directory")
.join("komorebi");
}
pub static DEFAULT_WORKSPACE_PADDING: AtomicI32 = AtomicI32::new(5);
pub static DEFAULT_CONTAINER_PADDING: AtomicI32 = AtomicI32::new(5);
#[derive(Debug)]
pub struct CoreFoundationRunLoop(pub CFRetained<CFRunLoop>);
unsafe impl Sync for CoreFoundationRunLoop {}
unsafe impl Send for CoreFoundationRunLoop {}
impl Deref for CoreFoundationRunLoop {
type Target = CFRunLoop;
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
#[derive(Debug, Clone)]
pub struct AccessibilityUiElement(pub CFRetained<AXUIElement>);
unsafe impl Sync for AccessibilityUiElement {}
unsafe impl Send for AccessibilityUiElement {}
impl Deref for AccessibilityUiElement {
type Target = AXUIElement;
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
#[derive(Debug, Clone)]
pub struct AccessibilityObserver(pub CFRetained<AXObserver>);
unsafe impl Sync for AccessibilityObserver {}
unsafe impl Send for AccessibilityObserver {}
impl Deref for AccessibilityObserver {
type Target = AXObserver;
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
pub fn cf_array_as<T>(array: &CFArray) -> impl Iterator<Item = NonNull<T>> + use<'_, T> {
let count = CFArray::count(array);
(0..count).flat_map(move |idx| {
+363
View File
@@ -0,0 +1,363 @@
use std::collections::VecDeque;
/// A trait for types that can be marked as locked or unlocked.
pub trait Lockable {
/// Returns `true` if the item is locked.
fn locked(&self) -> bool;
/// Sets the locked state of the item.
fn set_locked(&mut self, locked: bool) -> &mut Self;
}
/// A sequence supporting insertion, removal, and swapping of elements while preserving the absolute
/// positions of locked items.
pub trait LockableSequence<T: Lockable> {
/// Inserts a value at `idx`, keeping locked elements at their absolute positions.
fn insert_respecting_locks(&mut self, idx: usize, value: T) -> usize;
/// Removes the element at `idx`, keeping locked elements at their absolute positions.
fn remove_respecting_locks(&mut self, idx: usize) -> Option<T>;
/// Swaps the elements at indices `i` and `j`, keeping locked elements at their absolute positions.
fn swap_respecting_locks(&mut self, i: usize, j: usize);
}
impl<T: Lockable> LockableSequence<T> for VecDeque<T> {
/// Insert `value` at logical index `idx`, with trying to keep locked elements
/// (`is_locked()`) anchored at their original positions.
///
/// Returns the final index of the inserted element.
fn insert_respecting_locks(&mut self, mut idx: usize, value: T) -> usize {
// 1. Bounds check: if index is out of range, simply append.
if idx >= self.len() {
self.push_back(value);
return self.len() - 1; // last index
}
// 2. Normal VecDeque insertion
self.insert(idx, value);
// 3. Walk left-to-right once, swapping any misplaced locked element. After
// the VecDeque::insert all items after `idx` have moved right by one. For every locked
// element that is now to the right of an unlocked one, swap it back left exactly once.
for index in (idx + 1)..self.len() {
if self[index].locked() && !self[index - 1].locked() {
self.swap(index - 1, index);
// If the element we just inserted participated in the swap,
// update `idx` so we can return its final location.
if idx == index - 1 {
idx = index;
}
}
}
idx
}
/// Remove element at `idx`, with trying to keep locked elements
/// (`is_locked()`) anchored at their original positions.
///
/// Returns the removed element, or `None` if `idx` is out of bounds.
fn remove_respecting_locks(&mut self, idx: usize) -> Option<T> {
// 1. Bounds check: if index is out of range, do nothing.
if idx >= self.len() {
return None;
}
// 2. Remove the element at the requested index.
// All elements after idx are now shifted left by 1.
let removed = self.remove(idx)?;
// 3. If less than 2 elements remain, nothing to shift.
if self.len() < 2 {
return Some(removed);
}
// 4. Iterate from the element just after the removed spot up to the second-to-last
// element, right-to-left. This loop "fixes" locked elements that were shifted left
// off their anchored positions: If a locked element now has an unlocked element
// to its right, swap them back to restore locked order.
for index in (idx..self.len() - 1).rev() {
// If current is locked and the next one is not locked, swap them.
if self[index].locked() && !self[index + 1].locked() {
self.swap(index, index + 1);
}
}
// 5. Return the removed value.
Some(removed)
}
/// Swaps the elements at indices `i` and `j`, along with their `locked` status, ensuring
/// the lock state remains associated with the position rather than the element itself.
fn swap_respecting_locks(&mut self, i: usize, j: usize) {
self.swap(i, j);
let locked_i = self[i].locked();
let locked_j = self[j].locked();
self[i].set_locked(locked_j);
self[j].set_locked(locked_i);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, PartialEq)]
struct TestItem {
val: i32,
locked: bool,
}
impl Lockable for TestItem {
fn locked(&self) -> bool {
self.locked
}
fn set_locked(&mut self, locked: bool) -> &mut Self {
self.locked = locked;
self
}
}
fn vals(v: &VecDeque<TestItem>) -> Vec<i32> {
v.iter().map(|x| x.val).collect()
}
fn test_deque(items: &[(i32, bool)]) -> VecDeque<TestItem> {
items
.iter()
.cloned()
.map(|(val, locked)| TestItem { val, locked })
.collect()
}
#[test]
fn test_insert_respecting_locks() {
// Test case 1: Basic insertion with locked index
{
// Lock index 2
let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]);
// Insert at index 0, should shift elements while keeping index 2 locked
ring.insert_respecting_locks(
0,
TestItem {
val: 99,
locked: false,
},
);
// Element '2' remains at index 2, element '1' that was at index 1 is now at index 3
assert_eq!(vals(&ring), vec![99, 0, 2, 1, 3, 4]);
}
// Test case 2: Insert at a locked index (should insert after locked)
{
// Lock index 2
let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]);
// Try to insert at locked index 2, should insert at index 3 instead
let actual_index = ring.insert_respecting_locks(
2,
TestItem {
val: 99,
locked: false,
},
);
assert_eq!(actual_index, 3);
assert_eq!(vals(&ring), vec![0, 1, 2, 99, 3, 4]);
}
// Test case 3: Multiple locked indices
{
// Lock index 1 and 3
let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, true), (4, false)]);
// Insert at index 0, should maintain locked indices
ring.insert_respecting_locks(
0,
TestItem {
val: 99,
locked: false,
},
);
// Elements '1' and '3' remain at indices 1 and 3
assert_eq!(vals(&ring), vec![99, 1, 0, 3, 2, 4]);
}
// Test case 4: Insert at end
{
// Lock index 2
let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]);
let actual_index = ring.insert_respecting_locks(
5,
TestItem {
val: 99,
locked: false,
},
);
assert_eq!(actual_index, 5);
assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4, 99]);
}
// Test case 5: Empty ring
{
let mut ring = test_deque(&[]);
// Insert into empty deque
let actual_index = ring.insert_respecting_locks(
0,
TestItem {
val: 99,
locked: false,
},
);
assert_eq!(actual_index, 0);
assert_eq!(vals(&ring), vec![99]);
}
// Test case 6: All indices locked
{
// Lock all indices
let mut ring = test_deque(&[(0, true), (1, true), (2, true), (3, true), (4, true)]);
// Try to insert at index 2, should insert at the end
let actual_index = ring.insert_respecting_locks(
2,
TestItem {
val: 99,
locked: false,
},
);
assert_eq!(actual_index, 5);
assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4, 99]);
}
// Test case 7: Consecutive locked indices
{
// Lock index 2 and 3
let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, true), (4, false)]);
// Insert at index 1, should maintain consecutive locked indices
ring.insert_respecting_locks(
1,
TestItem {
val: 99,
locked: false,
},
);
// Elements '2' and '3' remain at indices 2 and 3
assert_eq!(vals(&ring), vec![0, 99, 2, 3, 1, 4]);
}
}
#[test]
fn test_remove_respecting_locks() {
// Test case 1: Remove a non-locked index before a locked index
{
// Lock index 2
let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]);
let removed = ring.remove_respecting_locks(0);
assert_eq!(removed.map(|x| x.val), Some(0));
// Elements '2' remain at index 2
assert_eq!(vals(&ring), vec![1, 3, 2, 4]);
}
// Test case 2: Remove a locked index
{
// Lock index 2
let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]);
let removed = ring.remove_respecting_locks(2);
assert_eq!(removed.map(|x| x.val), Some(2));
// Elements should stay at the same places
assert_eq!(vals(&ring), vec![0, 1, 3, 4]);
}
// Test case 3: Remove an index after a locked index
{
// Lock index 1
let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, false), (4, false)]);
let removed = ring.remove_respecting_locks(3);
assert_eq!(removed.map(|x| x.val), Some(3));
// Elements should stay at the same places
assert_eq!(vals(&ring), vec![0, 1, 2, 4]);
}
// Test case 4: Multiple locked indices
{
// Lock index 1 and 3
let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, true), (4, false)]);
let removed = ring.remove_respecting_locks(0);
assert_eq!(removed.map(|x| x.val), Some(0));
// Elements '1' and '3' remain at indices '1' and '3'
assert_eq!(vals(&ring), vec![2, 1, 4, 3]);
}
// Test case 5: Remove the last element
{
// Lock index 2
let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]);
let removed = ring.remove_respecting_locks(4);
assert_eq!(removed.map(|x| x.val), Some(4));
// Index 2 should still be at the same place
assert_eq!(vals(&ring), vec![0, 1, 2, 3]);
}
// Test case 6: Invalid index
{
// Lock index 2
let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]);
let removed = ring.remove_respecting_locks(10);
assert_eq!(removed, None);
// Deque unchanged
assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4]);
}
// Test case 7: Remove enough elements to make a locked index invalid
{
// Lock index 2
let mut ring = test_deque(&[(0, false), (1, false), (2, true)]);
ring.remove_respecting_locks(0);
// Index 2 should now be '1'
assert_eq!(vals(&ring), vec![1, 2]);
}
// Test case 8: Removing an element before multiple locked indices
{
// Lock index 2 and 4
let mut ring = test_deque(&[
(0, false),
(1, false),
(2, true),
(3, false),
(4, true),
(5, false),
]);
let removed = ring.remove_respecting_locks(1);
assert_eq!(removed.map(|x| x.val), Some(1));
// Both indices should still be at the same place
assert_eq!(vals(&ring), vec![0, 3, 2, 5, 4]);
}
}
#[test]
fn test_swap_respecting_locks_various_cases() {
// Swap unlocked and locked
let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, false)]);
ring.swap_respecting_locks(0, 1);
assert_eq!(vals(&ring), vec![1, 0, 2, 3]);
assert!(!ring[0].locked);
assert!(ring[1].locked);
ring.swap_respecting_locks(0, 1);
assert_eq!(vals(&ring), vec![0, 1, 2, 3]);
assert!(!ring[0].locked);
assert!(ring[1].locked);
// Both locked
let mut ring = test_deque(&[(0, true), (1, false), (2, true)]);
ring.swap_respecting_locks(0, 2);
assert_eq!(vals(&ring), vec![2, 1, 0]);
assert!(ring[0].locked);
assert!(!ring[1].locked);
assert!(ring[2].locked);
// Both unlocked
let mut ring = test_deque(&[(0, false), (1, true), (2, false)]);
ring.swap_respecting_locks(0, 2);
assert_eq!(vals(&ring), vec![2, 1, 0]);
assert!(!ring[0].locked);
assert!(ring[1].locked);
assert!(!ring[2].locked);
}
}
+64 -8
View File
@@ -1,24 +1,48 @@
use crate::LibraryError;
use crate::accessibility::attribute_constants::kAXPositionAttribute;
use crate::accessibility::attribute_constants::kAXSizeAttribute;
use crate::application::Application;
use crate::cf_array_as;
use crate::core::rect::Rect;
use crate::core_graphics::CoreGraphicsApi;
use crate::ring::Ring;
use crate::monitor::Monitor;
use crate::window::WindowInfo;
use crate::window_manager::Container;
use crate::window_manager::Monitor;
use crate::window_manager::WindowManager;
use objc2::MainThreadMarker;
use objc2_app_kit::NSScreen;
use objc2_application_services::AXUIElement;
use objc2_core_foundation::CFDictionary;
use objc2_core_foundation::CFString;
use objc2_core_foundation::CGPoint;
use objc2_core_foundation::CGSize;
use std::collections::HashMap;
use std::ptr::NonNull;
pub struct MacosApi;
impl MacosApi {
pub fn load_monitor_information(wm: &mut WindowManager) -> Result<(), LibraryError> {
let screens = NSScreen::screens(MainThreadMarker::new().unwrap());
for display_id in CoreGraphicsApi::connected_display_ids()? {
let size = Rect::from(CoreGraphicsApi::display_bounds(display_id));
let monitor = Monitor::new(display_id, size);
wm.monitors.elements_mut().push_back(monitor);
let display_bounds = CoreGraphicsApi::display_bounds(display_id);
for screen in &screens {
let menu_bar_height = screen.frame().size.height
- screen.visibleFrame().size.height
- screen.visibleFrame().origin.y;
if screen.frame() == display_bounds {
let size = Rect::from(display_bounds);
let mut work_area_size = Rect::from(display_bounds);
work_area_size.top += menu_bar_height as i32;
work_area_size.bottom = screen.visibleFrame().size.height as i32;
let monitor = Monitor::new(display_id, size, work_area_size);
wm.monitors.elements_mut().push_back(monitor);
}
}
}
Ok(())
@@ -78,9 +102,7 @@ impl MacosApi {
for (monitor_idx, windows) in monitor_window_map {
for window in windows {
let mut container = Container {
windows: Ring::default(),
};
let mut container = Container::default();
container.windows_mut().push_back(window);
if let Some(Some(workspace)) = monitor_workspace_map.get_mut(monitor_idx) {
@@ -91,4 +113,38 @@ impl MacosApi {
Ok(())
}
pub fn center_cursor_in_rect(rect: &Rect) -> Result<(), LibraryError> {
Ok(CoreGraphicsApi::warp_mouse_cursor_position(
rect.left + (rect.right / 2),
rect.top + (rect.bottom / 2),
)?)
}
pub fn window_rect(element: &AXUIElement) -> Rect {
let mut position_receiver = std::ptr::null();
let mut size_receiver = std::ptr::null();
unsafe {
element.copy_attribute_value(
&CFString::from_static_str(kAXPositionAttribute),
NonNull::from(&mut position_receiver),
);
element.copy_attribute_value(
&CFString::from_static_str(kAXSizeAttribute),
NonNull::from(&mut size_receiver),
);
let position = *position_receiver.cast::<CGPoint>();
let size = *position_receiver.cast::<CGSize>();
Rect {
left: position.x as i32,
top: position.y as i32,
right: size.width as i32,
bottom: size.height as i32,
}
}
}
}
+11 -8
View File
@@ -2,6 +2,8 @@
use color_eyre::eyre;
use color_eyre::eyre::eyre;
use komorebi::DATA_DIR;
use komorebi::process_command::listen_for_commands;
use komorebi::window_manager::WindowManager;
use objc2::rc::autoreleasepool;
use objc2_application_services::AXIsProcessTrusted;
@@ -11,6 +13,7 @@ use objc2_core_graphics::CGDisplayBounds;
use objc2_core_graphics::CGMainDisplayID;
use objc2_core_graphics::CGPreflightScreenCaptureAccess;
use objc2_core_graphics::CGRequestScreenCaptureAccess;
use parking_lot::Mutex;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
@@ -90,19 +93,19 @@ fn main() -> eyre::Result<()> {
setup()?;
check_permissions()?;
if !DATA_DIR.is_dir() {
std::fs::create_dir_all(&*DATA_DIR)?;
}
let display_size = unsafe { CGDisplayBounds(CGMainDisplayID()) };
tracing::info!("display size for main display is: {:?}", display_size);
let run_loop = CFRunLoop::current().ok_or(eyre!("couldn't get CFRunLoop::current"))?;
let mut wm = WindowManager::new(&run_loop);
wm.init()?;
let wm = Arc::new(Mutex::new(WindowManager::new(&run_loop, None)?));
wm.lock().init()?;
wm.lock().update_focused_workspace(true, true)?;
wm.monitors
.focused_mut()
.unwrap()
.focused_workspace_mut()
.unwrap()
.update()?;
listen_for_commands(wm.clone());
let quit_ctrlc = Arc::new(AtomicBool::new(false));
let quit_thread = quit_ctrlc.clone();
+88
View File
@@ -0,0 +1,88 @@
use crate::DEFAULT_CONTAINER_PADDING;
use crate::DEFAULT_WORKSPACE_PADDING;
use crate::core::rect::Rect;
use crate::ring::Ring;
use crate::workspace::Workspace;
use crate::workspace::WorkspaceGlobals;
use color_eyre::eyre;
use color_eyre::eyre::eyre;
use std::sync::atomic::Ordering;
impl_ring_elements!(Monitor, Workspace);
#[derive(Debug)]
pub struct Monitor {
pub id: u32,
pub workspaces: Ring<Workspace>,
pub size: Rect,
pub work_area_offset: Option<Rect>,
pub work_area_size: Rect,
pub window_based_work_area_offset: Option<Rect>,
pub window_based_work_area_offset_limit: isize,
pub container_padding: Option<i32>,
pub workspace_padding: Option<i32>,
}
impl Monitor {
#[allow(clippy::field_reassign_with_default)]
pub fn new(id: u32, size: Rect, work_area_size: Rect) -> Self {
let mut workspaces = Ring::default();
workspaces.elements_mut().push_back(Workspace::default());
Self {
id,
workspaces,
size,
work_area_offset: None,
work_area_size,
window_based_work_area_offset: None,
window_based_work_area_offset_limit: 0,
container_padding: None,
workspace_padding: None,
}
}
pub fn update_focused_workspace(&mut self, offset: Option<Rect>) -> eyre::Result<()> {
let offset = if self.work_area_offset.is_some() {
self.work_area_offset
} else {
offset
};
let focused_workspace_idx = self.focused_workspace_idx();
self.update_workspace_globals(focused_workspace_idx, offset);
self.focused_workspace_mut()
.ok_or_else(|| eyre!("there is no workspace"))?
.update()?;
Ok(())
}
/// Updates the `globals` field of workspace with index `workspace_idx`
pub fn update_workspace_globals(&mut self, workspace_idx: usize, offset: Option<Rect>) {
let container_padding = self
.container_padding
.or(Some(DEFAULT_CONTAINER_PADDING.load(Ordering::Relaxed)));
let workspace_padding = self
.workspace_padding
.or(Some(DEFAULT_WORKSPACE_PADDING.load(Ordering::Relaxed)));
let (border_width, border_offset) = (0, 0);
let work_area = self.work_area_size;
let work_area_offset = self.work_area_offset.or(offset);
let window_based_work_area_offset = self.window_based_work_area_offset;
let window_based_work_area_offset_limit = self.window_based_work_area_offset_limit;
if let Some(workspace) = self.workspaces_mut().get_mut(workspace_idx) {
workspace.globals = WorkspaceGlobals {
container_padding,
workspace_padding,
border_width,
border_offset,
work_area,
work_area_offset,
window_based_work_area_offset,
window_based_work_area_offset_limit,
}
}
}
}
+122
View File
@@ -0,0 +1,122 @@
use crate::core::SocketMessage;
use crate::window_manager::WindowManager;
use color_eyre::eyre;
use parking_lot::Mutex;
use std::io::BufRead;
use std::io::BufReader;
use std::os::unix::net::UnixStream;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
#[tracing::instrument]
pub fn listen_for_commands(wm: Arc<Mutex<WindowManager>>) {
std::thread::spawn(move || {
loop {
let wm = wm.clone();
let _ = std::thread::spawn(move || {
let listener = wm
.lock()
.command_listener
.try_clone()
.expect("could not clone unix listener");
tracing::info!("listening on komorebi.sock");
for client in listener.incoming() {
match client {
Ok(stream) => {
let wm_clone = wm.clone();
std::thread::spawn(move || {
match read_commands_uds(&wm_clone, stream) {
Ok(()) => {}
Err(error) => {
tracing::error!("failed to read command from uds {}", error)
}
}
});
}
Err(error) => {
tracing::error!("failed to get unix stream {}", error);
break;
}
}
}
})
.join();
tracing::error!("restarting failed thread");
}
});
}
impl WindowManager {
#[tracing::instrument(skip(self, _reply))]
pub fn process_command(
&mut self,
message: SocketMessage,
mut _reply: impl std::io::Write,
) -> eyre::Result<()> {
match message {
SocketMessage::FocusWindow(direction) => {
self.focus_container_in_direction(direction)?;
}
SocketMessage::MoveWindow(direction) => {
self.move_container_in_direction(direction)?;
}
SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?,
SocketMessage::TogglePause => {
if self.is_paused {
tracing::info!("resuming");
} else {
tracing::info!("pausing");
}
self.is_paused = !self.is_paused;
}
}
Ok(())
}
}
pub fn read_commands_uds(
wm: &Arc<Mutex<WindowManager>>,
mut stream: UnixStream,
) -> eyre::Result<()> {
let reader = BufReader::new(stream.try_clone()?);
// TODO(raggi): while this processes more than one command, if there are
// replies there is no clearly defined protocol for framing yet - it's
// perhaps whole-json objects for now, but termination is signalled by
// socket shutdown.
for line in reader.lines() {
let message = SocketMessage::from_str(&line?)?;
match wm.try_lock_for(Duration::from_secs(1)) {
None => {
tracing::warn!(
"could not acquire window manager lock, not processing message: {message}"
);
}
Some(mut wm) => {
if wm.is_paused {
return match message {
SocketMessage::TogglePause
// | SocketMessage::State
// | SocketMessage::GlobalState
// | SocketMessage::Stop
=> Ok(wm.process_command(message, &mut stream)?),
_ => {
tracing::trace!("ignoring while paused");
Ok(())
}
};
}
wm.process_command(message.clone(), &mut stream)?;
}
}
}
Ok(())
}
+16 -7
View File
@@ -1,3 +1,6 @@
use crate::AccessibilityObserver;
use crate::AccessibilityUiElement;
use crate::LibraryError;
use crate::accessibility::AccessibilityApi;
use crate::accessibility::attribute_constants::kAXMainAttribute;
use crate::accessibility::attribute_constants::kAXPositionAttribute;
@@ -122,9 +125,9 @@ impl WindowInfo {
#[derive(Debug)]
#[allow(unused)]
pub struct Window {
element: CFRetained<AXUIElement>,
element: AccessibilityUiElement,
application: Application,
observer: CFRetained<AXObserver>,
observer: AccessibilityObserver,
}
impl Drop for Window {
@@ -150,14 +153,14 @@ impl Window {
)?;
Ok(Self {
element,
element: AccessibilityUiElement(element),
application,
observer,
observer: AccessibilityObserver(observer),
})
}
#[tracing::instrument(skip_all)]
pub fn observe(&self, run_loop: &CFRetained<CFRunLoop>) -> Result<(), AccessibilityError> {
pub fn observe(&self, run_loop: &CFRunLoop) -> Result<(), AccessibilityError> {
tracing::info!(
"registering observer for process: {}, title: {}",
self.application.process_id,
@@ -183,7 +186,7 @@ impl Window {
self.set_size(CGSize::new(rect.right as CGFloat, rect.bottom as CGFloat))
}
pub fn focus(&self) -> Result<(), AccessibilityError> {
pub fn focus(&self, focus_follows_mouse: bool) -> Result<(), LibraryError> {
unsafe {
NSRunningApplication::runningApplicationWithProcessIdentifier(
self.application.process_id,
@@ -195,8 +198,14 @@ impl Window {
let cf_boolean = CFBoolean::new(true);
let value = &**cf_boolean;
AccessibilityApi::set_attribute_cf_value(&self.element, kAXMainAttribute, value)
AccessibilityApi::set_attribute_cf_value(&self.element, kAXMainAttribute, value)?;
}
if focus_follows_mouse {
// MacosApi::center_cursor_in_rect(&MacosApi::window_rect(&self.element))?
}
Ok(())
}
pub fn set_point(&self, point: CGPoint) -> Result<(), AccessibilityError> {
+222 -33
View File
@@ -1,28 +1,67 @@
use crate::CoreFoundationRunLoop;
use crate::DATA_DIR;
use crate::LibraryError;
use crate::application::Application;
use crate::core::default_layout::DefaultLayout;
use crate::core::layout::Layout;
use crate::core::operation_direction::OperationDirection;
use crate::core::rect::Rect;
use crate::lockable_sequence::Lockable;
use crate::macos_api::MacosApi;
use crate::monitor::Monitor;
use crate::ring::Ring;
use crate::window::Window;
use crate::workspace::Workspace;
use color_eyre::eyre;
use color_eyre::eyre::eyre;
use objc2_core_foundation::CFRetained;
use objc2_core_foundation::CFRunLoop;
use std::collections::HashMap;
use std::io::ErrorKind;
use std::os::unix::net::UnixListener;
use std::path::PathBuf;
#[derive(Debug)]
pub struct WindowManager {
pub monitors: Ring<Monitor>,
pub applications: HashMap<i32, Application>,
pub run_loop: CFRetained<CFRunLoop>,
pub run_loop: CoreFoundationRunLoop,
pub command_listener: UnixListener,
pub is_paused: bool,
pub mouse_follows_focus: bool,
pub work_area_offset: Option<Rect>,
}
impl_ring_elements!(WindowManager, Monitor);
impl WindowManager {
pub fn new(run_loop: &CFRetained<CFRunLoop>) -> Self {
Self {
pub fn new(
run_loop: &CFRetained<CFRunLoop>,
custom_socket_path: Option<PathBuf>,
) -> eyre::Result<Self> {
let socket = custom_socket_path.unwrap_or_else(|| DATA_DIR.join("komorebi.sock"));
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
ErrorKind::NotFound => {}
_ => {
return Err(error.into());
}
},
};
let listener = UnixListener::bind(&socket)?;
Ok(Self {
monitors: Ring::default(),
applications: Default::default(),
run_loop: run_loop.clone(),
}
run_loop: CoreFoundationRunLoop(run_loop.clone()),
command_listener: listener,
is_paused: false,
mouse_follows_focus: true,
work_area_offset: None,
})
}
#[tracing::instrument(skip(self))]
@@ -33,41 +72,191 @@ impl WindowManager {
}
}
impl_ring_elements!(Monitor, Workspace);
#[derive(Debug)]
pub struct Monitor {
pub id: u32,
pub workspaces: Ring<Workspace>,
pub size: Rect,
}
impl WindowManager {
#[tracing::instrument(skip(self))]
pub fn focus_container_in_direction(
&mut self,
direction: OperationDirection,
) -> eyre::Result<()> {
let workspace = self.focused_workspace()?;
impl Monitor {
#[allow(clippy::field_reassign_with_default)]
pub fn new(id: u32, size: Rect) -> Self {
let mut workspaces = Ring::default();
let mut workspace = Workspace::default();
workspace.work_area = size;
workspace.container_padding = Some(20);
workspace.workspace_padding = Some(20);
workspace.work_area_offset = Some(Rect {
left: 0,
top: 0,
right: 0,
bottom: 40,
});
tracing::info!("focusing container");
workspaces.elements_mut().push_back(workspace);
Self {
id,
workspaces,
size,
match workspace.new_idx_for_direction(direction) {
None => {}
Some(idx) => {
let workspace = self.focused_workspace_mut()?;
workspace.focus_container(idx);
}
}
if let Ok(focused_window) = self.focused_window() {
focused_window.focus(self.mouse_follows_focus)?;
}
Ok(())
}
#[tracing::instrument(skip(self))]
pub fn move_container_in_direction(
&mut self,
direction: OperationDirection,
) -> eyre::Result<()> {
let workspace = self.focused_workspace()?;
tracing::info!("moving container");
let origin_container_idx = workspace.focused_container_idx();
let target_container_idx = workspace.new_idx_for_direction(direction);
match target_container_idx {
None => {}
Some(new_idx) => {
let workspace = self.focused_workspace_mut()?;
workspace.swap_containers(origin_container_idx, new_idx);
workspace.focus_container(new_idx);
}
}
self.update_focused_workspace(self.mouse_follows_focus, true)?;
Ok(())
}
#[tracing::instrument(skip(self))]
pub fn update_focused_workspace(
&mut self,
follow_focus: bool,
trigger_focus: bool,
) -> eyre::Result<()> {
tracing::info!("updating");
let offset = self.work_area_offset;
let mouse_follows_focus = self.mouse_follows_focus;
self.focused_monitor_mut()
.ok_or_else(|| eyre!("there is no monitor"))?
.update_focused_workspace(offset)?;
if follow_focus
&& let Ok(window) = self.focused_window_mut()
&& trigger_focus
{
window.focus(mouse_follows_focus)?;
}
Ok(())
}
#[tracing::instrument(skip(self))]
pub fn change_workspace_layout_default(&mut self, layout: DefaultLayout) -> eyre::Result<()> {
tracing::info!("changing layout");
let monitor_count = self.monitors().len();
let workspace = self.focused_workspace_mut()?;
if monitor_count > 1 && matches!(layout, DefaultLayout::Scrolling) {
tracing::warn!(
"scrolling layout is only supported for a single monitor; not changing layout"
);
return Ok(());
}
workspace.layout = Layout::Default(layout);
self.update_focused_workspace(self.mouse_follows_focus, false)
}
pub fn focused_workspace_idx(&self) -> eyre::Result<usize> {
Ok(self
.focused_monitor()
.ok_or_else(|| eyre!("there is no monitor"))?
.focused_workspace_idx())
}
pub fn focused_workspace(&self) -> eyre::Result<&Workspace> {
self.focused_monitor()
.ok_or_else(|| eyre!("there is no monitor"))?
.focused_workspace()
.ok_or_else(|| eyre!("there is no workspace"))
}
pub fn focused_workspace_mut(&mut self) -> eyre::Result<&mut Workspace> {
self.focused_monitor_mut()
.ok_or_else(|| eyre!("there is no monitor"))?
.focused_workspace_mut()
.ok_or_else(|| eyre!("there is no workspace"))
}
pub fn focused_workspace_idx_for_monitor_idx(&self, idx: usize) -> eyre::Result<usize> {
Ok(self
.monitors()
.get(idx)
.ok_or_else(|| eyre!("there is no monitor at this index"))?
.focused_workspace_idx())
}
pub fn focused_workspace_for_monitor_idx(&self, idx: usize) -> eyre::Result<&Workspace> {
self.monitors()
.get(idx)
.ok_or_else(|| eyre!("there is no monitor at this index"))?
.focused_workspace()
.ok_or_else(|| eyre!("there is no workspace"))
}
pub fn focused_workspace_for_monitor_idx_mut(
&mut self,
idx: usize,
) -> eyre::Result<&mut Workspace> {
self.monitors_mut()
.get_mut(idx)
.ok_or_else(|| eyre!("there is no monitor at this index"))?
.focused_workspace_mut()
.ok_or_else(|| eyre!("there is no workspace"))
}
pub fn focused_container(&self) -> eyre::Result<&Container> {
self.focused_workspace()?
.focused_container()
.ok_or_else(|| eyre!("there is no container"))
}
pub fn focused_container_idx(&self) -> eyre::Result<usize> {
Ok(self.focused_workspace()?.focused_container_idx())
}
pub fn focused_container_mut(&mut self) -> eyre::Result<&mut Container> {
self.focused_workspace_mut()?
.focused_container_mut()
.ok_or_else(|| eyre!("there is no container"))
}
pub fn focused_window(&self) -> eyre::Result<&Window> {
self.focused_container()?
.focused_window()
.ok_or_else(|| eyre!("there is no window"))
}
fn focused_window_mut(&mut self) -> eyre::Result<&mut Window> {
self.focused_container_mut()?
.focused_window_mut()
.ok_or_else(|| eyre!("there is no window"))
}
}
impl_ring_elements!(Container, Window);
#[derive(Debug)]
#[derive(Debug, Default)]
pub struct Container {
pub windows: Ring<Window>,
pub locked: bool,
}
impl Lockable for Container {
fn locked(&self) -> bool {
self.locked
}
fn set_locked(&mut self, locked: bool) -> &mut Self {
self.locked = locked;
self
}
}
+26 -3
View File
@@ -2,7 +2,9 @@ use crate::core::arrangement::Axis;
use crate::core::default_layout::DefaultLayout;
use crate::core::default_layout::LayoutOptions;
use crate::core::layout::Layout;
use crate::core::operation_direction::OperationDirection;
use crate::core::rect::Rect;
use crate::lockable_sequence::LockableSequence;
use crate::ring::Ring;
use crate::window_manager::Container;
use color_eyre::eyre;
@@ -18,7 +20,6 @@ pub struct Workspace {
pub container_padding: Option<i32>,
pub resize_dimensions: Vec<Option<Rect>>,
pub layout: Layout,
pub work_area: Rect,
pub work_area_offset: Option<Rect>,
pub latest_layout: Vec<Rect>,
pub layout_flip: Option<Axis>,
@@ -35,7 +36,6 @@ impl Default for Workspace {
container_padding: None,
resize_dimensions: vec![],
layout: Layout::Default(DefaultLayout::UltrawideVerticalStack),
work_area: Default::default(),
work_area_offset: None,
latest_layout: vec![],
layout_flip: None,
@@ -81,7 +81,7 @@ impl Workspace {
// self.globals.window_based_work_area_offset_limit;
let mut adjusted_work_area = work_area_offset.map_or_else(
|| self.work_area,
|| work_area,
|offset| {
let mut with_offset = work_area;
with_offset.left += offset.left;
@@ -130,4 +130,27 @@ impl Workspace {
Ok(())
}
#[tracing::instrument(skip(self))]
pub fn focus_container(&mut self, idx: usize) {
tracing::info!("focusing container");
self.containers.focus(idx);
}
pub fn swap_containers(&mut self, i: usize, j: usize) {
self.containers.elements_mut().swap_respecting_locks(i, j);
self.focus_container(j);
}
pub fn new_idx_for_direction(&self, direction: OperationDirection) -> Option<usize> {
let len = NonZeroUsize::new(self.containers().len())?;
direction.destination(
self.layout.as_boxed_direction().as_ref(),
self.layout_flip,
self.focused_container_idx(),
len,
)
}
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "komorebic"
version = "0.1.0"
edition = "2024"
[dependencies]
komorebi-client = { path = "../komorebi-client", default-features = false }
clap = { workspace = true }
color-eyre = { workspace = true }
dirs = { workspace = true }
lazy_static = { workspace = true }
pastey = { workspace = true }
+100
View File
@@ -0,0 +1,100 @@
#![warn(clippy::all)]
use clap::Parser;
use color_eyre::eyre;
use komorebi_client::DefaultLayout;
use komorebi_client::OperationDirection;
use komorebi_client::PathExt;
use komorebi_client::SocketMessage;
use komorebi_client::send_message;
use lazy_static::lazy_static;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
lazy_static! {
static ref HAS_CUSTOM_CONFIG_HOME: AtomicBool = AtomicBool::new(false);
static ref HOME_DIR: PathBuf = {
std::env::var("KOMOREBI_CONFIG_HOME").map_or_else(
|_| dirs::home_dir().expect("there is no home directory"),
|home_path| {
let home = home_path.replace_env();
if home.as_path().is_dir() {
HAS_CUSTOM_CONFIG_HOME.store(true, Ordering::SeqCst);
home
} else {
panic!(
"$Env:KOMOREBI_CONFIG_HOME is set to '{home_path}', which is not a valid directory",
);
}
},
)
};
static ref DATA_DIR: PathBuf = dirs::data_local_dir()
.expect("there is no local data directory")
.join("komorebi");
}
macro_rules! gen_enum_subcommand_args {
// SubCommand Pattern: Enum Type
( $( $name:ident: $element:ty ),+ $(,)? ) => {
$(
pastey::paste! {
#[derive(clap::Parser)]
pub struct $name {
#[clap(value_enum)]
[<$element:snake>]: $element
}
}
)+
};
}
gen_enum_subcommand_args! {
Focus: OperationDirection,
Move: OperationDirection,
ChangeLayout: DefaultLayout,
}
#[derive(Parser)]
#[clap(author, about, version)]
struct Opts {
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Parser)]
enum SubCommand {
/// Change focus to the window in the specified direction
#[clap(arg_required_else_help = true)]
Focus(Focus),
/// Move the focused window in the specified direction
#[clap(arg_required_else_help = true)]
Move(Move),
/// Toggle the paused state for all window tiling
TogglePause,
/// Set the layout on the focused workspace
#[clap(arg_required_else_help = true)]
ChangeLayout(ChangeLayout),
}
fn main() -> eyre::Result<()> {
let opts: Opts = Opts::parse();
match opts.subcmd {
SubCommand::Focus(arg) => {
send_message(&SocketMessage::FocusWindow(arg.operation_direction))?;
}
SubCommand::Move(arg) => {
send_message(&SocketMessage::MoveWindow(arg.operation_direction))?;
}
SubCommand::TogglePause => {
send_message(&SocketMessage::TogglePause)?;
}
SubCommand::ChangeLayout(arg) => {
send_message(&SocketMessage::ChangeLayout(arg.default_layout))?;
}
}
Ok(())
}
+2 -1
View File
@@ -10,5 +10,6 @@ with pkgs;
cargo-deny
jq
prettier
cargo-udeps
];
}
}