Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

feat: add macOS support (#1272)

Lars Berger42436baf9655
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..7ff6c3fe
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,67 @@
+<project_overview>
+GlazeWM is a window manager for macOS and Windows, written in Rust.
+
+Crate structure:
+
+- **wm** (bin): Main application, which implements the core window management logic. Install path on Windows: `C:\Program Files\glzr.io\glazewm.exe`
+- **wm-cli** (bin, lib): CLI for interacting with the main application. Added to `$PATH` by default. Install path on Windows: `C:\Program Files\glzr.io\cli\glazewm.exe`
+- **wm-common** (lib): Shared types, utilities, and constants used across other crates.
+- **wm-ipc-client** (lib): WebSocket client library for IPC with the main application.
+- **wm-platform** (lib): Wrappers over platform-specific APIs; other crates do not call Windows/macOS APIs directly.
+- **wm-watcher** (Windows-only) (bin): Watchdog process ensuring proper cleanup when the main application exits. Install path on Windows: `C:\Program Files\glzr.io\glazewm-watcher.exe`
+
+</project_overview>
+
+<output_guidelines>
+
+- Be extremely concise. Sacrifice grammar for the sake of conciseness.
+- Do not leave partial or simplified implementations.
+- The required quality standard is high. Low quality code will be rejected.
+- Do not proceed with solutions that are hacky. Solutions must be robust, maintainable, and extendable. Ask guiding questions if uncertain about a solution.
+
+</output_guidelines>
+
+<code_style_guidelines>
+
+- Avoid `.unwrap()` wherever possible.
+- For error handling:
+ - Use `crate::Error` and `crate::Result` within the `wm-platform` crate.
+ - Use `anyhow` in all other crates.
+- For logging, use `tracing` macros (e.g. `tracing::info!("...")`).
+
+</code_style_guidelines>
+
+<code_comment_guidelines>
+
+- Functions should always be documented.
+- Use punctuation mark at the end of all comments.
+- If using unsafe features, include a "SAFETY: ..." comment.
+- Wrap type names in backticks (e.g. `NativeMonitor`).
+
+Comment structure:
+
+```rs
+/// <Concise summary of the function or type>
+///
+/// (optional) <Notable caveats for usage (kept brief)>
+///
+/// (optional) <Describe return value if ambiguous (e.g. "Returns a vector of `NativeMonitor`, sorted by their position from left-to-right.")>
+///
+/// (optional) # Example usage
+///
+/// <Code block with example usage>
+///
+/// (optional) # Platform-specific
+///
+/// <Bullet-point list of behavioral differences on macOS vs Windows>
+pub fn my_function() { ... }
+```
+
+</code_comment_guidelines>
+
+<test_guidelines>
+
+- Use `#[cfg(test)]` for test modules.
+- Write unit tests for core functionality.
+
+</test_guidelines>
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index cb994aba..6ad59cfe 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -58,7 +58,7 @@ GlazeWM is organized into several Rust crates:
- Gets installed to `C:\Program Files\glzr.io\cli\glazewm.exe`. This is added to `$PATH` by default.
- `wm-common` (lib): Shared types, utilities, and constants used across other crates.
- `wm-ipc-client` (lib): WebSocket client library for IPC with the main application.
-- `wm-platform` (lib): Wrappers over Windows APIs - other crates don't interact directly with the Windows APIs.
+- `wm-platform` (lib): Wrappers over platform-specific API's - other crates don't interact directly with the Windows and macOS API's.
- `wm-watcher` (bin): Watchdog process that ensures proper cleanup when the main application exits.
- Gets installed to `C:\Program Files\glzr.io\glazewm-watcher.exe`.
diff --git a/Cargo.lock b/Cargo.lock
index 12333bcd..8391b6bc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -26,13 +26,22 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "aligned-vec"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"
+dependencies = [
+ "equator",
+]
+
[[package]]
name = "ambassador"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b27ba24e4d8a188489d5a03c7fabc167a60809a383cdb4d15feb37479cd2a48"
dependencies = [
- "itertools",
+ "itertools 0.10.5",
"proc-macro2",
"quote",
"syn 1.0.109",
@@ -97,6 +106,29 @@ dependencies = [
"backtrace",
]
+[[package]]
+name = "arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
+
+[[package]]
+name = "arg_enum_proc_macro"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.103",
+]
+
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
[[package]]
name = "atk"
version = "0.18.2"
@@ -137,6 +169,29 @@ version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
+[[package]]
+name = "av1-grain"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4f3efb2ca85bc610acfa917b5aaa36f3fcbebed5b3182d7f877b02531c4b80c8"
+dependencies = [
+ "anyhow",
+ "arrayvec",
+ "log",
+ "nom",
+ "num-rational",
+ "v_frame",
+]
+
+[[package]]
+name = "avif-serialize"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47c8fbc0f831f4519fe8b810b6a7a91410ec83031b8233f730a0480029f6a23f"
+dependencies = [
+ "arrayvec",
+]
+
[[package]]
name = "backtrace"
version = "0.3.75"
@@ -152,6 +207,12 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "bit_field"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6"
+
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -167,6 +228,12 @@ dependencies = [
"serde",
]
+[[package]]
+name = "bitstream-io"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6099cdc01846bc367c4e7dd630dc5966dccf36b652fae7a74e17b640411a91b2"
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -185,12 +252,30 @@ dependencies = [
"objc2",
]
+[[package]]
+name = "built"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56ed6191a7e78c36abdb16ab65341eefd73d64d303fffccdbb00d51e4205967b"
+
[[package]]
name = "bumpalo"
version = "3.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "793db76d6187cd04dff33004d8e6c9cc4e05cd330500379d2394209271b4aeee"
+[[package]]
+name = "bytemuck"
+version = "1.23.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3995eaeebcdf32f91f980d360f78732ddc061097ab4e39991ae7a6ace9194677"
+
+[[package]]
+name = "byteorder-lite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
+
[[package]]
name = "bytes"
version = "1.10.1"
@@ -228,6 +313,8 @@ version = "1.2.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "956a5e21988b87f372569b66183b78babf23ebc2e744b733e4350a752c4dafac"
dependencies = [
+ "jobserver",
+ "libc",
"shlex",
]
@@ -287,6 +374,12 @@ version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675"
+[[package]]
+name = "color_quant"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
+
[[package]]
name = "colorchoice"
version = "1.0.4"
@@ -320,12 +413,37 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
+dependencies = [
+ "crossbeam-utils",
+]
+
[[package]]
name = "crossbeam-utils"
version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
[[package]]
name = "crypto-common"
version = "0.1.6"
@@ -336,6 +454,16 @@ dependencies = [
"typenum",
]
+[[package]]
+name = "ctor"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501"
+dependencies = [
+ "quote",
+ "syn 2.0.103",
+]
+
[[package]]
name = "data-encoding"
version = "2.9.0"
@@ -399,7 +527,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users 0.5.0",
- "windows-sys 0.59.0",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -438,6 +566,15 @@ dependencies = [
"winreg 0.52.0",
]
+[[package]]
+name = "encoding_rs"
+version = "0.8.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
+dependencies = [
+ "cfg-if",
+]
+
[[package]]
name = "enum-as-inner"
version = "0.6.1"
@@ -450,12 +587,73 @@ dependencies = [
"syn 2.0.103",
]
+[[package]]
+name = "equator"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"
+dependencies = [
+ "equator-macro",
+]
+
+[[package]]
+name = "equator-macro"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.103",
+]
+
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+[[package]]
+name = "escape8259"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5692dd7b5a1978a5aeb0ce83b7655c58ca8efdcb79d21036ea249da95afec2c6"
+
+[[package]]
+name = "exr"
+version = "1.73.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83197f59927b46c04a183a619b7c29df34e63e63c7869320862268c0ef687e0"
+dependencies = [
+ "bit_field",
+ "half",
+ "lebe",
+ "miniz_oxide",
+ "rayon-core",
+ "smallvec",
+ "zune-inflate",
+]
+
+[[package]]
+name = "fax"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f05de7d48f37cd6730705cbca900770cab77a89f413d23e100ad7fad7795a0ab"
+dependencies = [
+ "fax_derive",
+]
+
+[[package]]
+name = "fax_derive"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0aca10fb742cb43f9e7bb8467c91aa9bcb8e3ffbc6a6f7389bb93ffc920577d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.103",
+]
+
[[package]]
name = "fdeflate"
version = "0.3.7"
@@ -652,6 +850,16 @@ dependencies = [
"wasi 0.14.2+wasi-0.2.4",
]
+[[package]]
+name = "gif"
+version = "0.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b"
+dependencies = [
+ "color_quant",
+ "weezl",
+]
+
[[package]]
name = "gimli"
version = "0.31.1"
@@ -800,6 +1008,16 @@ dependencies = [
"syn 2.0.103",
]
+[[package]]
+name = "half"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+]
+
[[package]]
name = "hashbrown"
version = "0.15.4"
@@ -844,6 +1062,46 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+[[package]]
+name = "image"
+version = "0.25.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "529feb3e6769d234375c4cf1ee2ce713682b8e76538cb13f9fc23e1400a591e7"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "color_quant",
+ "exr",
+ "gif",
+ "image-webp",
+ "moxcms",
+ "num-traits",
+ "png 0.18.0",
+ "qoi",
+ "ravif",
+ "rayon",
+ "rgb",
+ "tiff",
+ "zune-core",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "image-webp"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
+dependencies = [
+ "byteorder-lite",
+ "quick-error",
+]
+
+[[package]]
+name = "imgref"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0263a3d970d5c054ed9312c0057b4f3bde9c0b33836d3637361d4a9e6e7a408"
+
[[package]]
name = "indexmap"
version = "2.9.0"
@@ -854,6 +1112,17 @@ dependencies = [
"hashbrown",
]
+[[package]]
+name = "interpolate_name"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.103",
+]
+
[[package]]
name = "is_terminal_polyfill"
version = "1.70.1"
@@ -869,12 +1138,31 @@ dependencies = [
"either",
]
+[[package]]
+name = "itertools"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
+[[package]]
+name = "jobserver"
+version = "0.1.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
+dependencies = [
+ "getrandom 0.3.3",
+ "libc",
+]
+
[[package]]
name = "js-sys"
version = "0.3.77"
@@ -902,6 +1190,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+[[package]]
+name = "lebe"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
+
[[package]]
name = "libappindicator"
version = "0.9.0"
@@ -932,6 +1226,16 @@ version = "0.2.172"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"
+[[package]]
+name = "libfuzzer-sys"
+version = "0.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5037190e1f70cbeef565bd267599242926f724d3b8a9f510fd7e0b540cfa4404"
+dependencies = [
+ "arbitrary",
+ "cc",
+]
+
[[package]]
name = "libloading"
version = "0.7.4"
@@ -952,6 +1256,40 @@ dependencies = [
"libc",
]
+[[package]]
+name = "libtest-mimic"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5297962ef19edda4ce33aaa484386e0a5b3d7f2f4e037cbeee00503ef6b29d33"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap",
+ "escape8259",
+]
+
+[[package]]
+name = "libtest-mimic-collect"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "003d06b2c6cdd006b440d047a2b94dd3a83abbde4fe21475b392ad38f6c79546"
+dependencies = [
+ "ctor",
+ "libtest-mimic",
+ "libtest-mimic-collect-macro",
+]
+
+[[package]]
+name = "libtest-mimic-collect-macro"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6eeb2525f5cee3328f83ac5ba57977b458e5ed7b54eeebd52709445f156a3c9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.103",
+]
+
[[package]]
name = "libxdo"
version = "0.6.0"
@@ -987,6 +1325,15 @@ version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
+[[package]]
+name = "loop9"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062"
+dependencies = [
+ "imgref",
+]
+
[[package]]
name = "matchers"
version = "0.1.0"
@@ -996,6 +1343,16 @@ dependencies = [
"regex-automata 0.1.10",
]
+[[package]]
+name = "maybe-rayon"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519"
+dependencies = [
+ "cfg-if",
+ "rayon",
+]
+
[[package]]
name = "memchr"
version = "2.7.5"
@@ -1011,6 +1368,12 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -1032,11 +1395,21 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "moxcms"
+version = "0.7.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddd32fa8935aeadb8a8a6b6b351e40225570a37c43de67690383d87ef170cd08"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
[[package]]
name = "muda"
-version = "0.16.1"
+version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4de14a9b5d569ca68d7c891d613b390cf5ab4f851c77aaa2f9e435555d3d9492"
+checksum = "01c1738382f66ed56b3b9c8119e794a2e23148ac8ea214eda86622d4cb9d415a"
dependencies = [
"crossbeam-channel",
"dpi",
@@ -1048,11 +1421,33 @@ dependencies = [
"objc2-core-foundation",
"objc2-foundation",
"once_cell",
- "png",
+ "png 0.17.16",
"thiserror 2.0.12",
- "windows-sys 0.59.0",
+ "windows-sys 0.60.2",
]
+[[package]]
+name = "new_debug_unreachable"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
+
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
+[[package]]
+name = "noop_proc_macro"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
+
[[package]]
name = "nu-ansi-term"
version = "0.46.0"
@@ -1063,12 +1458,62 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "num-bigint"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-conv"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
+[[package]]
+name = "num-derive"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.103",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-bigint",
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
[[package]]
name = "objc2"
version = "0.6.1"
@@ -1082,49 +1527,118 @@ dependencies = [
name = "objc2-app-kit"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e6f29f568bec459b0ddff777cec4fe3fd8666d82d5a40ebd0ff7e66134f89bcc"
+checksum = "e6f29f568bec459b0ddff777cec4fe3fd8666d82d5a40ebd0ff7e66134f89bcc"
+dependencies = [
+ "bitflags 2.9.1",
+ "libc",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-application-services"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9abc05b1f757ebfbd72f4f3f9a515662c67dfe66b26e71b37d818f56a1c2f17"
+dependencies = [
+ "bitflags 2.9.1",
+ "libc",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-core-services",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c10c2894a6fed806ade6027bcd50662746363a9589d3ec9d9bef30a4e4bc166"
+dependencies = [
+ "bitflags 2.9.1",
+ "block2",
+ "dispatch2",
+ "libc",
+ "objc2",
+]
+
+[[package]]
+name = "objc2-core-graphics"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "989c6c68c13021b5c2d6b71456ebb0f9dc78d752e86a98da7c716f4f9470f5a4"
+dependencies = [
+ "bitflags 2.9.1",
+ "block2",
+ "dispatch2",
+ "libc",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-io-surface",
+ "objc2-metal",
+]
+
+[[package]]
+name = "objc2-core-services"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "159be6e4cd366c7d236d798daa2aa71855230e5691cde045a0670ce01a06d664"
+dependencies = [
+ "dispatch2",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-security",
+]
+
+[[package]]
+name = "objc2-encode"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
+
+[[package]]
+name = "objc2-foundation"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "900831247d2fe1a09a683278e5384cfb8c80c79fe6b166f9d14bfdde0ea1b03c"
dependencies = [
"bitflags 2.9.1",
+ "block2",
"objc2",
"objc2-core-foundation",
- "objc2-foundation",
]
[[package]]
-name = "objc2-core-foundation"
+name = "objc2-io-surface"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1c10c2894a6fed806ade6027bcd50662746363a9589d3ec9d9bef30a4e4bc166"
+checksum = "7282e9ac92529fa3457ce90ebb15f4ecbc383e8338060960760fa2cf75420c3c"
dependencies = [
"bitflags 2.9.1",
- "dispatch2",
"objc2",
+ "objc2-core-foundation",
]
[[package]]
-name = "objc2-core-graphics"
+name = "objc2-metal"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "989c6c68c13021b5c2d6b71456ebb0f9dc78d752e86a98da7c716f4f9470f5a4"
+checksum = "7f246c183239540aab1782457b35ab2040d4259175bd1d0c58e46ada7b47a874"
dependencies = [
"bitflags 2.9.1",
- "objc2-core-foundation",
+ "objc2",
+ "objc2-foundation",
]
[[package]]
-name = "objc2-encode"
-version = "4.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
-
-[[package]]
-name = "objc2-foundation"
+name = "objc2-security"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "900831247d2fe1a09a683278e5384cfb8c80c79fe6b166f9d14bfdde0ea1b03c"
+checksum = "e1f8e0ef3ab66b08c42644dcb34dba6ec0a574bbd8adbb8bdbdc7a2779731a44"
dependencies = [
"bitflags 2.9.1",
- "block2",
"objc2",
"objc2-core-foundation",
]
@@ -1156,6 +1670,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "os_pipe"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
+dependencies = [
+ "libc",
+ "windows-sys 0.60.2",
+]
+
[[package]]
name = "overload"
version = "0.1.1"
@@ -1210,6 +1734,12 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
[[package]]
name = "pin-project-lite"
version = "0.2.16"
@@ -1241,6 +1771,19 @@ dependencies = [
"miniz_oxide",
]
+[[package]]
+name = "png"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97baced388464909d42d89643fe4361939af9b7ce7a31ee32a168f832a70f2a0"
+dependencies = [
+ "bitflags 2.9.1",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide",
+]
+
[[package]]
name = "powerfmt"
version = "0.2.0"
@@ -1309,6 +1852,49 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "profiling"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eb8486b569e12e2c32ad3e204dbaba5e4b5b216e9367044f25f1dba42341773"
+dependencies = [
+ "profiling-procmacros",
+]
+
+[[package]]
+name = "profiling-procmacros"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52717f9a02b6965224f95ca2a81e2e0c5c43baacd28ca057577988930b6c3d5b"
+dependencies = [
+ "quote",
+ "syn 2.0.103",
+]
+
+[[package]]
+name = "pxfm"
+version = "0.1.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83f9b339b02259ada5c0f4a389b7fb472f933aa17ce176fd2ad98f28bb401fde"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "qoi"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
[[package]]
name = "quote"
version = "1.0.40"
@@ -1324,14 +1910,35 @@ version = "5.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5"
+[[package]]
+name = "rand"
+version = "0.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
+dependencies = [
+ "libc",
+ "rand_chacha 0.3.1",
+ "rand_core 0.6.4",
+]
+
[[package]]
name = "rand"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97"
dependencies = [
- "rand_chacha",
- "rand_core",
+ "rand_chacha 0.9.0",
+ "rand_core 0.9.3",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.6.4",
]
[[package]]
@@ -1341,7 +1948,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
- "rand_core",
+ "rand_core 0.9.3",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.16",
]
[[package]]
@@ -1353,6 +1969,76 @@ dependencies = [
"getrandom 0.3.3",
]
+[[package]]
+name = "rav1e"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd87ce80a7665b1cce111f8a16c1f3929f6547ce91ade6addf4ec86a8dda5ce9"
+dependencies = [
+ "arbitrary",
+ "arg_enum_proc_macro",
+ "arrayvec",
+ "av1-grain",
+ "bitstream-io",
+ "built",
+ "cfg-if",
+ "interpolate_name",
+ "itertools 0.12.1",
+ "libc",
+ "libfuzzer-sys",
+ "log",
+ "maybe-rayon",
+ "new_debug_unreachable",
+ "noop_proc_macro",
+ "num-derive",
+ "num-traits",
+ "once_cell",
+ "paste",
+ "profiling",
+ "rand 0.8.5",
+ "rand_chacha 0.3.1",
+ "simd_helpers",
+ "system-deps",
+ "thiserror 1.0.69",
+ "v_frame",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "ravif"
+version = "0.11.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5825c26fddd16ab9f515930d49028a630efec172e903483c94796cfe31893e6b"
+dependencies = [
+ "avif-serialize",
+ "imgref",
+ "loop9",
+ "quick-error",
+ "rav1e",
+ "rayon",
+ "rgb",
+]
+
+[[package]]
+name = "rayon"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.13"
@@ -1428,6 +2114,12 @@ version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
+[[package]]
+name = "rgb"
+version = "0.8.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c6a884d2998352bb4daf0183589aec883f16a6da1f4dde84d8e2e9a5409a1ce"
+
[[package]]
name = "rustc-demangle"
version = "0.1.25"
@@ -1541,12 +2233,61 @@ dependencies = [
"lazy_static",
]
+[[package]]
+name = "shared_child"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7"
+dependencies = [
+ "libc",
+ "sigchld",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "shell-util"
+version = "0.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1b310932f52a5ee39a8636ea7ec44c3255ecc2ce916198d89e405d133c1f4e6"
+dependencies = [
+ "encoding_rs",
+ "os_pipe",
+ "regex",
+ "serde",
+ "serde_json",
+ "shared_child",
+ "thiserror 2.0.12",
+ "tokio",
+ "tracing",
+]
+
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+[[package]]
+name = "sigchld"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1"
+dependencies = [
+ "libc",
+ "os_pipe",
+ "signal-hook",
+]
+
+[[package]]
+name = "signal-hook"
+version = "0.3.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
+dependencies = [
+ "libc",
+ "signal-hook-registry",
+]
+
[[package]]
name = "signal-hook-registry"
version = "1.4.5"
@@ -1562,6 +2303,15 @@ version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe"
+[[package]]
+name = "simd_helpers"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6"
+dependencies = [
+ "quote",
+]
+
[[package]]
name = "slab"
version = "0.4.9"
@@ -1693,6 +2443,20 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "tiff"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af9605de7fee8d9551863fd692cce7637f548dbd9db9180fcc07ccc6d26c336f"
+dependencies = [
+ "fax",
+ "flate2",
+ "half",
+ "quick-error",
+ "weezl",
+ "zune-jpeg",
+]
+
[[package]]
name = "time"
version = "0.3.41"
@@ -1899,9 +2663,9 @@ dependencies = [
[[package]]
name = "tray-icon"
-version = "0.20.1"
+version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f7eee98ec5c90daf179d55c20a49d8c0d043054ce7c26336c09a24d31f14fa0"
+checksum = "a0d92153331e7d02ec09137538996a7786fe679c629c279e82a6be762b7e6fe2"
dependencies = [
"crossbeam-channel",
"dirs 6.0.0",
@@ -1913,7 +2677,7 @@ dependencies = [
"objc2-core-graphics",
"objc2-foundation",
"once_cell",
- "png",
+ "png 0.17.16",
"thiserror 2.0.12",
"windows-sys 0.59.0",
]
@@ -1929,7 +2693,7 @@ dependencies = [
"http",
"httparse",
"log",
- "rand",
+ "rand 0.9.1",
"sha1",
"thiserror 2.0.12",
"utf-8",
@@ -1983,6 +2747,17 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "v_frame"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2"
+dependencies = [
+ "aligned-vec",
+ "num-traits",
+ "wasm-bindgen",
+]
+
[[package]]
name = "valuable"
version = "0.1.1"
@@ -2094,6 +2869,12 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "weezl"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a751b3277700db47d3e574514de2eced5e54dc8a5436a3bf7a0b248b2cee16f3"
+
[[package]]
name = "winapi"
version = "0.3.9"
@@ -2159,6 +2940,12 @@ dependencies = [
"syn 2.0.103",
]
+[[package]]
+name = "windows-link"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
+
[[package]]
name = "windows-sys"
version = "0.48.0"
@@ -2186,6 +2973,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.3",
+]
+
[[package]]
name = "windows-targets"
version = "0.48.5"
@@ -2210,13 +3006,30 @@ dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
- "windows_i686_gnullvm",
+ "windows_i686_gnullvm 0.52.6",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
+[[package]]
+name = "windows-targets"
+version = "0.53.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm 0.53.0",
+ "windows_aarch64_msvc 0.53.0",
+ "windows_i686_gnu 0.53.0",
+ "windows_i686_gnullvm 0.53.0",
+ "windows_i686_msvc 0.53.0",
+ "windows_x86_64_gnu 0.53.0",
+ "windows_x86_64_gnullvm 0.53.0",
+ "windows_x86_64_msvc 0.53.0",
+]
+
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
@@ -2229,6 +3042,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764"
+
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
@@ -2241,6 +3060,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c"
+
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
@@ -2253,12 +3078,24 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3"
+
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11"
+
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
@@ -2271,6 +3108,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d"
+
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
@@ -2283,6 +3126,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba"
+
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
@@ -2295,6 +3144,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57"
+
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
@@ -2307,6 +3162,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
+
[[package]]
name = "winnow"
version = "0.5.40"
@@ -2350,13 +3211,16 @@ version = "0.0.0"
dependencies = [
"ambassador",
"anyhow",
+ "auto-launch",
"clap",
"enum-as-inner",
"futures-util",
"home",
+ "image",
"serde",
"serde_json",
"serde_yaml",
+ "shell-util",
"tauri-winres",
"tokio",
"tokio-tungstenite",
@@ -2397,6 +3261,7 @@ dependencies = [
"serde",
"tracing",
"uuid",
+ "wm-platform",
]
[[package]]
@@ -2425,14 +3290,21 @@ dependencies = [
name = "wm-platform"
version = "0.0.0"
dependencies = [
- "anyhow",
- "auto-launch",
"home",
+ "libtest-mimic-collect",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-application-services",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation",
+ "regex",
+ "serde",
+ "thiserror 2.0.12",
"tokio",
"tracing",
"windows",
"windows-interface",
- "wm-common",
]
[[package]]
@@ -2479,3 +3351,27 @@ dependencies = [
"quote",
"syn 2.0.103",
]
+
+[[package]]
+name = "zune-core"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
+
+[[package]]
+name = "zune-inflate"
+version = "0.2.54"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
+dependencies = [
+ "simd-adler32",
+]
+
+[[package]]
+name = "zune-jpeg"
+version = "0.4.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
+dependencies = [
+ "zune-core",
+]
diff --git a/Cargo.toml b/Cargo.toml
index 546e237f..9bb892ca 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[workspace]
resolver = "2"
members = ["packages/*"]
-default-members = ["packages/wm", "packages/wm-cli", "packages/wm-watcher"]
+default-members = ["packages/wm", "packages/wm-cli"]
[workspace.dependencies]
anyhow = { version = "1", features = ["backtrace"] }
@@ -11,10 +11,16 @@ home = "0.5"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["raw_value"] }
tauri-winres = "0.1"
+thiserror = "2"
+regex = "1"
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = "0.26"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
uuid = { version = "1", features = ["v4", "serde"] }
-
wm-macros = { path = "packages/wm-macros" }
+
+[workspace.lints]
+clippy.all = { level = "warn", priority = -1 }
+clippy.pedantic = { level = "warn", priority = -1 }
+clippy.missing_errors_doc = "allow"
diff --git a/README.md b/README.md
index 24bff172..b0485b01 100644
--- a/README.md
+++ b/README.md
@@ -356,7 +356,7 @@ binding_modes:
**Q: How do I run GlazeWM on startup?**
-Right-click the GlazeWM icon in the system tray and select "Start with Windows".
+Right-click the GlazeWM icon in the system tray and select "Run on system startup".
**Q: How can I create `<insert layout>`?**
diff --git a/clippy.toml b/clippy.toml
new file mode 100644
index 00000000..29348c29
--- /dev/null
+++ b/clippy.toml
@@ -0,0 +1,3 @@
+# TODO: Would ideally move this to `Cargo.toml`, but it's not supported yet.
+# Ref: https://github.com/rust-lang/cargo/issues/12917#issuecomment-1795069197
+doc-valid-idents = ["AppKit", "DisplayPort", ".."]
diff --git a/packages/wm-common/Cargo.toml b/packages/wm-common/Cargo.toml
index e133cab6..3bc16511 100644
--- a/packages/wm-common/Cargo.toml
+++ b/packages/wm-common/Cargo.toml
@@ -9,7 +9,9 @@ path = "src/lib.rs"
[dependencies]
anyhow = { workspace = true }
clap = { workspace = true }
-regex = "1"
+regex = { workspace = true }
serde = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true }
+
+wm-platform = { path = "../wm-platform" }
diff --git a/packages/wm-common/src/active_drag.rs b/packages/wm-common/src/active_drag.rs
index b6199c72..70cd308b 100644
--- a/packages/wm-common/src/active_drag.rs
+++ b/packages/wm-common/src/active_drag.rs
@@ -1,13 +1,25 @@
use serde::{Deserialize, Serialize};
+use wm_platform::Rect;
-#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ActiveDrag {
+ /// Whether the drag is a move or resize.
pub operation: Option<ActiveDragOperation>,
- pub is_from_tiling: bool,
+
+ /// Whether the drag is from a floating window.
+ ///
+ /// If `true`, it means we shouldn't drop the window as a tiling window
+ /// on drag end.
+ pub is_from_floating: bool,
+
+ /// Initial position when the drag started.
+ ///
+ /// Used to calculate movement distance.
+ pub initial_position: Rect,
}
#[derive(Debug, Copy, Clone, Deserialize, PartialEq, Serialize)]
pub enum ActiveDragOperation {
- Moving,
- Resizing,
+ Move,
+ Resize,
}
diff --git a/packages/wm-common/src/app_command.rs b/packages/wm-common/src/app_command.rs
index d39e1b85..18052fb9 100644
--- a/packages/wm-common/src/app_command.rs
+++ b/packages/wm-common/src/app_command.rs
@@ -4,10 +4,9 @@ use clap::{error::KindFormatter, Args, Parser, ValueEnum};
use serde::{Deserialize, Deserializer, Serialize};
use tracing::Level;
use uuid::Uuid;
+use wm_platform::{Delta, Direction, LengthValue, OpacityValue};
-use crate::{
- Delta, Direction, LengthValue, OpacityValue, TilingDirection,
-};
+use crate::TilingDirection;
const VERSION: &str = env!("VERSION_NUMBER");
diff --git a/packages/wm-common/src/dtos/monitor_dto.rs b/packages/wm-common/src/dtos/monitor_dto.rs
index fe700c37..1a789c9f 100644
--- a/packages/wm-common/src/dtos/monitor_dto.rs
+++ b/packages/wm-common/src/dtos/monitor_dto.rs
@@ -1,8 +1,8 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
+use wm_platform::Rect;
use super::ContainerDto;
-use crate::Rect;
/// User-friendly representation of a monitor.
///
@@ -21,7 +21,7 @@ pub struct MonitorDto {
pub y: i32,
pub dpi: u32,
pub scale_factor: f32,
- pub handle: isize,
+ pub handle: Option<isize>,
pub device_name: String,
pub device_path: Option<String>,
pub hardware_id: Option<String>,
diff --git a/packages/wm-common/src/dtos/window_dto.rs b/packages/wm-common/src/dtos/window_dto.rs
index 589263c7..3237d1f9 100644
--- a/packages/wm-common/src/dtos/window_dto.rs
+++ b/packages/wm-common/src/dtos/window_dto.rs
@@ -1,7 +1,8 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
+use wm_platform::{Rect, RectDelta};
-use crate::{ActiveDrag, DisplayState, Rect, RectDelta, WindowState};
+use crate::{ActiveDrag, DisplayState, WindowState};
/// User-friendly representation of a tiling or non-tiling window.
///
@@ -24,6 +25,7 @@ pub struct WindowDto {
pub floating_placement: Rect,
pub handle: isize,
pub title: String,
+ #[cfg(target_os = "windows")]
pub class_name: String,
pub process_name: String,
pub active_drag: Option<ActiveDrag>,
diff --git a/packages/wm-common/src/hide_corner.rs b/packages/wm-common/src/hide_corner.rs
new file mode 100644
index 00000000..3e91b2ee
--- /dev/null
+++ b/packages/wm-common/src/hide_corner.rs
@@ -0,0 +1,6 @@
+/// Represents the corner of a monitor that a window should be hidden in.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum HideCorner {
+ BottomLeft,
+ BottomRight,
+}
diff --git a/packages/wm-common/src/lib.rs b/packages/wm-common/src/lib.rs
index 762aba40..94b3eff0 100644
--- a/packages/wm-common/src/lib.rs
+++ b/packages/wm-common/src/lib.rs
@@ -3,18 +3,11 @@
mod active_drag;
mod app_command;
-mod color;
-mod delta;
-mod direction;
mod display_state;
mod dtos;
+mod hide_corner;
mod ipc;
-mod length_value;
-mod opacity_value;
mod parsed_config;
-mod point;
-mod rect;
-mod rect_delta;
mod tiling_direction;
mod utils;
mod window_state;
@@ -22,18 +15,11 @@ mod wm_event;
pub use active_drag::*;
pub use app_command::*;
-pub use color::*;
-pub use delta::*;
-pub use direction::*;
pub use display_state::*;
pub use dtos::*;
+pub use hide_corner::*;
pub use ipc::*;
-pub use length_value::*;
-pub use opacity_value::*;
pub use parsed_config::*;
-pub use point::*;
-pub use rect::*;
-pub use rect_delta::*;
pub use tiling_direction::*;
pub use utils::*;
pub use window_state::*;
diff --git a/packages/wm-common/src/parsed_config.rs b/packages/wm-common/src/parsed_config.rs
index 0bd55df5..37e5c5ad 100644
--- a/packages/wm-common/src/parsed_config.rs
+++ b/packages/wm-common/src/parsed_config.rs
@@ -1,9 +1,11 @@
use serde::{Deserialize, Serialize};
-
-use crate::{
- app_command::InvokeCommand, Color, LengthValue, OpacityValue, RectDelta,
+use wm_platform::{
+ Color, CornerStyle, Key, Keybinding, LengthValue, OpacityValue,
+ RectDelta,
};
+use crate::app_command::InvokeCommand;
+
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default, rename_all(serialize = "camelCase"))]
pub struct ParsedConfig {
@@ -89,6 +91,7 @@ pub struct GeneralConfig {
pub config_reload_commands: Vec<InvokeCommand>,
/// How windows should be hidden when switching workspaces.
+ #[serde(deserialize_with = "deserialize_hide_method")]
pub hide_method: HideMethod,
/// Affects which windows get shown in the native Windows taskbar.
@@ -104,7 +107,16 @@ impl Default for GeneralConfig {
startup_commands: vec![],
shutdown_commands: vec![],
config_reload_commands: vec![],
- hide_method: HideMethod::Cloak,
+ hide_method: {
+ #[cfg(target_os = "macos")]
+ {
+ HideMethod::PlaceInCorner
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ HideMethod::Cloak
+ }
+ },
show_all_in_taskbar: false,
}
}
@@ -134,13 +146,18 @@ pub enum HideMethod {
Hide,
#[default]
Cloak,
+ PlaceInCorner,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default, rename_all(serialize = "camelCase"))]
pub struct KeybindingConfig {
/// Keyboard shortcut to trigger the keybinding.
- pub bindings: Vec<String>,
+ #[serde(
+ deserialize_with = "deserialize_bindings",
+ serialize_with = "serialize_bindings"
+ )]
+ pub bindings: Vec<Keybinding>,
/// WM commands to run when the keybinding is triggered.
pub commands: Vec<InvokeCommand>,
@@ -278,16 +295,6 @@ pub struct CornerEffectConfig {
pub style: CornerStyle,
}
-#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
-#[serde(rename_all = "snake_case")]
-pub enum CornerStyle {
- #[default]
- Default,
- Square,
- Rounded,
- SmallRounded,
-}
-
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default, rename_all(serialize = "camelCase"))]
pub struct TransparencyEffectConfig {
@@ -389,3 +396,79 @@ const fn default_bool<const V: bool>() -> bool {
fn default_window_rule_on() -> Vec<WindowRuleEvent> {
vec![WindowRuleEvent::Manage, WindowRuleEvent::TitleChange]
}
+
+/// Helper function for serializing a vector of keybindings.
+///
+/// Returns a vector of strings (e.g. `["cmd+shift+a", "ctrl+shift+b"]`).
+fn serialize_bindings<S>(
+ bindings: &[Keybinding],
+ serializer: S,
+) -> Result<S::Ok, S::Error>
+where
+ S: serde::Serializer,
+{
+ let binding_strings: Vec<String> = bindings
+ .iter()
+ .map(|binding| {
+ binding
+ .keys()
+ .iter()
+ .map(|key| key.to_string().to_lowercase())
+ .collect::<Vec<_>>()
+ .join("+")
+ })
+ .collect();
+
+ binding_strings.serialize(serializer)
+}
+
+/// Helper function for deserializing a vector of strings into keybindings.
+///
+/// Returns a vector of [`Keybinding`].
+fn deserialize_bindings<'de, D>(
+ deserializer: D,
+) -> Result<Vec<Keybinding>, D::Error>
+where
+ D: serde::de::Deserializer<'de>,
+{
+ let s: Vec<&str> = serde::de::Deserialize::deserialize(deserializer)?;
+ s.iter()
+ .map(|keybinding_str| {
+ let keys: Vec<Key> = keybinding_str
+ .split('+')
+ .map(|key| {
+ key.trim().parse().or_else(|_| Key::try_from_literal(key))
+ })
+ .collect::<Result<Vec<Key>, _>>()
+ .map_err(serde::de::Error::custom)?;
+
+ Keybinding::new(keys).map_err(serde::de::Error::custom)
+ })
+ .collect()
+}
+
+/// Helper function for deserializing [`HideMethod`].
+///
+/// On macOS, [`HideMethod::Hide`] and [`HideMethod::Cloak`] are not valid
+/// and are automatically converted to [`HideMethod::PlaceInCorner`].
+fn deserialize_hide_method<'de, D>(
+ deserializer: D,
+) -> Result<HideMethod, D::Error>
+where
+ D: serde::de::Deserializer<'de>,
+{
+ // LINT: The deserialized value is ignored on macOS, but we still want
+ // to produce an error for invalid values.
+ #[allow(unused_variables)]
+ let method = HideMethod::deserialize(deserializer)?;
+
+ #[cfg(target_os = "macos")]
+ {
+ Ok(HideMethod::PlaceInCorner)
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ {
+ Ok(method)
+ }
+}
diff --git a/packages/wm-common/src/point.rs b/packages/wm-common/src/point.rs
deleted file mode 100644
index 0f87c385..00000000
--- a/packages/wm-common/src/point.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-/// Represents an x-y coordinate.
-#[derive(Debug, Clone)]
-pub struct Point {
- pub x: i32,
- pub y: i32,
-}
diff --git a/packages/wm-common/src/tiling_direction.rs b/packages/wm-common/src/tiling_direction.rs
index 0a43d0bc..40b36139 100644
--- a/packages/wm-common/src/tiling_direction.rs
+++ b/packages/wm-common/src/tiling_direction.rs
@@ -2,8 +2,7 @@ use std::str::FromStr;
use anyhow::bail;
use serde::{Deserialize, Serialize};
-
-use super::Direction;
+use wm_platform::Direction;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
@@ -17,7 +16,7 @@ impl TilingDirection {
///
/// Example:
/// ```
- /// # use wm::common::TilingDirection;
+ /// # use wm_platform::TilingDirection;
/// let dir = TilingDirection::Horizontal.inverse();
/// assert_eq!(dir, TilingDirection::Vertical);
/// ```
@@ -34,7 +33,7 @@ impl TilingDirection {
///
/// Example:
/// ```
- /// # use wm::common::{Direction, TilingDirection};
+ /// # use wm_platform::{Direction, TilingDirection};
/// let dir = TilingDirection::from_direction(&Direction::Left);
/// assert_eq!(dir, TilingDirection::Horizontal);
/// ```
@@ -54,7 +53,7 @@ impl FromStr for TilingDirection {
///
/// Example:
/// ```
- /// # use wm::common::TilingDirection;
+ /// # use wm_platform::TilingDirection;
/// # use std::str::FromStr;
/// let dir = TilingDirection::from_str("horizontal");
/// assert_eq!(dir.unwrap(), TilingDirection::Horizontal);
diff --git a/packages/wm-common/src/utils/memo.rs b/packages/wm-common/src/utils/memo.rs
deleted file mode 100644
index 84c833cd..00000000
--- a/packages/wm-common/src/utils/memo.rs
+++ /dev/null
@@ -1,77 +0,0 @@
-use std::sync::{Arc, Mutex};
-
-/// A thread-safe type that provides lazy initialization and caching of a
-/// value.
-#[derive(Debug, Clone)]
-pub struct Memo<T>
-where
- T: Clone,
-{
- value: Arc<Mutex<Option<T>>>,
-}
-
-impl<T> Default for Memo<T>
-where
- T: Clone,
-{
- fn default() -> Self {
- Self {
- value: Arc::new(Mutex::new(None)),
- }
- }
-}
-
-impl<T> Memo<T>
-where
- T: Clone,
-{
- /// Creates a new `Memo` instance with `None` as the initial value.
- #[must_use]
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Retrieves the cached value if it exists, otherwise initializes it
- /// using the provided closure.
- ///
- /// # Panics
- ///
- /// If the internal mutex is poisoned.
- pub fn get_or_init<F, R>(
- &self,
- retriever_fn: F,
- arg: &R,
- ) -> anyhow::Result<T>
- where
- F: FnOnce(&R) -> anyhow::Result<T>,
- T: Clone,
- {
- let mut value_ref = self.value.lock().unwrap();
-
- if let Some(value) = value_ref.as_ref() {
- Ok(value.clone())
- } else {
- let value = retriever_fn(arg)?;
- *value_ref = Some(value.clone());
- Ok(value)
- }
- }
-
- /// Refreshes the cached value by generating a new value using the
- /// provided closure.
- ///
- /// # Panics
- ///
- /// If the internal mutex is poisoned.
- pub fn update<F, R>(&self, retriever_fn: F, arg: &R) -> anyhow::Result<T>
- where
- F: FnOnce(&R) -> anyhow::Result<T>,
- T: Clone,
- {
- let mut value_ref = self.value.lock().unwrap();
-
- let value = retriever_fn(arg)?;
- *value_ref = Some(value.clone());
- Ok(value)
- }
-}
diff --git a/packages/wm-common/src/utils/mod.rs b/packages/wm-common/src/utils/mod.rs
index c886d13b..df20011b 100644
--- a/packages/wm-common/src/utils/mod.rs
+++ b/packages/wm-common/src/utils/mod.rs
@@ -1,8 +1,6 @@
mod iterator_ext;
-mod memo;
mod try_warn;
mod vec_deque_ext;
pub use iterator_ext::*;
-pub use memo::*;
pub use vec_deque_ext::*;
diff --git a/packages/wm-macros/src/common/mod.rs b/packages/wm-macros/src/common/mod.rs
index eb79885c..0e7ccb2f 100644
--- a/packages/wm-macros/src/common/mod.rs
+++ b/packages/wm-macros/src/common/mod.rs
@@ -1,12 +1,12 @@
-/// Utilitirs for parsing attributes
+/// Utilities for parsing attributes
pub mod attributes;
-/// Utilities for parsing alternitives and combinators
+/// Utilities for parsing alternatives and combinators
pub mod branch;
/// Extension traits and utilities to make error handling more succinct
pub mod error_handling;
-/// Utilitirs for parsing a named parameter (`name = vaue`)
+/// Utilities for parsing a named parameter (`name = value`)
pub mod named_parameter;
-/// Type for a parsable type within parenthesis
+/// Type for a parsable type within parentheses
pub mod parenthesized;
/// Trait to get a `Peek` object from compatible syn types
pub mod peekable;
diff --git a/packages/wm-platform/Cargo.toml b/packages/wm-platform/Cargo.toml
index f4079810..97b80ec2 100644
--- a/packages/wm-platform/Cargo.toml
+++ b/packages/wm-platform/Cargo.toml
@@ -5,13 +5,25 @@ edition = "2021"
[lib]
path = "src/lib.rs"
+test = false
+
+[[test]]
+name = "test"
+harness = false
+path = "src/test.rs"
[dependencies]
-anyhow = { workspace = true }
-auto-launch = "0.5.0"
home = { workspace = true }
+thiserror = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
+serde = { workspace = true }
+regex = { workspace = true }
+
+[dev-dependencies]
+libtest-mimic-collect = "0.3.2"
+
+[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.52", features = [
"implement",
"Win32_Devices_HumanInterfaceDevice",
@@ -35,4 +47,34 @@ windows = { version = "0.52", features = [
"Win32_UI_WindowsAndMessaging",
] }
windows-interface = { version = "0.52" }
-wm-common = { path = "../wm-common" }
+
+[target.'cfg(target_os = "macos")'.dependencies]
+objc2-core-graphics = "0.3.1"
+objc2 = "0.6.1"
+objc2-app-kit = { version = "0.3.1", default-features = false, features = [
+ "NSAlert",
+ "NSApplication",
+ "NSEvent",
+ "NSGraphics",
+ "NSRunningApplication",
+ "NSResponder",
+ "NSScreen",
+ "NSWindow",
+ "NSWorkspace",
+ "libc",
+ "objc2-core-foundation",
+] }
+objc2-application-services = "0.3.1"
+objc2-core-foundation = { version = "0.3.1", features = [
+ "CFCGTypes",
+ "CFUUID",
+] }
+objc2-foundation = { version = "0.3.1", default-features = false, features = [
+ "NSArray",
+ "NSEnumerator",
+ "NSNotification",
+ "NSKeyValueCoding",
+ "NSString",
+ "NSThread",
+ "NSValue",
+] }
diff --git a/packages/wm-platform/build.rs b/packages/wm-platform/build.rs
new file mode 100644
index 00000000..a3fa9b08
--- /dev/null
+++ b/packages/wm-platform/build.rs
@@ -0,0 +1,6 @@
+fn main() {
+ #[cfg(target_os = "macos")]
+ println!(
+ "cargo:rustc-link-search=framework=/System/Library/PrivateFrameworks"
+ );
+}
diff --git a/packages/wm-platform/src/dispatcher.rs b/packages/wm-platform/src/dispatcher.rs
new file mode 100644
index 00000000..4dc4ffbb
--- /dev/null
+++ b/packages/wm-platform/src/dispatcher.rs
@@ -0,0 +1,835 @@
+use std::{
+ path::Path,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
+ thread::ThreadId,
+};
+
+#[cfg(target_os = "macos")]
+use objc2::MainThreadMarker;
+#[cfg(target_os = "macos")]
+use objc2_app_kit::{NSAlert, NSAlertStyle, NSEvent};
+#[cfg(target_os = "macos")]
+use objc2_application_services::{
+ kAXTrustedCheckOptionPrompt, AXIsProcessTrustedWithOptions,
+};
+#[cfg(target_os = "macos")]
+use objc2_core_foundation::{CFBoolean, CFDictionary, CGPoint};
+#[cfg(target_os = "macos")]
+use objc2_core_graphics::{CGError, CGEvent, CGWarpMouseCursorPosition};
+#[cfg(target_os = "macos")]
+use objc2_foundation::NSString;
+#[cfg(target_os = "windows")]
+use windows::{
+ core::PCWSTR,
+ Win32::{
+ Foundation::POINT,
+ System::Environment::ExpandEnvironmentStringsW,
+ UI::{
+ Input::KeyboardAndMouse::{
+ GetAsyncKeyState, VK_LBUTTON, VK_RBUTTON,
+ },
+ Shell::{
+ ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS,
+ SHELLEXECUTEINFOW,
+ },
+ WindowsAndMessaging::{
+ GetCursorPos, MessageBoxW, SetCursorPos, SystemParametersInfoW,
+ ANIMATIONINFO, MB_ICONERROR, MB_OK, MB_SYSTEMMODAL,
+ SPIF_SENDCHANGE, SPIF_UPDATEINIFILE, SPI_GETANIMATION,
+ SPI_SETANIMATION, SW_HIDE, SW_NORMAL,
+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS,
+ },
+ },
+ },
+};
+
+#[cfg(target_os = "macos")]
+use crate::platform_impl::Application;
+use crate::{
+ platform_impl, Display, DisplayDevice, MouseButton, NativeWindow, Point,
+};
+
+/// Type alias for a closure to be executed by the event loop.
+pub type DispatchFn = dyn FnOnce() + Send + 'static;
+
+/// A callback that pre-processes window procedure messages received by the
+/// event loop.
+///
+/// Mirrors the Win32 [`WNDPROC`] signature. Returns `Some(lresult)` if
+/// the message was handled, or `None` to pass it along.
+///
+/// [`WNDPROC`]: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nc-winuser-wndproc
+pub type WndProcCallback =
+ dyn Fn(isize, u32, usize, isize) -> Option<isize> + Send + 'static;
+
+/// macOS-specific extension trait for [`Dispatcher`].
+#[cfg(target_os = "macos")]
+pub trait DispatcherExtMacOs {
+ /// Gets all running applications.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on macOS.
+ fn all_applications(&self) -> crate::Result<Vec<Application>>;
+
+ /// Checks whether accessibility permissions are granted.
+ ///
+ /// If `prompt` is `true`, a dialog will be shown to the user to request
+ /// accessibility permissions.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on macOS.
+ fn has_ax_permission(&self, prompt: bool) -> bool;
+}
+
+#[cfg(target_os = "macos")]
+impl DispatcherExtMacOs for Dispatcher {
+ fn all_applications(&self) -> crate::Result<Vec<Application>> {
+ platform_impl::all_applications(self)
+ }
+
+ fn has_ax_permission(&self, prompt: bool) -> bool {
+ let options = CFDictionary::from_slices(
+ &[unsafe { kAXTrustedCheckOptionPrompt }],
+ &[CFBoolean::new(prompt)],
+ );
+
+ unsafe { AXIsProcessTrustedWithOptions(Some(options.as_ref())) }
+ }
+}
+
+/// Windows-specific extensions for `Dispatcher`.
+#[cfg(target_os = "windows")]
+pub trait DispatcherExtWindows {
+ /// Returns the handle of the event loop's message window.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn message_window_handle(&self) -> isize;
+
+ /// Registers a callback to pre-process messages in the event loop's
+ /// window procedure.
+ ///
+ /// Returns a unique ID that can be passed to
+ /// `deregister_wndproc_callback` to remove the callback.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn register_wndproc_callback(
+ &self,
+ callback: Box<crate::WndProcCallback>,
+ ) -> crate::Result<usize>;
+
+ /// Removes a previously registered window procedure callback by its ID.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn deregister_wndproc_callback(&self, id: usize) -> crate::Result<()>;
+
+ /// Gets whether system-wide window transition animations are enabled.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn window_animations_enabled(&self) -> crate::Result<bool>;
+
+ /// Enables or disables system-wide window transition animations.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn set_window_animations_enabled(
+ &self,
+ enable: bool,
+ ) -> crate::Result<()>;
+
+ /// Expands `%VAR%` environment variable references in `input`.
+ ///
+ /// Returns the expanded string.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ ///
+ /// TODO: Remove this. Handle environment variable expansion in a
+ /// unified, cross-platform way.
+ fn expand_env_strings(&self, input: &str) -> crate::Result<String>;
+
+ /// Runs the specified program using `ShellExecuteExW`.
+ ///
+ /// If `hide_window` is `true`, the spawned process window is hidden.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ ///
+ /// TODO: Remove this. Use `shell_util::Shell::spawn` instead.
+ fn shell_execute_ex(
+ &self,
+ program: &str,
+ args: &str,
+ directory: &Path,
+ hide_window: bool,
+ ) -> crate::Result<()>;
+}
+
+#[cfg(target_os = "windows")]
+impl DispatcherExtWindows for Dispatcher {
+ fn message_window_handle(&self) -> isize {
+ self.source.as_ref().unwrap().message_window_handle
+ }
+
+ fn register_wndproc_callback(
+ &self,
+ callback: Box<crate::WndProcCallback>,
+ ) -> crate::Result<usize> {
+ self
+ .source
+ .as_ref()
+ .unwrap()
+ .register_wndproc_callback(callback)
+ }
+
+ fn deregister_wndproc_callback(&self, id: usize) -> crate::Result<()> {
+ self
+ .source
+ .as_ref()
+ .unwrap()
+ .deregister_wndproc_callback(id)
+ }
+
+ fn window_animations_enabled(&self) -> crate::Result<bool> {
+ let mut animation_info = ANIMATIONINFO {
+ #[allow(clippy::cast_possible_truncation)]
+ cbSize: std::mem::size_of::<ANIMATIONINFO>() as u32,
+ iMinAnimate: 0,
+ };
+
+ unsafe {
+ SystemParametersInfoW(
+ SPI_GETANIMATION,
+ animation_info.cbSize,
+ Some(std::ptr::from_mut(&mut animation_info).cast()),
+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
+ )
+ }?;
+
+ Ok(animation_info.iMinAnimate != 0)
+ }
+
+ fn set_window_animations_enabled(
+ &self,
+ enable: bool,
+ ) -> crate::Result<()> {
+ let mut animation_info = ANIMATIONINFO {
+ #[allow(clippy::cast_possible_truncation)]
+ cbSize: std::mem::size_of::<ANIMATIONINFO>() as u32,
+ iMinAnimate: i32::from(enable),
+ };
+
+ unsafe {
+ SystemParametersInfoW(
+ SPI_SETANIMATION,
+ animation_info.cbSize,
+ Some(std::ptr::from_mut(&mut animation_info).cast()),
+ SPIF_UPDATEINIFILE | SPIF_SENDCHANGE,
+ )
+ }?;
+
+ Ok(())
+ }
+
+ fn expand_env_strings(&self, input: &str) -> crate::Result<String> {
+ let wide_input =
+ input.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
+
+ let size = unsafe {
+ ExpandEnvironmentStringsW(PCWSTR(wide_input.as_ptr()), None)
+ };
+
+ if size == 0 {
+ return Err(crate::Error::Platform(format!(
+ "Failed to expand environment strings in '{input}'.",
+ )));
+ }
+
+ let mut buffer = vec![0u16; size as usize];
+ let size = unsafe {
+ ExpandEnvironmentStringsW(
+ PCWSTR(wide_input.as_ptr()),
+ Some(&mut buffer),
+ )
+ };
+
+ // The size includes the null terminator, so subtract one.
+ Ok(String::from_utf16_lossy(&buffer[..(size - 1) as usize]))
+ }
+
+ fn shell_execute_ex(
+ &self,
+ program: &str,
+ args: &str,
+ directory: &Path,
+ hide_window: bool,
+ ) -> crate::Result<()> {
+ let program_wide =
+ program.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
+ let args_wide = args.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
+ let directory_wide = directory
+ .to_string_lossy()
+ .encode_utf16()
+ .chain(Some(0))
+ .collect::<Vec<_>>();
+
+ let mut exec_info = SHELLEXECUTEINFOW {
+ #[allow(clippy::cast_possible_truncation)]
+ cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
+ lpFile: PCWSTR(program_wide.as_ptr()),
+ lpParameters: PCWSTR(args_wide.as_ptr()),
+ lpDirectory: PCWSTR(directory_wide.as_ptr()),
+ nShow: if hide_window { SW_HIDE } else { SW_NORMAL }.0 as _,
+ fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC,
+ ..Default::default()
+ };
+
+ unsafe { ShellExecuteExW(&raw mut exec_info) }
+ .map_err(crate::Error::from)
+ }
+}
+
+/// A thread-safe dispatcher for cross-platform window management
+/// operations.
+///
+/// On macOS, operations are automatically dispatched to the main thread
+/// whenever necessary.
+///
+/// # Thread safety
+///
+/// This type is `Send + Sync` and can be cheaply cloned and shared across
+/// threads.
+///
+/// # Example usage
+///
+/// ```rust,no_run
+/// use wm_platform::EventLoop;
+/// use std::thread;
+///
+/// # fn main() -> wm_platform::Result<()> {
+/// let (event_loop, dispatcher) = EventLoop::new()?;
+///
+/// // Dispatch from another thread.
+/// thread::spawn(move || {
+/// dispatcher.dispatch_async(|| {
+/// println!("This is running on the event loop thread!");
+/// }).unwrap();
+/// });
+///
+/// event_loop.run()
+/// # }
+/// ```
+#[derive(Clone)]
+pub struct Dispatcher {
+ source: Option<platform_impl::EventLoopSource>,
+ stopped: Arc<AtomicBool>,
+}
+
+impl Dispatcher {
+ // TODO: Allow for source to be resolved after creation when used via
+ // `EventLoopInstaller` (to be added).
+ pub(crate) fn new(
+ source: Option<platform_impl::EventLoopSource>,
+ stopped: Arc<AtomicBool>,
+ ) -> Self {
+ Self { source, stopped }
+ }
+
+ /// Stops the event loop gracefully from any thread.
+ ///
+ /// After calling this method, all subsequent calls to `dispatch_async()`
+ /// and `dispatch_sync()` will return `Error::EventLoopStopped`.
+ pub fn stop_event_loop(&self) -> crate::Result<()> {
+ // Set stopped flag to prevent new dispatches.
+ self.stopped.store(true, Ordering::SeqCst);
+
+ // Signal platform-specific event loop to stop.
+ if let Some(source) = &self.source {
+ source.send_stop()?;
+ }
+
+ Ok(())
+ }
+
+ /// Asynchronously executes a closure on the event loop thread.
+ ///
+ /// If the current thread is the event loop thread, the function is
+ /// executed directly (synchronously).
+ ///
+ /// Returns `Ok(())` if the closure was successfully queued. No result is
+ /// returned.
+ pub fn dispatch_async<F>(&self, dispatch_fn: F) -> crate::Result<()>
+ where
+ F: FnOnce() + Send + 'static,
+ {
+ // Check if stopped first.
+ if self.stopped.load(Ordering::SeqCst) {
+ return Err(crate::Error::EventLoopStopped);
+ }
+
+ // Execute the function directly if already on the event loop thread.
+ if self.is_event_loop_thread() {
+ dispatch_fn();
+ return Ok(());
+ }
+
+ if let Some(source) = &self.source {
+ // Platform-specific behavior:
+ // * On Windows, this uses `PostMessageW` to send callbacks via
+ // window messages.
+ // * On macOS, this uses `CFRunLoopSourceSignal` to wake the run loop
+ // and process callbacks.
+ source.send_dispatch_async(dispatch_fn)?;
+ }
+
+ Ok(())
+ }
+
+ /// Synchronously executes a closure on the event loop thread.
+ ///
+ /// If the current thread is the event loop thread, the function is
+ /// executed directly.
+ ///
+ /// Returns a `Result` with the closure's return value.
+ #[allow(clippy::missing_panics_doc)]
+ pub fn dispatch_sync<F, R>(&self, dispatch_fn: F) -> crate::Result<R>
+ where
+ F: FnOnce() -> R + Send,
+ R: Send,
+ {
+ // Check if stopped first.
+ if self.stopped.load(Ordering::SeqCst) {
+ return Err(crate::Error::EventLoopStopped);
+ }
+
+ // Execute the function directly if already on the event loop thread.
+ if self.is_event_loop_thread() {
+ return Ok(dispatch_fn());
+ }
+
+ let (result_tx, result_rx) = std::sync::mpsc::channel();
+
+ // TODO: Block until event loop source is set.
+ self.source.as_ref().unwrap().send_dispatch_sync(move || {
+ let result = dispatch_fn();
+
+ if result_tx.send(result).is_err() {
+ tracing::error!("Failed to send closure result.");
+ }
+ })?;
+
+ result_rx
+ .recv_timeout(std::time::Duration::from_secs(5))
+ .map_err(crate::Error::ChannelRecv)
+ }
+
+ /// Gets the thread ID of the event loop thread.
+ #[allow(clippy::missing_panics_doc)]
+ #[must_use]
+ pub fn thread_id(&self) -> ThreadId {
+ // TODO: Block until event loop source is set.
+ self.source.as_ref().unwrap().thread_id
+ }
+
+ /// Gets whether the current thread is the event loop thread.
+ #[must_use]
+ fn is_event_loop_thread(&self) -> bool {
+ std::thread::current().id() == self.thread_id()
+ }
+
+ /// Gets all active displays.
+ ///
+ /// NOTE: Does not guarantee a specific, consistent order.
+ ///
+ /// Returns all displays that are currently active and available for use.
+ pub fn displays(&self) -> crate::Result<Vec<Display>> {
+ platform_impl::all_displays(self)
+ }
+
+ /// Gets all active displays sorted left-to-right, top-to-bottom.
+ ///
+ /// Returns all displays that are currently active and available for
+ /// use, sorted by their X coordinate (left edge), with ties broken
+ /// by Y coordinate (top edge).
+ ///
+ /// TODO: Remove this. Instead, call `sort_monitors` after populating WM
+ /// state. Need to assign workspaces after sorting monitors because of
+ /// `bind_to_monitor`.
+ pub fn sorted_displays(&self) -> crate::Result<Vec<Display>> {
+ let displays = platform_impl::all_displays(self)?;
+
+ let mut displays_with_bounds = displays
+ .into_iter()
+ .map(|display| {
+ let bounds = display.bounds()?;
+ crate::Result::Ok((display, bounds))
+ })
+ .try_collect::<Vec<_>>()?;
+
+ displays_with_bounds.sort_by(|(_, bounds_a), (_, bounds_b)| {
+ if bounds_a.x() == bounds_b.x() {
+ bounds_a.y().cmp(&bounds_b.y())
+ } else {
+ bounds_a.x().cmp(&bounds_b.x())
+ }
+ });
+
+ Ok(
+ displays_with_bounds
+ .into_iter()
+ .map(|(display, _)| display)
+ .collect(),
+ )
+ }
+
+ /// Gets all display devices.
+ ///
+ /// NOTE: Does not guarantee a specific, consistent order.
+ ///
+ /// Returns all display devices including active, inactive, and
+ /// disconnected ones.
+ pub fn display_devices(&self) -> crate::Result<Vec<DisplayDevice>> {
+ platform_impl::all_display_devices(self)
+ }
+
+ /// Gets the display containing the specified point.
+ ///
+ /// If no display contains the point, returns the primary display.
+ pub fn display_from_point(
+ &self,
+ point: &Point,
+ ) -> crate::Result<Display> {
+ platform_impl::display_from_point(point, self)
+ }
+
+ /// Gets the primary display.
+ pub fn primary_display(&self) -> crate::Result<Display> {
+ platform_impl::primary_display(self)
+ }
+
+ /// Gets the nearest display to a window.
+ ///
+ /// Returns the display that contains the largest area of the window's
+ /// frame. Defaults to the primary display if no overlap is found.
+ pub fn nearest_display(
+ &self,
+ native_window: &NativeWindow,
+ ) -> crate::Result<Display> {
+ platform_impl::nearest_display(native_window, self)
+ }
+
+ /// Gets all visible windows from all running applications.
+ ///
+ /// NOTE: Does not guarantee a specific, consistent order.
+ ///
+ /// Returns a vector of `NativeWindow` instances for windows that are
+ /// not hidden and on the current virtual desktop.
+ pub fn visible_windows(&self) -> crate::Result<Vec<NativeWindow>> {
+ platform_impl::visible_windows(self)
+ }
+
+ /// Gets the currently focused (foreground) window.
+ ///
+ /// This may be the desktop window if no window has focus.
+ pub fn focused_window(&self) -> crate::Result<NativeWindow> {
+ platform_impl::focused_window(self)
+ }
+
+ /// Gets the current cursor position.
+ pub fn cursor_position(&self) -> crate::Result<Point> {
+ #[cfg(target_os = "macos")]
+ {
+ let event = unsafe { CGEvent::new(None) };
+ let point = unsafe { CGEvent::location(event.as_deref()) };
+
+ #[allow(clippy::cast_possible_truncation)]
+ Ok(Point {
+ x: point.x as i32,
+ y: point.y as i32,
+ })
+ }
+ #[cfg(target_os = "windows")]
+ {
+ let mut point = POINT { x: 0, y: 0 };
+ unsafe { GetCursorPos(&raw mut point) }?;
+
+ Ok(Point {
+ x: point.x,
+ y: point.y,
+ })
+ }
+ }
+
+ /// Gets whether the given mouse button is currently pressed.
+ #[must_use]
+ pub fn is_mouse_down(&self, button: &MouseButton) -> bool {
+ #[cfg(target_os = "macos")]
+ {
+ let bit_index = match button {
+ MouseButton::Left => 0usize,
+ MouseButton::Right => 1usize,
+ };
+
+ // Check if bit at corresponding index is set in the bitmask.
+ let pressed_mask = unsafe { NSEvent::pressedMouseButtons() };
+ (pressed_mask & (1usize << bit_index)) != 0
+ }
+ #[cfg(target_os = "windows")]
+ {
+ // Virtual-key codes for mouse buttons.
+ let vk_code = match button {
+ MouseButton::Left => VK_LBUTTON.0,
+ MouseButton::Right => VK_RBUTTON.0,
+ };
+
+ // High-order bit set indicates the key is currently down.
+ let state = unsafe { GetAsyncKeyState(vk_code.into()) };
+ (state.cast_unsigned() & 0x8000u16) != 0
+ }
+ }
+
+ /// Gets the top-level window at the specified point.
+ pub fn window_from_point(
+ &self,
+ point: &Point,
+ ) -> crate::Result<Option<crate::NativeWindow>> {
+ platform_impl::window_from_point(point, self)
+ }
+
+ /// Sets the cursor position to the specified coordinates.
+ pub fn set_cursor_position(&self, point: &Point) -> crate::Result<()> {
+ #[cfg(target_os = "macos")]
+ {
+ let point = CGPoint {
+ x: f64::from(point.x),
+ y: f64::from(point.y),
+ };
+
+ if unsafe { CGWarpMouseCursorPosition(point) } != CGError::Success {
+ return Err(crate::Error::Platform(
+ "Failed to set cursor position.".to_string(),
+ ));
+ }
+ }
+ #[cfg(target_os = "windows")]
+ {
+ unsafe { SetCursorPos(point.x, point.y) }?;
+ }
+
+ Ok(())
+ }
+
+ /// Removes focus from the current window and focuses the desktop.
+ pub fn reset_focus(&self) -> crate::Result<()> {
+ platform_impl::reset_focus(self)
+ }
+
+ /// Opens the operating system's file explorer at the given path.
+ ///
+ /// # Platform-specific
+ ///
+ /// - **Windows**: Uses `explorer` to open the file explorer.
+ /// - **macOS**: Uses `open` to open the file explorer.
+ pub fn open_file_explorer(&self, path: &Path) -> crate::Result<()> {
+ #[cfg(target_os = "windows")]
+ {
+ let normalized_path = std::fs::canonicalize(path)?;
+ std::process::Command::new("explorer")
+ .arg(normalized_path)
+ .spawn()?;
+ }
+ #[cfg(target_os = "macos")]
+ {
+ std::process::Command::new("open")
+ .arg(path)
+ .arg("-R")
+ .spawn()?;
+ }
+
+ Ok(())
+ }
+
+ /// Shows a modal error dialog with the given title and message.
+ ///
+ /// Blocks the current thread until the user dismisses the dialog.
+ #[allow(clippy::missing_panics_doc)]
+ pub fn show_error_dialog(&self, title: &str, message: &str) {
+ #[cfg(target_os = "windows")]
+ {
+ let title_wide =
+ title.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
+ let message_wide =
+ message.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
+
+ unsafe {
+ MessageBoxW(
+ None,
+ PCWSTR(message_wide.as_ptr()),
+ PCWSTR(title_wide.as_ptr()),
+ MB_ICONERROR | MB_OK | MB_SYSTEMMODAL,
+ );
+ }
+ }
+ #[cfg(target_os = "macos")]
+ {
+ // TODO: This should block indefinitely. Currently, it gets timed out
+ // after 5 seconds.
+ let _ = self.dispatch_sync(|| {
+ let mtm = MainThreadMarker::new().unwrap();
+
+ unsafe {
+ let alert = NSAlert::new(mtm);
+ alert.setMessageText(&NSString::from_str(title));
+ alert.setInformativeText(&NSString::from_str(message));
+ alert.setAlertStyle(NSAlertStyle::Critical);
+ alert.runModal();
+ };
+ });
+ }
+ }
+}
+
+impl std::fmt::Debug for Dispatcher {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "EventLoopDispatcher")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::{Arc, Mutex};
+
+ use crate::EventLoop;
+
+ #[test]
+ fn dispatch_after_stop_fails() {
+ let (_event_loop, dispatcher) = EventLoop::new().unwrap();
+
+ dispatcher
+ .stop_event_loop()
+ .expect("Failed to stop dispatcher.");
+
+ // Try to dispatch asynchronously - should fail.
+ let result = dispatcher.dispatch_sync(|| {});
+ assert!(matches!(result, Err(crate::Error::EventLoopStopped)));
+
+ // Try dispatch synchronously - should fail.
+ let sync_result: crate::Result<i32> = dispatcher.dispatch_sync(|| 69);
+ assert!(matches!(sync_result, Err(crate::Error::EventLoopStopped)));
+ }
+
+ #[test]
+ fn dispatch_sync_executes_in_order() {
+ const ITERATIONS: usize = 5000;
+
+ let (event_loop, dispatcher) = EventLoop::new().unwrap();
+
+ let order = Arc::new(Mutex::new(Vec::new()));
+ let order_clone = order.clone();
+
+ std::thread::spawn(move || {
+ for index in 1..=ITERATIONS {
+ dispatcher
+ .dispatch_sync(|| {
+ order_clone.lock().unwrap().push(index);
+ })
+ .unwrap();
+ }
+
+ dispatcher.stop_event_loop().unwrap();
+ });
+
+ event_loop.run().unwrap();
+ assert_eq!(
+ *order.lock().unwrap(),
+ (1..=ITERATIONS).collect::<Vec<_>>()
+ );
+ }
+
+ #[test]
+ fn dispatch_sync_from_different_threads() {
+ // Stress test with many threads calling `dispatch_sync`
+ // simultaneously. Ensure that dispatching doesn't deadlock.
+ const NUM_THREADS: usize = 10;
+ const ITERATIONS: usize = 1000;
+
+ let (event_loop, dispatcher) = EventLoop::new().unwrap();
+ let counter = Arc::new(Mutex::new(0));
+
+ let thread_handles: Vec<_> = (0..NUM_THREADS)
+ .map(|_| {
+ let counter = counter.clone();
+ let dispatcher = dispatcher.clone();
+ std::thread::spawn(move || {
+ for _ in 0..ITERATIONS {
+ dispatcher
+ .dispatch_sync(|| {
+ let mut count = counter.lock().unwrap();
+ *count += 1;
+ })
+ .unwrap();
+ }
+ })
+ })
+ .collect();
+
+ std::thread::spawn(move || {
+ // Wait for all threads to finish.
+ for handle in thread_handles {
+ handle.join().unwrap();
+ }
+ dispatcher.stop_event_loop().unwrap();
+ });
+
+ event_loop.run().unwrap();
+
+ assert_eq!(*counter.lock().unwrap(), NUM_THREADS * ITERATIONS);
+ }
+
+ #[test]
+ fn dispatch_sync_with_nested() {
+ // Test that calling `dispatch_sync` from within a `dispatch_sync`
+ // callback works correctly (should execute directly without blocking).
+ let (event_loop, dispatcher) = EventLoop::new().unwrap();
+ let result = Arc::new(Mutex::new(Vec::new()));
+
+ let result_clone = result.clone();
+ std::thread::spawn(move || {
+ dispatcher
+ .dispatch_sync(|| {
+ result_clone.lock().unwrap().push(1);
+
+ // Nested `dispatch_sync` - should execute immediately since it's
+ // already on the event loop thread.
+ dispatcher
+ .dispatch_sync(|| {
+ result_clone.lock().unwrap().push(2);
+ })
+ .unwrap();
+
+ result_clone.lock().unwrap().push(3);
+ })
+ .unwrap();
+
+ dispatcher.stop_event_loop().unwrap();
+ });
+
+ event_loop.run().unwrap();
+ assert_eq!(*result.lock().unwrap(), vec![1, 2, 3]);
+ }
+}
diff --git a/packages/wm-platform/src/display.rs b/packages/wm-platform/src/display.rs
new file mode 100644
index 00000000..979a208c
--- /dev/null
+++ b/packages/wm-platform/src/display.rs
@@ -0,0 +1,326 @@
+#[cfg(target_os = "macos")]
+use objc2::rc::Retained;
+#[cfg(target_os = "macos")]
+use objc2_app_kit::NSScreen;
+#[cfg(target_os = "macos")]
+use objc2_core_graphics::CGDirectDisplayID;
+#[cfg(target_os = "windows")]
+use windows::Win32::Graphics::Gdi::HMONITOR;
+
+#[cfg(target_os = "macos")]
+use crate::ThreadBound;
+use crate::{platform_impl, Rect};
+
+/// Unique identifier for a display.
+///
+/// Can be obtained with `display.id()`.
+///
+/// # Platform-specific
+///
+/// - **Windows**: `isize` (`HMONITOR`)
+/// - **macOS**: `u32` (`CGDirectDisplayID`)
+#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct DisplayId(
+ #[cfg(target_os = "windows")] pub isize,
+ #[cfg(target_os = "macos")] pub u32,
+);
+
+/// Unique identifier for a display device.
+///
+/// Can be obtained with `display_device.id()`.
+///
+/// # Platform-specific
+///
+/// - **Windows**: Hardware ID string with fallback to adapter name.
+/// - **macOS**: UUID string from `CGDisplayCreateUUIDFromDisplayID`.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct DisplayDeviceId(pub String);
+
+/// macOS-specific extension trait for [`Display`].
+#[cfg(target_os = "macos")]
+pub trait DisplayExtMacOs {
+ /// Gets the Core Graphics display ID.
+ fn cg_display_id(&self) -> CGDirectDisplayID;
+
+ /// Gets the `NSScreen` instance for this display.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on macOS.
+ fn ns_screen(&self) -> &ThreadBound<Retained<NSScreen>>;
+}
+
+#[cfg(target_os = "macos")]
+impl DisplayExtMacOs for Display {
+ fn cg_display_id(&self) -> CGDirectDisplayID {
+ self.inner.cg_display_id()
+ }
+
+ fn ns_screen(&self) -> &ThreadBound<Retained<NSScreen>> {
+ self.inner.ns_screen()
+ }
+}
+
+/// Windows-specific extensions for [`Display`].
+#[cfg(target_os = "windows")]
+pub trait DisplayExtWindows {
+ /// Gets the monitor handle.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn hmonitor(&self) -> HMONITOR;
+}
+
+#[cfg(target_os = "windows")]
+impl DisplayExtWindows for Display {
+ fn hmonitor(&self) -> HMONITOR {
+ self.inner.hmonitor()
+ }
+}
+
+/// Represents a logical display space where windows can be placed.
+///
+/// # Platform-specific
+///
+/// - **Windows**: This corresponds to a Win32 "display monitor", each with
+/// a monitor handle (`HMONITOR`).
+/// - **macOS**: This corresponds to an `NSScreen`.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Display {
+ pub(crate) inner: platform_impl::Display,
+}
+
+impl Display {
+ /// Gets the unique identifier for this display.
+ #[must_use]
+ pub fn id(&self) -> DisplayId {
+ self.inner.id()
+ }
+
+ /// Gets the display name.
+ pub fn name(&self) -> crate::Result<String> {
+ self.inner.name()
+ }
+
+ /// Gets the full bounds rectangle of the display.
+ pub fn bounds(&self) -> crate::Result<Rect> {
+ self.inner.bounds()
+ }
+
+ /// Gets the working area rectangle (excluding system UI).
+ pub fn working_area(&self) -> crate::Result<Rect> {
+ self.inner.working_area()
+ }
+
+ /// Gets the scale factor for the display.
+ pub fn scale_factor(&self) -> crate::Result<f32> {
+ self.inner.scale_factor()
+ }
+
+ /// Gets the DPI for the display.
+ pub fn dpi(&self) -> crate::Result<u32> {
+ self.inner.dpi()
+ }
+
+ /// Returns whether this is the primary display.
+ pub fn is_primary(&self) -> crate::Result<bool> {
+ self.inner.is_primary()
+ }
+
+ /// Gets the display devices for this display.
+ ///
+ /// A single display can be associated with multiple display devices. For
+ /// example, when mirroring a display or combining multiple displays
+ /// (e.g. using NVIDIA Surround).
+ pub fn devices(&self) -> crate::Result<Vec<DisplayDevice>> {
+ self.inner.devices()
+ }
+
+ /// Gets the main device (first non-mirroring device) for this display.
+ pub fn main_device(&self) -> crate::Result<DisplayDevice> {
+ self.inner.main_device()
+ }
+}
+
+/// Connection state of a display device.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ConnectionState {
+ /// Device is connected and part of the desktop coordinate space.
+ Active,
+
+ /// Device is connected but inactive (i.e. on standby or in sleep mode).
+ Inactive,
+
+ /// Device is disconnected.
+ Disconnected,
+}
+
+/// Mirroring state of a display device.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum MirroringState {
+ /// This device is the source being mirrored.
+ Source,
+
+ /// This device is mirroring another (target).
+ Target,
+}
+
+/// Display connection type for physical devices.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum OutputTechnology {
+ /// Built-in display (laptop screen).
+ Internal,
+ /// VGA connection.
+ VGA,
+ /// DVI connection.
+ DVI,
+ /// HDMI connection.
+ HDMI,
+ /// DisplayPort connection.
+ DisplayPort,
+ /// Thunderbolt connection.
+ Thunderbolt,
+ /// USB connection.
+ USB,
+ /// Wireless connection.
+ Wireless,
+ /// Unknown connection type.
+ Unknown,
+}
+
+/// macOS-specific extension trait for [`DisplayDevice`].
+#[cfg(target_os = "macos")]
+pub trait DisplayDeviceExtMacOs {
+ /// Gets the Core Graphics display ID.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on macOS.
+ fn cg_display_id(&self) -> CGDirectDisplayID;
+}
+
+#[cfg(target_os = "macos")]
+impl DisplayDeviceExtMacOs for DisplayDevice {
+ fn cg_display_id(&self) -> CGDirectDisplayID {
+ self.inner.cg_display_id()
+ }
+}
+
+/// Windows-specific extensions for [`DisplayDevice`].
+#[cfg(target_os = "windows")]
+pub trait DisplayDeviceExtWindows {
+ /// Gets the device path.
+ ///
+ /// This can be an empty string for virtual display devices.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn device_path(&self) -> Option<String>;
+
+ /// Gets the hardware ID from the device path.
+ ///
+ /// # Example usage
+ ///
+ /// ```rust,no_run
+ /// device.device_path(); // "\\?\DISPLAY#DEL40A3#5&1234abcd&0&UID256#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}"
+ /// device.hardware_id(); // Some("DEL40A3")
+ /// ```
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn hardware_id(&self) -> Option<String>;
+
+ /// Gets the output technology.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn output_technology(&self) -> crate::Result<Option<OutputTechnology>>;
+}
+
+#[cfg(target_os = "windows")]
+impl DisplayDeviceExtWindows for DisplayDevice {
+ fn device_path(&self) -> Option<String> {
+ self.inner.device_path.clone()
+ }
+
+ fn hardware_id(&self) -> Option<String> {
+ self.inner.hardware_id()
+ }
+
+ fn output_technology(&self) -> crate::Result<Option<OutputTechnology>> {
+ self.inner.output_technology()
+ }
+}
+
+/// Represents a display device (physical or virtual).
+///
+/// This is typically a physical display device, such as a monitor or
+/// built-in laptop screen.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct DisplayDevice {
+ pub(crate) inner: platform_impl::DisplayDevice,
+}
+
+impl DisplayDevice {
+ /// Gets the unique identifier for this display device.
+ #[must_use]
+ pub fn id(&self) -> DisplayDeviceId {
+ self.inner.id()
+ }
+
+ /// Gets the rotation of the device in degrees.
+ pub fn rotation(&self) -> crate::Result<f32> {
+ self.inner.rotation()
+ }
+
+ /// Gets the refresh rate of the device in Hz.
+ pub fn refresh_rate(&self) -> crate::Result<f32> {
+ self.inner.refresh_rate()
+ }
+
+ /// Gets whether this is a built-in display.
+ ///
+ /// Returns `true` for embedded displays (like laptop screens).
+ pub fn is_builtin(&self) -> crate::Result<bool> {
+ self.inner.is_builtin()
+ }
+
+ /// Gets the connection state of the device.
+ pub fn connection_state(&self) -> crate::Result<ConnectionState> {
+ self.inner.connection_state()
+ }
+
+ /// Gets the mirroring state of the device.
+ pub fn mirroring_state(&self) -> crate::Result<Option<MirroringState>> {
+ self.inner.mirroring_state()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::EventLoop;
+
+ #[test]
+ fn test_nearest_display() {
+ let (event_loop, dispatcher) = EventLoop::new().unwrap();
+
+ let thread = std::thread::spawn(move || {
+ let display = platform_impl::nearest_display(
+ // Assumes that there is at least one window currently visible.
+ &dispatcher.visible_windows().unwrap()[0],
+ &dispatcher,
+ );
+ dispatcher.stop_event_loop().unwrap();
+ display
+ });
+
+ event_loop.run().unwrap();
+ let display = thread.join().unwrap();
+ assert!(display.is_ok());
+ }
+}
diff --git a/packages/wm-platform/src/display_listener.rs b/packages/wm-platform/src/display_listener.rs
new file mode 100644
index 00000000..1239c542
--- /dev/null
+++ b/packages/wm-platform/src/display_listener.rs
@@ -0,0 +1,35 @@
+use tokio::sync::mpsc;
+
+use crate::{platform_impl, Dispatcher};
+
+/// A listener for system-wide display setting changes.
+///
+/// Detects changes to display configuration including resolution changes,
+/// display connections/disconnections, and working area changes.
+pub struct DisplayListener {
+ event_rx: mpsc::UnboundedReceiver<()>,
+
+ /// Inner platform-specific display listener.
+ inner: platform_impl::DisplayListener,
+}
+
+impl DisplayListener {
+ /// Creates a new [`DisplayListener`].
+ pub fn new(dispatcher: &Dispatcher) -> crate::Result<Self> {
+ let (event_tx, event_rx) = mpsc::unbounded_channel();
+ let inner = platform_impl::DisplayListener::new(event_tx, dispatcher)?;
+ Ok(Self { event_rx, inner })
+ }
+
+ /// Returns when the next display settings change is detected.
+ ///
+ /// Returns `None` if the channel has been closed.
+ pub async fn next_event(&mut self) -> Option<()> {
+ self.event_rx.recv().await
+ }
+
+ /// Terminates the display listener.
+ pub fn terminate(&mut self) -> crate::Result<()> {
+ self.inner.terminate()
+ }
+}
diff --git a/packages/wm-platform/src/error.rs b/packages/wm-platform/src/error.rs
new file mode 100644
index 00000000..6d608f0d
--- /dev/null
+++ b/packages/wm-platform/src/error.rs
@@ -0,0 +1,106 @@
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error(transparent)]
+ Io(#[from] std::io::Error),
+
+ #[error(transparent)]
+ #[cfg(target_os = "windows")]
+ Windows(#[from] windows::core::Error),
+
+ #[error("Accessibility operation failed for attribute {0} with error code: {1}")]
+ #[cfg(target_os = "macos")]
+ Accessibility(String, i32),
+
+ #[error(transparent)]
+ Parse(#[from] ParseError),
+
+ #[error("Invalid pointer: {0}")]
+ InvalidPointer(String),
+
+ #[error("AXValue creation failed: {0}")]
+ #[cfg(target_os = "macos")]
+ AXValueCreation(String),
+
+ #[error(transparent)]
+ ChannelRecv(#[from] std::sync::mpsc::RecvTimeoutError),
+
+ #[error("Channel receive error")]
+ OneshotRecv(#[from] tokio::sync::oneshot::error::RecvError),
+
+ #[error(transparent)]
+ IntConversion(#[from] std::num::TryFromIntError),
+
+ #[error("Channel send error")]
+ ChannelSend,
+
+ #[error("Display enumeration failed")]
+ DisplayEnumerationFailed,
+
+ #[error("Display mode not found")]
+ DisplayModeNotFound,
+
+ #[error("Primary display not found")]
+ PrimaryDisplayNotFound,
+
+ #[error("Not main thread")]
+ NotMainThread,
+
+ #[error("Display not found")]
+ DisplayNotFound,
+
+ #[error("Display device not found")]
+ DisplayDeviceNotFound,
+
+ #[error("Hardware enumeration failed")]
+ HardwareEnumerationFailed,
+
+ #[error("Window enumeration failed")]
+ WindowEnumerationFailed,
+
+ #[error("Window not found")]
+ WindowNotFound,
+
+ #[error("Thread error: {0}")]
+ Thread(String),
+
+ #[error("Window message error: {0}")]
+ WindowMessage(String),
+
+ #[error("Platform error: {0}")]
+ Platform(String),
+
+ #[error("Event loop has been stopped")]
+ EventLoopStopped,
+
+ #[error("Keybinding is empty")]
+ InvalidKeybinding,
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum ParseError {
+ #[error(
+ "Invalid length value '{0}': must be of format '10px' or '10%'."
+ )]
+ Length(String),
+
+ #[error("Invalid keybinding: {0}")]
+ Keybinding(String),
+
+ #[error(
+ "Invalid opacity value '{0}': must be of format '75%' or '0.75'."
+ )]
+ Opacity(String),
+
+ #[error(
+ "Invalid color '{0}': must be of format '#RRGGBB' or '#RRGGBBAA'."
+ )]
+ Color(String),
+
+ #[error("Invalid delta value: {0}")]
+ Delta(String),
+
+ #[error("Invalid direction '{0}': must be one of 'left', 'right', 'up', or 'down'.")]
+ Direction(String),
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
diff --git a/packages/wm-platform/src/event_listener.rs b/packages/wm-platform/src/event_listener.rs
deleted file mode 100644
index dbe01184..00000000
--- a/packages/wm-platform/src/event_listener.rs
+++ /dev/null
@@ -1,88 +0,0 @@
-use tokio::sync::mpsc::{self, UnboundedReceiver};
-use wm_common::{
- BindingModeConfig, InvokeCommand, KeybindingConfig, ParsedConfig, Point,
-};
-
-use super::{EventWindow, NativeWindow};
-
-#[derive(Debug)]
-pub enum PlatformEvent {
- DisplaySettingsChanged,
- KeybindingTriggered(KeybindingConfig),
- MouseMove(MouseMoveEvent),
- WindowDestroyed(NativeWindow),
- WindowFocused(NativeWindow),
- WindowHidden(NativeWindow),
- WindowLocationChanged(NativeWindow),
- WindowMinimized(NativeWindow),
- WindowMinimizeEnded(NativeWindow),
- WindowMovedOrResizedEnd(NativeWindow),
- WindowMovedOrResizedStart(NativeWindow),
- WindowShown(NativeWindow),
- WindowTitleChanged(NativeWindow),
-}
-
-#[derive(Debug, Clone)]
-pub struct MouseMoveEvent {
- /// Location of mouse with 0,0 being the top-left corner of the primary
- /// monitor.
- pub point: Point,
-
- /// Whether either left or right-click is currently pressed.
- pub is_mouse_down: bool,
-}
-
-pub struct EventListener {
- pub event_rx: UnboundedReceiver<PlatformEvent>,
- event_window: EventWindow,
-}
-
-impl EventListener {
- /// Initializes listener for platform events.
- ///
- /// Returns an instance of `EventListener`.
- pub fn start(config: &ParsedConfig) -> anyhow::Result<Self> {
- let (event_tx, event_rx) = mpsc::unbounded_channel();
-
- let event_window = EventWindow::new(
- &event_tx,
- &config.keybindings,
- config.general.focus_follows_cursor,
- )?;
-
- Ok(Self {
- event_rx,
- event_window,
- })
- }
-
- /// Updates the event listener with the latest user config and the
- /// currently active binding modes.
- pub fn update(
- &mut self,
- config: &ParsedConfig,
- binding_modes: &[BindingModeConfig],
- paused: bool,
- ) {
- // Modify keybindings based on active binding modes and paused state.
- let keybindings = if paused {
- &config
- .keybindings
- .iter()
- .filter(|config| {
- config.commands.contains(&InvokeCommand::WmTogglePause)
- })
- .cloned()
- .collect::<Vec<_>>()
- } else {
- match binding_modes.first() {
- Some(binding_mode) => &binding_mode.keybindings,
- None => &config.keybindings,
- }
- };
-
- self
- .event_window
- .update(keybindings, config.general.focus_follows_cursor && !paused);
- }
-}
diff --git a/packages/wm-platform/src/event_loop.rs b/packages/wm-platform/src/event_loop.rs
new file mode 100644
index 00000000..e80f0e56
--- /dev/null
+++ b/packages/wm-platform/src/event_loop.rs
@@ -0,0 +1,70 @@
+use crate::{platform_impl, Dispatcher};
+
+/// A cross-platform event loop that allows for remote dispatching via
+/// [`Dispatcher`].
+///
+/// Does not start pumping events until [`EventLoop::run`] is called.
+///
+/// This type is `!Send` to ensure it stays on the thread where it was
+/// created, as the `Drop` implementation relies on thread-specific
+/// cleanup.
+///
+/// # Platform-specific
+///
+/// - **macOS**: Can be created on any thread. Runs `CFRunLoopRun()`.
+/// - **Windows**: Can be created on any thread. Runs a Win32 message loop.
+pub struct EventLoop {
+ inner: platform_impl::EventLoop,
+ /// Marker to ensure not `Send`.
+ _marker: std::marker::PhantomData<*const ()>,
+}
+
+impl EventLoop {
+ /// Creates a new event loop and dispatcher.
+ pub fn new() -> crate::Result<(Self, Dispatcher)> {
+ let (event_loop, dispatcher) = platform_impl::EventLoop::new()?;
+ Ok((
+ Self {
+ inner: event_loop,
+ _marker: std::marker::PhantomData,
+ },
+ dispatcher,
+ ))
+ }
+
+ /// Runs the event loop, blocking the current thread until shutdown.
+ ///
+ /// # Platform-specific
+ ///
+ /// - **macOS**: Must be called from the main thread. Runs
+ /// `CFRunLoopRun()`.
+ /// - **Windows**: Can be called from any thread. Runs Win32 message
+ /// loop.
+ pub fn run(self) -> crate::Result<()> {
+ self.inner.run()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::time::Duration;
+
+ use super::*;
+
+ #[test]
+ fn event_loop_start_stop() {
+ let (event_loop, dispatcher) =
+ EventLoop::new().expect("Failed to create event loop.");
+
+ // Stop the event loop after a short delay.
+ let handle = std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(10));
+ dispatcher.stop_event_loop()
+ });
+
+ event_loop.run().expect("Failed to run event loop.");
+
+ // Ensure the event loop is stopped.
+ assert!(handle.join().is_ok());
+ }
+}
diff --git a/packages/wm-platform/src/event_window.rs b/packages/wm-platform/src/event_window.rs
deleted file mode 100644
index f10d65fc..00000000
--- a/packages/wm-platform/src/event_window.rs
+++ /dev/null
@@ -1,347 +0,0 @@
-use std::{
- sync::{
- atomic::{AtomicBool, AtomicU64, Ordering},
- Arc, OnceLock,
- },
- thread::{self, JoinHandle},
- time::SystemTime,
-};
-
-use tokio::sync::mpsc;
-use tracing::{info, warn};
-use windows::Win32::{
- Devices::HumanInterfaceDevice::{
- HID_USAGE_GENERIC_MOUSE, HID_USAGE_PAGE_GENERIC,
- },
- Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM},
- UI::{
- Input::{
- GetRawInputData, RegisterRawInputDevices, HRAWINPUT, RAWINPUT,
- RAWINPUTDEVICE, RAWINPUTHEADER, RIDEV_INPUTSINK, RID_INPUT,
- RIM_TYPEMOUSE,
- },
- WindowsAndMessaging::{
- DefWindowProcW, DestroyWindow, GetCursorPos, DBT_DEVNODES_CHANGED,
- PBT_APMRESUMEAUTOMATIC, PBT_APMRESUMESUSPEND, PBT_APMSUSPEND,
- RI_MOUSE_LEFT_BUTTON_DOWN, RI_MOUSE_LEFT_BUTTON_UP,
- RI_MOUSE_RIGHT_BUTTON_DOWN, RI_MOUSE_RIGHT_BUTTON_UP,
- SPI_ICONVERTICALSPACING, SPI_SETWORKAREA, WM_DEVICECHANGE,
- WM_DISPLAYCHANGE, WM_INPUT, WM_POWERBROADCAST, WM_SETTINGCHANGE,
- },
- },
-};
-use wm_common::{KeybindingConfig, Point};
-
-use super::{
- KeyboardHook, MouseMoveEvent, Platform, PlatformEvent, WindowEventHook,
- FOREGROUND_INPUT_IDENTIFIER,
-};
-
-/// Global instance of sender for platform events.
-///
-/// For use with window procedure.
-static PLATFORM_EVENT_TX: OnceLock<mpsc::UnboundedSender<PlatformEvent>> =
- OnceLock::new();
-
-/// Whether mouse hook is currently enabled.
-///
-/// For use with window procedure.
-static ENABLE_MOUSE_EVENTS: AtomicBool = AtomicBool::new(false);
-
-/// Whether the system is currently sleeping/hibernating.
-///
-/// For use with window procedure.
-static IS_SYSTEM_SUSPENDED: AtomicBool = AtomicBool::new(false);
-
-/// Whether left-click is currently pressed.
-///
-/// For use with window procedure.
-static IS_L_MOUSE_DOWN: AtomicBool = AtomicBool::new(false);
-
-/// Whether right-click is currently pressed.
-///
-/// For use with window procedure.
-static IS_R_MOUSE_DOWN: AtomicBool = AtomicBool::new(false);
-
-/// Timestamp of the last mouse event emission.
-///
-/// For use with window procedure.
-static LAST_MOUSE_EVENT_TIME: AtomicU64 = AtomicU64::new(0);
-
-#[derive(Debug)]
-pub struct EventWindow {
- keyboard_hook: Arc<KeyboardHook>,
- window_thread: Option<JoinHandle<anyhow::Result<()>>>,
-}
-
-impl EventWindow {
- /// Creates an instance of `EventWindow`. Spawns a hidden window and
- /// emits platform events.
- ///
- /// Uses global state (e.g. `PLATFORM_EVENT_TX`) and should thus only
- /// ever be instantiated once in the application's lifetime.
- pub fn new(
- event_tx: &mpsc::UnboundedSender<PlatformEvent>,
- keybindings: &Vec<KeybindingConfig>,
- enable_mouse_events: bool,
- ) -> anyhow::Result<Self> {
- let keyboard_hook = KeyboardHook::new(keybindings, event_tx.clone())?;
- let window_event_hook = WindowEventHook::new(event_tx.clone())?;
- let keyboard_hook_clone = keyboard_hook.clone();
-
- // Add the sender for platform events to global state.
- PLATFORM_EVENT_TX.set(event_tx.clone()).map_err(|_| {
- anyhow::anyhow!("Platform event sender already set.")
- })?;
-
- ENABLE_MOUSE_EVENTS.store(enable_mouse_events, Ordering::Relaxed);
-
- let window_thread = thread::spawn(move || {
- // Start hooks for listening to platform events.
- keyboard_hook_clone.start()?;
- window_event_hook.start()?;
-
- // Create a hidden window with a message loop on the current thread.
- let handle =
- Platform::create_message_window(Some(event_window_proc))?;
-
- let rid = RAWINPUTDEVICE {
- usUsagePage: HID_USAGE_PAGE_GENERIC,
- usUsage: HID_USAGE_GENERIC_MOUSE,
- dwFlags: RIDEV_INPUTSINK,
- hwndTarget: HWND(handle),
- };
-
- // Register our window to receive mouse events.
- unsafe {
- #[allow(clippy::cast_possible_truncation)]
- RegisterRawInputDevices(
- &[rid],
- std::mem::size_of::<RAWINPUTDEVICE>() as u32,
- )
- }?;
-
- Platform::run_message_loop();
-
- // Clean-up on message loop exit.
- unsafe { DestroyWindow(HWND(handle)) }?;
- keyboard_hook_clone.stop()?;
- window_event_hook.stop()?;
-
- Ok(())
- });
-
- Ok(Self {
- keyboard_hook,
- window_thread: Some(window_thread),
- })
- }
-
- pub fn update(
- &mut self,
- keybindings: &Vec<KeybindingConfig>,
- enable_mouse_events: bool,
- ) {
- self.keyboard_hook.update(keybindings);
- ENABLE_MOUSE_EVENTS.store(enable_mouse_events, Ordering::Relaxed);
- }
-
- /// Destroys the event window and stops the message loop.
- pub fn destroy(&mut self) -> anyhow::Result<()> {
- info!("Shutting down event window.");
-
- // Wait for the spawned thread to finish.
- if let Some(window_thread) = self.window_thread.take() {
- Platform::kill_message_loop(&window_thread)?;
-
- window_thread
- .join()
- .map_err(|_| anyhow::anyhow!("Thread join failed."))??;
- }
-
- Ok(())
- }
-}
-
-impl Drop for EventWindow {
- fn drop(&mut self) {
- if let Err(err) = self.destroy() {
- warn!("Failed to gracefully shut down event window: {}", err);
- }
- }
-}
-
-/// Window procedure for the event window.
-///
-/// Handles messages for the event window, and forwards display change
-/// events through an MPSC channel for the WM to process.
-pub extern "system" fn event_window_proc(
- handle: HWND,
- message: u32,
- wparam: WPARAM,
- lparam: LPARAM,
-) -> LRESULT {
- if let Some(event_tx) = PLATFORM_EVENT_TX.get() {
- return match message {
- WM_POWERBROADCAST => {
- #[allow(clippy::cast_possible_truncation)]
- match wparam.0 as u32 {
- // System is resuming from sleep/hibernation.
- PBT_APMRESUMEAUTOMATIC | PBT_APMRESUMESUSPEND => {
- IS_SYSTEM_SUSPENDED.store(false, Ordering::Relaxed);
- }
- // System is entering sleep/hibernation.
- PBT_APMSUSPEND => {
- IS_SYSTEM_SUSPENDED.store(true, Ordering::Relaxed);
- }
- _ => {}
- }
-
- LRESULT(0)
- }
- WM_DISPLAYCHANGE | WM_SETTINGCHANGE | WM_DEVICECHANGE => {
- // Ignore display change messages if the system hasn't fully
- // resumed from sleep.
- if !IS_SYSTEM_SUSPENDED.load(Ordering::Relaxed) {
- if let Err(err) =
- handle_display_change_msg(message, wparam, event_tx)
- {
- warn!("Failed to handle display change message: {}", err);
- }
- }
-
- LRESULT(0)
- }
- WM_INPUT if ENABLE_MOUSE_EVENTS.load(Ordering::Relaxed) => {
- if let Err(err) = handle_input_msg(wparam, lparam, event_tx) {
- warn!("Failed to handle input message: {}", err);
- }
-
- LRESULT(0)
- }
- _ => unsafe { DefWindowProcW(handle, message, wparam, lparam) },
- };
- }
-
- LRESULT(0)
-}
-
-/// Handles display change messages and emits the corresponding platform
-/// event through an MPSC channel.
-fn handle_display_change_msg(
- message: u32,
- wparam: WPARAM,
- event_tx: &mpsc::UnboundedSender<PlatformEvent>,
-) -> anyhow::Result<()> {
- #[allow(clippy::cast_possible_truncation)]
- let should_emit_event = match message {
- WM_SETTINGCHANGE => {
- wparam.0 as u32 == SPI_SETWORKAREA.0
- || wparam.0 as u32 == SPI_ICONVERTICALSPACING.0
- }
- WM_DEVICECHANGE => wparam.0 as u32 == DBT_DEVNODES_CHANGED,
- _ => true,
- };
-
- if should_emit_event {
- event_tx.send(PlatformEvent::DisplaySettingsChanged)?;
- }
-
- Ok(())
-}
-
-/// Handles raw input messages for mouse events and emits the corresponding
-/// platform event through an MPSC channel.
-fn handle_input_msg(
- _wparam: WPARAM,
- lparam: LPARAM,
- event_tx: &mpsc::UnboundedSender<PlatformEvent>,
-) -> anyhow::Result<()> {
- let mut raw_input: RAWINPUT = unsafe { std::mem::zeroed() };
- #[allow(clippy::cast_possible_truncation)]
- let mut raw_input_size = std::mem::size_of::<RAWINPUT>() as u32;
-
- let res_size = unsafe {
- #[allow(clippy::cast_possible_truncation)]
- GetRawInputData(
- HRAWINPUT(lparam.0),
- RID_INPUT,
- Some(std::ptr::from_mut(&mut raw_input).cast()),
- &raw mut raw_input_size,
- std::mem::size_of::<RAWINPUTHEADER>() as u32,
- )
- };
-
- // Ignore if data is invalid or not a mouse event. Inputs from our own
- // process are ignored, which would cause issues since
- // `NativeWindow::set_foreground` simulates a mouse input.
- if res_size == 0
- || raw_input_size == u32::MAX
- || raw_input.header.dwType != RIM_TYPEMOUSE.0
- || unsafe { raw_input.data.mouse.ulExtraInformation }
- == FOREGROUND_INPUT_IDENTIFIER
- {
- return Ok(());
- }
-
- let mouse_input = unsafe { raw_input.data.mouse };
- let button_flags =
- unsafe { mouse_input.Anonymous.Anonymous.usButtonFlags };
-
- let has_state_change = match button_flags {
- flags if has_mouse_flag(flags, RI_MOUSE_LEFT_BUTTON_DOWN) => {
- IS_L_MOUSE_DOWN.store(true, Ordering::Relaxed);
- true
- }
- flags if has_mouse_flag(flags, RI_MOUSE_LEFT_BUTTON_UP) => {
- IS_L_MOUSE_DOWN.store(false, Ordering::Relaxed);
- true
- }
- flags if has_mouse_flag(flags, RI_MOUSE_RIGHT_BUTTON_DOWN) => {
- IS_R_MOUSE_DOWN.store(true, Ordering::Relaxed);
- true
- }
- flags if has_mouse_flag(flags, RI_MOUSE_RIGHT_BUTTON_UP) => {
- IS_R_MOUSE_DOWN.store(false, Ordering::Relaxed);
- true
- }
- _ => false,
- };
-
- #[allow(clippy::cast_possible_truncation)]
- let event_time = SystemTime::now()
- .duration_since(SystemTime::UNIX_EPOCH)
- .map(|dur| dur.as_millis() as u64)?;
-
- let last_event_time = LAST_MOUSE_EVENT_TIME.load(Ordering::Relaxed);
-
- // Throttle events so that there's a minimum of 50ms between each
- // emission. Always emit if there's a state change.
- if !has_state_change && event_time - last_event_time < 50 {
- return Ok(());
- }
-
- let is_mouse_down = IS_L_MOUSE_DOWN.load(Ordering::Relaxed)
- || IS_R_MOUSE_DOWN.load(Ordering::Relaxed);
-
- let mut point = POINT { x: 0, y: 0 };
- unsafe { GetCursorPos(&raw mut point) }?;
-
- event_tx.send(PlatformEvent::MouseMove(MouseMoveEvent {
- point: Point {
- x: point.x,
- y: point.y,
- },
- is_mouse_down,
- }))?;
-
- LAST_MOUSE_EVENT_TIME.store(event_time, Ordering::Relaxed);
-
- Ok(())
-}
-
-/// Checks whether `state` contains all the bits of `mask`.
-#[inline]
-fn has_mouse_flag(state: u16, mask: u32) -> bool {
- u32::from(state) & mask == mask
-}
diff --git a/packages/wm-platform/src/keybinding_listener.rs b/packages/wm-platform/src/keybinding_listener.rs
new file mode 100644
index 00000000..4a2bf7c5
--- /dev/null
+++ b/packages/wm-platform/src/keybinding_listener.rs
@@ -0,0 +1,253 @@
+use std::{
+ collections::HashMap,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc, Mutex,
+ },
+};
+
+use tokio::sync::mpsc;
+
+use crate::{
+ platform_event::KeybindingEvent, platform_impl, Dispatcher, Key,
+};
+
+const MODIFIER_KEYS: [Key; 8] = [
+ Key::LShift,
+ Key::RShift,
+ Key::LCtrl,
+ Key::RCtrl,
+ Key::LAlt,
+ Key::RAlt,
+ Key::LCmd,
+ Key::RCmd,
+];
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct Keybinding(Vec<Key>);
+
+impl Keybinding {
+ /// Creates a new keybinding from a vector of keys.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`Error::InvalidKeybinding`] if the keybinding is empty.
+ pub fn new(keys: Vec<Key>) -> crate::Result<Self> {
+ if keys.is_empty() {
+ return Err(crate::Error::InvalidKeybinding);
+ }
+
+ Ok(Self(keys))
+ }
+
+ /// Returns the keys in the keybinding.
+ #[must_use]
+ pub fn keys(&self) -> &[Key] {
+ &self.0
+ }
+
+ /// Returns the trigger key in the keybinding.
+ #[must_use]
+ #[allow(clippy::missing_panics_doc)]
+ pub fn trigger_key(&self) -> &Key {
+ // SAFETY: Keys vector is verified to be non-empty in
+ // `Keybinding::new`.
+ self.0.last().unwrap()
+ }
+}
+
+/// A listener for system-wide keybindings.
+#[derive(Debug)]
+pub struct KeybindingListener {
+ /// A receiver channel for outgoing keybinding events.
+ event_rx: mpsc::UnboundedReceiver<KeybindingEvent>,
+
+ /// A map of keybindings to their trigger key.
+ ///
+ /// The trigger key is the final key in a keybinding. For example,
+ /// in the keybinding `[Key::Cmd, Key::Shift, Key::A]`, `Key::A` is the
+ /// trigger key.
+ keybinding_map: Arc<Mutex<HashMap<Key, Vec<Keybinding>>>>,
+
+ /// Whether the listener is currently enabled.
+ enabled: Arc<AtomicBool>,
+
+ /// The underlying keyboard hook used to listen for key events.
+ keyboard_hook: platform_impl::KeyboardHook,
+}
+
+impl KeybindingListener {
+ /// Creates an instance of `KeybindingListener`.
+ pub fn new(
+ keybindings: &[Keybinding],
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<Self> {
+ let (event_tx, event_rx) = mpsc::unbounded_channel();
+
+ let keybinding_map =
+ Arc::new(Mutex::new(Self::create_keybinding_map(keybindings)));
+
+ let enabled = Arc::new(AtomicBool::new(true));
+
+ let keyboard_hook = Self::create_keyboard_hook(
+ keybinding_map.clone(),
+ enabled.clone(),
+ event_tx,
+ dispatcher,
+ )?;
+
+ Ok(Self {
+ event_rx,
+ keybinding_map,
+ enabled,
+ keyboard_hook,
+ })
+ }
+
+ /// Returns the next keybinding event from the listener.
+ ///
+ /// This will block until a keybinding event is available.
+ pub async fn next_event(&mut self) -> Option<KeybindingEvent> {
+ self.event_rx.recv().await
+ }
+
+ /// Updates the keybindings for the keybinding listener.
+ ///
+ /// # Panics
+ ///
+ /// If the internal mutex is poisoned.
+ pub fn update(&self, keybindings: &[Keybinding]) {
+ *self.keybinding_map.lock().unwrap() =
+ Self::create_keybinding_map(keybindings);
+ }
+
+ /// Enables or disables the keybinding listener.
+ pub fn enable(&mut self, enabled: bool) {
+ self.enabled.store(enabled, Ordering::Relaxed);
+ }
+
+ /// Terminates the keybinding listener.
+ pub fn terminate(&mut self) -> crate::Result<()> {
+ self.keyboard_hook.terminate()
+ }
+
+ /// Creates and starts the keyboard hook with the given callback.
+ fn create_keyboard_hook(
+ keybinding_map: Arc<Mutex<HashMap<Key, Vec<Keybinding>>>>,
+ enabled: Arc<AtomicBool>,
+ event_tx: mpsc::UnboundedSender<KeybindingEvent>,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<platform_impl::KeyboardHook> {
+ platform_impl::KeyboardHook::new(
+ move |event: platform_impl::KeyEvent| -> bool {
+ if !enabled.load(Ordering::Relaxed) || !event.is_keypress {
+ return false;
+ }
+
+ let Ok(keybinding_map) = keybinding_map.lock() else {
+ tracing::error!("Failed to acquire lock on keybinding map.");
+ return false;
+ };
+
+ // Find keybinding candidates whose trigger key is the pressed key.
+ // TODO: This can probably be simplified.
+ if let Some(candidates) = keybinding_map.get(&event.key) {
+ let mut cached_key_states = HashMap::new();
+
+ // Find the matching keybindings based on the pressed keys.
+ let matched_keybindings =
+ candidates.iter().filter(|keybinding| {
+ keybinding.keys().iter().all(|&key| {
+ if key == event.key {
+ return true;
+ }
+
+ if let Some(&is_key_down) = cached_key_states.get(&key) {
+ return is_key_down;
+ }
+
+ let is_key_down = event.is_key_down(key);
+ cached_key_states.insert(key, is_key_down);
+ is_key_down
+ })
+ });
+
+ // Find the longest matching keybinding.
+ let Some(longest_keybinding) = matched_keybindings
+ .max_by_key(|keybinding| keybinding.keys().len())
+ else {
+ return false;
+ };
+
+ // Get the modifier keys to reject based on the longest matching
+ // keybinding.
+ let mut modifier_keys_to_reject =
+ MODIFIER_KEYS.iter().filter(|&&modifier_key| {
+ !longest_keybinding.keys().contains(&modifier_key)
+ && !longest_keybinding
+ .keys()
+ .contains(&Self::generic_modifier_key(modifier_key))
+ });
+
+ // Check if any modifier keys to reject are currently down.
+ let has_modifier_keys_to_reject =
+ modifier_keys_to_reject.any(|&modifier_key| {
+ if let Some(&is_key_down) =
+ cached_key_states.get(&modifier_key)
+ {
+ is_key_down
+ } else {
+ event.is_key_down(modifier_key)
+ }
+ });
+
+ if has_modifier_keys_to_reject {
+ return false;
+ }
+
+ let _ =
+ event_tx.send(KeybindingEvent(longest_keybinding.clone()));
+
+ return true;
+ }
+
+ false
+ },
+ dispatcher,
+ )
+ }
+
+ /// Builds the keybinding map from configs.
+ fn create_keybinding_map(
+ keybindings: &[Keybinding],
+ ) -> HashMap<Key, Vec<Keybinding>> {
+ let mut keybinding_map = HashMap::new();
+
+ for keybinding in keybindings {
+ keybinding_map
+ .entry(*keybinding.trigger_key())
+ .or_insert_with(Vec::new)
+ .push(keybinding.clone());
+ }
+
+ keybinding_map
+ }
+
+ /// Gets the generic modifier key for a given key.
+ fn generic_modifier_key(key: Key) -> Key {
+ match key {
+ Key::LCmd | Key::RCmd => Key::Cmd,
+ Key::LCtrl | Key::RCtrl => Key::Ctrl,
+ Key::LAlt | Key::RAlt => Key::Alt,
+ Key::LShift | Key::RShift => Key::Shift,
+ // TODO: Not ideal, shouldn't panic if used incorrectly.
+ _ => unreachable!(),
+ }
+ }
+}
+
+impl Drop for KeybindingListener {
+ fn drop(&mut self) {
+ let _ = self.terminate();
+ }
+}
diff --git a/packages/wm-platform/src/keyboard_hook.rs b/packages/wm-platform/src/keyboard_hook.rs
deleted file mode 100644
index 32a2c71f..00000000
--- a/packages/wm-platform/src/keyboard_hook.rs
+++ /dev/null
@@ -1,472 +0,0 @@
-use std::{
- collections::HashMap,
- sync::{Arc, Mutex, OnceLock},
-};
-
-use tokio::sync::mpsc;
-use tracing::warn;
-use windows::Win32::{
- Foundation::{LPARAM, LRESULT, WPARAM},
- UI::{
- Input::KeyboardAndMouse::{
- GetKeyState, GetKeyboardLayout, VkKeyScanExW, VIRTUAL_KEY, VK_0,
- VK_1, VK_2, VK_3, VK_4, VK_5, VK_6, VK_7, VK_8, VK_9, VK_A, VK_ADD,
- VK_B, VK_BACK, VK_C, VK_CAPITAL, VK_CONTROL, VK_CONVERT, VK_D,
- VK_DECIMAL, VK_DELETE, VK_DIVIDE, VK_DOWN, VK_E, VK_END, VK_ESCAPE,
- VK_F, VK_F1, VK_F10, VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16,
- VK_F17, VK_F18, VK_F19, VK_F2, VK_F20, VK_F21, VK_F22, VK_F23,
- VK_F24, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_G, VK_H,
- VK_HOME, VK_I, VK_INSERT, VK_J, VK_K, VK_L, VK_LCONTROL, VK_LEFT,
- VK_LMENU, VK_LSHIFT, VK_LWIN, VK_M, VK_MEDIA_NEXT_TRACK,
- VK_MEDIA_PLAY_PAUSE, VK_MEDIA_PREV_TRACK, VK_MEDIA_STOP, VK_MENU,
- VK_MULTIPLY, VK_N, VK_NEXT, VK_NONCONVERT, VK_NUMLOCK, VK_NUMPAD0,
- VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5,
- VK_NUMPAD6, VK_NUMPAD7, VK_NUMPAD8, VK_NUMPAD9, VK_O, VK_OEM_1,
- VK_OEM_2, VK_OEM_3, VK_OEM_4, VK_OEM_5, VK_OEM_6, VK_OEM_7,
- VK_OEM_COMMA, VK_OEM_MINUS, VK_OEM_PERIOD, VK_OEM_PLUS, VK_P,
- VK_PRIOR, VK_Q, VK_R, VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU,
- VK_RSHIFT, VK_RWIN, VK_S, VK_SCROLL, VK_SHIFT, VK_SNAPSHOT,
- VK_SPACE, VK_SUBTRACT, VK_T, VK_TAB, VK_U, VK_UP, VK_V,
- VK_VOLUME_DOWN, VK_VOLUME_MUTE, VK_VOLUME_UP, VK_W, VK_X, VK_Y,
- VK_Z,
- },
- WindowsAndMessaging::{
- CallNextHookEx, SetWindowsHookExW, UnhookWindowsHookEx, HHOOK,
- KBDLLHOOKSTRUCT, WH_KEYBOARD_LL, WM_KEYDOWN, WM_SYSKEYDOWN,
- },
- },
-};
-use wm_common::KeybindingConfig;
-
-use super::PlatformEvent;
-
-/// Global instance of `KeyboardHook`.
-///
-/// For use with hook procedure.
-static KEYBOARD_HOOK: OnceLock<Arc<KeyboardHook>> = OnceLock::new();
-
-/// Available modifier keys.
-const MODIFIER_KEYS: [u16; 6] = [
- VK_LSHIFT.0,
- VK_RSHIFT.0,
- VK_LCONTROL.0,
- VK_RCONTROL.0,
- VK_LMENU.0,
- VK_RMENU.0,
-];
-
-#[derive(Debug)]
-pub struct ActiveKeybinding {
- pub vk_codes: Vec<u16>,
- pub config: KeybindingConfig,
-}
-
-#[derive(Debug)]
-pub struct KeyboardHook {
- /// Sender to emit platform events.
- event_tx: mpsc::UnboundedSender<PlatformEvent>,
-
- /// Handle to the keyboard hook.
- hook: Arc<Mutex<HHOOK>>,
-
- /// Active keybindings grouped by trigger key. The trigger key is the
- /// final key in a key combination.
- keybindings_by_trigger_key:
- Arc<Mutex<HashMap<u16, Vec<ActiveKeybinding>>>>,
-}
-
-impl KeyboardHook {
- /// Creates an instance of `KeyboardHook`.
- pub fn new(
- keybindings: &Vec<KeybindingConfig>,
- event_tx: mpsc::UnboundedSender<PlatformEvent>,
- ) -> anyhow::Result<Arc<Self>> {
- let keyboard_hook = Arc::new(Self {
- event_tx,
- hook: Arc::new(Mutex::new(HHOOK::default())),
- keybindings_by_trigger_key: Arc::new(Mutex::new(
- Self::keybindings_by_trigger_key(keybindings),
- )),
- });
-
- KEYBOARD_HOOK
- .set(keyboard_hook.clone())
- .map_err(|_| anyhow::anyhow!("Keyboard hook already running."))?;
-
- Ok(keyboard_hook)
- }
-
- /// Starts a keyboard hook on the current thread.
- ///
- /// Assumes that a message loop is currently running.
- ///
- /// # Panics
- ///
- /// If the internal mutex is poisoned.
- pub fn start(&self) -> anyhow::Result<()> {
- *self.hook.lock().unwrap() = unsafe {
- SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_hook_proc), None, 0)
- }?;
-
- Ok(())
- }
-
- /// Updates the keybindings for the keyboard hook.
- ///
- /// # Panics
- ///
- /// If the internal mutex is poisoned.
- pub fn update(&self, keybindings: &Vec<KeybindingConfig>) {
- *self.keybindings_by_trigger_key.lock().unwrap() =
- Self::keybindings_by_trigger_key(keybindings);
- }
-
- /// Stops the low-level keyboard hook.
- ///
- /// # Panics
- ///
- /// If the internal mutex is poisoned.
- pub fn stop(&self) -> anyhow::Result<()> {
- unsafe { UnhookWindowsHookEx(*self.hook.lock().unwrap()) }?;
- Ok(())
- }
-
- fn keybindings_by_trigger_key(
- keybindings: &Vec<KeybindingConfig>,
- ) -> HashMap<u16, Vec<ActiveKeybinding>> {
- let mut keybinding_map = HashMap::new();
-
- for keybinding in keybindings {
- for binding in &keybinding.bindings {
- let vk_codes = binding
- .split('+')
- .filter_map(|key| {
- let vk_code = Self::key_to_vk_code(key);
-
- if vk_code.is_none() {
- warn!(
- "Unrecognized key on current keyboard '{}'. Ensure that alt or shift isn't required for the key.",
- key
- );
- }
-
- vk_code
- })
- .collect::<Vec<_>>();
-
- // Safety: A split string always has at least one element.
- let trigger_key = *vk_codes.last().unwrap();
-
- keybinding_map
- .entry(trigger_key)
- .or_insert_with(Vec::new)
- .push(ActiveKeybinding {
- vk_codes,
- config: keybinding.clone(),
- });
- }
- }
-
- keybinding_map
- }
-
- #[allow(clippy::too_many_lines)]
- fn key_to_vk_code(key: &str) -> Option<u16> {
- match key.to_lowercase().as_str() {
- "a" => Some(VK_A.0),
- "b" => Some(VK_B.0),
- "c" => Some(VK_C.0),
- "d" => Some(VK_D.0),
- "e" => Some(VK_E.0),
- "f" => Some(VK_F.0),
- "g" => Some(VK_G.0),
- "h" => Some(VK_H.0),
- "i" => Some(VK_I.0),
- "j" => Some(VK_J.0),
- "k" => Some(VK_K.0),
- "l" => Some(VK_L.0),
- "m" => Some(VK_M.0),
- "n" => Some(VK_N.0),
- "o" => Some(VK_O.0),
- "p" => Some(VK_P.0),
- "q" => Some(VK_Q.0),
- "r" => Some(VK_R.0),
- "s" => Some(VK_S.0),
- "t" => Some(VK_T.0),
- "u" => Some(VK_U.0),
- "v" => Some(VK_V.0),
- "w" => Some(VK_W.0),
- "x" => Some(VK_X.0),
- "y" => Some(VK_Y.0),
- "z" => Some(VK_Z.0),
- "0" | "d0" => Some(VK_0.0),
- "1" | "d1" => Some(VK_1.0),
- "2" | "d2" => Some(VK_2.0),
- "3" | "d3" => Some(VK_3.0),
- "4" | "d4" => Some(VK_4.0),
- "5" | "d5" => Some(VK_5.0),
- "6" | "d6" => Some(VK_6.0),
- "7" | "d7" => Some(VK_7.0),
- "8" | "d8" => Some(VK_8.0),
- "9" | "d9" => Some(VK_9.0),
- "numpad0" => Some(VK_NUMPAD0.0),
- "numpad1" => Some(VK_NUMPAD1.0),
- "numpad2" => Some(VK_NUMPAD2.0),
- "numpad3" => Some(VK_NUMPAD3.0),
- "numpad4" => Some(VK_NUMPAD4.0),
- "numpad5" => Some(VK_NUMPAD5.0),
- "numpad6" => Some(VK_NUMPAD6.0),
- "numpad7" => Some(VK_NUMPAD7.0),
- "numpad8" => Some(VK_NUMPAD8.0),
- "numpad9" => Some(VK_NUMPAD9.0),
- "f1" => Some(VK_F1.0),
- "f2" => Some(VK_F2.0),
- "f3" => Some(VK_F3.0),
- "f4" => Some(VK_F4.0),
- "f5" => Some(VK_F5.0),
- "f6" => Some(VK_F6.0),
- "f7" => Some(VK_F7.0),
- "f8" => Some(VK_F8.0),
- "f9" => Some(VK_F9.0),
- "f10" => Some(VK_F10.0),
- "f11" => Some(VK_F11.0),
- "f12" => Some(VK_F12.0),
- "f13" => Some(VK_F13.0),
- "f14" => Some(VK_F14.0),
- "f15" => Some(VK_F15.0),
- "f16" => Some(VK_F16.0),
- "f17" => Some(VK_F17.0),
- "f18" => Some(VK_F18.0),
- "f19" => Some(VK_F19.0),
- "f20" => Some(VK_F20.0),
- "f21" => Some(VK_F21.0),
- "f22" => Some(VK_F22.0),
- "f23" => Some(VK_F23.0),
- "f24" => Some(VK_F24.0),
- "shift" | "shiftkey" => Some(VK_SHIFT.0),
- "lshift" | "lshiftkey" => Some(VK_LSHIFT.0),
- "rshift" | "rshiftkey" => Some(VK_RSHIFT.0),
- "ctrl" | "controlkey" | "control" => Some(VK_CONTROL.0),
- "lctrl" | "lcontrolkey" => Some(VK_LCONTROL.0),
- "rctrl" | "rcontrolkey" => Some(VK_RCONTROL.0),
- "alt" | "menu" => Some(VK_MENU.0),
- "lalt" | "lmenu" => Some(VK_LMENU.0),
- "ralt" | "rmenu" => Some(VK_RMENU.0),
- "lwin" => Some(VK_LWIN.0),
- "rwin" => Some(VK_RWIN.0),
- "space" => Some(VK_SPACE.0),
- "escape" => Some(VK_ESCAPE.0),
- "back" => Some(VK_BACK.0),
- "tab" => Some(VK_TAB.0),
- "enter" | "return" => Some(VK_RETURN.0),
- "left" => Some(VK_LEFT.0),
- "right" => Some(VK_RIGHT.0),
- "up" => Some(VK_UP.0),
- "down" => Some(VK_DOWN.0),
- "num_lock" => Some(VK_NUMLOCK.0),
- "scroll_lock" => Some(VK_SCROLL.0),
- "caps_lock" => Some(VK_CAPITAL.0),
- "page_up" => Some(VK_PRIOR.0),
- "page_down" => Some(VK_NEXT.0),
- "insert" => Some(VK_INSERT.0),
- "delete" => Some(VK_DELETE.0),
- "end" => Some(VK_END.0),
- "home" => Some(VK_HOME.0),
- "print_screen" => Some(VK_SNAPSHOT.0),
- "multiply" => Some(VK_MULTIPLY.0),
- "add" => Some(VK_ADD.0),
- "subtract" => Some(VK_SUBTRACT.0),
- "decimal" => Some(VK_DECIMAL.0),
- "divide" => Some(VK_DIVIDE.0),
- "volume_up" => Some(VK_VOLUME_UP.0),
- "volume_down" => Some(VK_VOLUME_DOWN.0),
- "volume_mute" => Some(VK_VOLUME_MUTE.0),
- "media_next_track" => Some(VK_MEDIA_NEXT_TRACK.0),
- "media_prev_track" => Some(VK_MEDIA_PREV_TRACK.0),
- "media_stop" => Some(VK_MEDIA_STOP.0),
- "media_play_pause" => Some(VK_MEDIA_PLAY_PAUSE.0),
- "oem_semicolon" => Some(VK_OEM_1.0),
- "oem_question" => Some(VK_OEM_2.0),
- "oem_tilde" => Some(VK_OEM_3.0),
- "oem_open_brackets" => Some(VK_OEM_4.0),
- "oem_pipe" => Some(VK_OEM_5.0),
- "oem_close_brackets" => Some(VK_OEM_6.0),
- "oem_quotes" => Some(VK_OEM_7.0),
- "oem_plus" => Some(VK_OEM_PLUS.0),
- "oem_comma" => Some(VK_OEM_COMMA.0),
- "oem_minus" => Some(VK_OEM_MINUS.0),
- "oem_period" => Some(VK_OEM_PERIOD.0),
- "muhenkan" => Some(VK_NONCONVERT.0),
- "henkan" => Some(VK_CONVERT.0),
- _ => {
- // Check if the key exists on the current keyboard layout.
- let utf16_key = key.encode_utf16().next()?;
- let layout = unsafe { GetKeyboardLayout(0) };
- let vk_code = unsafe { VkKeyScanExW(utf16_key, layout) };
-
- if vk_code == -1 {
- return None;
- }
-
- // The low-order byte contains the virtual-key code and the high-
- // order byte contains the shift state.
- let [high_order, low_order] = vk_code.to_be_bytes();
-
- // Key is valid if it doesn't require shift or alt to be pressed.
- match high_order {
- 0 => Some(u16::from(low_order)),
- _ => None,
- }
- }
- }
- }
-
- /// Emits a platform event if a keybinding should be triggered.
- ///
- /// Returns `true` if the event should be blocked and not sent to other
- /// applications.
- fn handle_key_event(&self, vk_code: u16) -> bool {
- match self
- .keybindings_by_trigger_key
- .lock()
- .unwrap()
- .get(&vk_code)
- {
- // Forward the event if no keybindings exist for the trigger key.
- None => false,
- // Otherwise, check if there is a matching keybinding.
- Some(keybindings) => {
- let mut cached_key_states = HashMap::new();
-
- // Find the matching keybindings based on the pressed keys.
- let matched_keybindings =
- keybindings.iter().filter(|keybinding| {
- keybinding.vk_codes.iter().all(|&key| {
- if key == vk_code {
- return true;
- }
-
- if let Some(&is_key_down) = cached_key_states.get(&key) {
- return is_key_down;
- }
-
- let is_key_down = Self::is_key_down(key);
- cached_key_states.insert(key, is_key_down);
- is_key_down
- })
- });
-
- // Find the longest matching keybinding.
- let longest_keybinding = matched_keybindings
- .max_by_key(|keybinding| keybinding.vk_codes.len());
-
- if longest_keybinding.is_none() {
- return false;
- }
-
- let longest_keybinding = longest_keybinding.unwrap();
-
- // Get the modifier keys to reject based on the longest matching
- // keybinding.
- let mut modifier_keys_to_reject =
- MODIFIER_KEYS.iter().filter(|&&modifier_key| {
- !longest_keybinding.vk_codes.contains(&modifier_key)
- && !longest_keybinding
- .vk_codes
- .contains(&Self::generic_key(modifier_key))
- });
-
- // Check if any modifier keys to reject are currently down.
- let has_modifier_keys_to_reject =
- modifier_keys_to_reject.any(|&modifier_key| {
- if let Some(&is_key_down) =
- cached_key_states.get(&modifier_key)
- {
- is_key_down
- } else {
- Self::is_key_down(modifier_key)
- }
- });
-
- if has_modifier_keys_to_reject {
- return false;
- }
-
- // Invoke the callback function for the longest matching
- // keybinding.
- let _ = self.event_tx.send(PlatformEvent::KeybindingTriggered(
- longest_keybinding.config.clone(),
- ));
-
- true
- }
- }
- }
-
- /// Gets the generic key code for a given key code.
- fn generic_key(key: u16) -> u16 {
- match VIRTUAL_KEY(key) {
- VK_LMENU | VK_RMENU => VK_MENU.0,
- VK_LSHIFT | VK_RSHIFT => VK_SHIFT.0,
- VK_LCONTROL | VK_RCONTROL => VK_CONTROL.0,
- _ => key,
- }
- }
-
- /// Gets whether the specified key is currently down.
- fn is_key_down(key: u16) -> bool {
- match VIRTUAL_KEY(key) {
- VK_MENU => {
- Self::is_key_down_raw(VK_LMENU.0)
- || Self::is_key_down_raw(VK_RMENU.0)
- }
- VK_SHIFT => {
- Self::is_key_down_raw(VK_LSHIFT.0)
- || Self::is_key_down_raw(VK_RSHIFT.0)
- }
- VK_CONTROL => {
- Self::is_key_down_raw(VK_LCONTROL.0)
- || Self::is_key_down_raw(VK_RCONTROL.0)
- }
- _ => Self::is_key_down_raw(key),
- }
- }
-
- /// Gets whether the specified key is currently down using the raw key
- /// code.
- fn is_key_down_raw(key: u16) -> bool {
- unsafe { (GetKeyState(key.into()) & 0x80) == 0x80 }
- }
-}
-
-extern "system" fn keyboard_hook_proc(
- code: i32,
- wparam: WPARAM,
- lparam: LPARAM,
-) -> LRESULT {
- #[allow(clippy::cast_possible_truncation)]
- let should_ignore = code != 0
- || !(wparam.0 as u32 == WM_KEYDOWN
- || wparam.0 as u32 == WM_SYSKEYDOWN);
-
- // If the code is less than zero, the hook procedure must pass the hook
- // notification directly to other applications. We also only care about
- // keydown events.
- if should_ignore {
- return unsafe { CallNextHookEx(None, code, wparam, lparam) };
- }
-
- // Get struct with keyboard input event.
- let input = unsafe { *(lparam.0 as *const KBDLLHOOKSTRUCT) };
-
- if let Some(hook) = KEYBOARD_HOOK.get() {
- #[allow(clippy::cast_possible_truncation)]
- let should_block = hook.handle_key_event(input.vkCode as u16);
-
- if should_block {
- return LRESULT(1);
- }
- }
-
- unsafe { CallNextHookEx(None, code, wparam, lparam) }
-}
diff --git a/packages/wm-platform/src/lib.rs b/packages/wm-platform/src/lib.rs
index 2b807d9e..6f235c4f 100644
--- a/packages/wm-platform/src/lib.rs
+++ b/packages/wm-platform/src/lib.rs
@@ -1,24 +1,40 @@
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]
#![feature(iterator_try_collect)]
-#![feature(once_cell_try)]
-mod com;
-mod event_listener;
-mod event_window;
-mod keyboard_hook;
-mod native_monitor;
+mod dispatcher;
+mod display;
+mod display_listener;
+mod error;
+mod event_loop;
+mod keybinding_listener;
+mod models;
+mod mouse_listener;
mod native_window;
-mod platform;
+mod platform_event;
+mod platform_impl;
mod single_instance;
-mod window_event_hook;
+mod thread_bound;
+mod window_listener;
-pub use com::*;
-pub use event_listener::*;
-pub use event_window::*;
-pub use keyboard_hook::*;
-pub use native_monitor::*;
+pub use dispatcher::*;
+pub use display::*;
+pub use display_listener::*;
+pub use error::*;
+pub use event_loop::*;
+pub use keybinding_listener::*;
+pub use models::*;
+pub use mouse_listener::*;
pub use native_window::*;
-pub use platform::*;
+pub use platform_event::*;
pub use single_instance::*;
-pub use window_event_hook::*;
+pub use thread_bound::*;
+pub use window_listener::*;
+// TODO: Avoid exposing `windows` crate types in the public API.
+#[cfg(target_os = "windows")]
+pub use windows::Win32::UI::WindowsAndMessaging::{
+ SET_WINDOW_POS_FLAGS, SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED,
+ SWP_NOACTIVATE, SWP_NOCOPYBITS, SWP_NOSENDCHANGING, WINDOW_EX_STYLE,
+ WINDOW_STYLE, WS_CAPTION, WS_CHILD, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,
+ WS_MAXIMIZEBOX,
+};
diff --git a/packages/wm-platform/src/mod.rs b/packages/wm-platform/src/mod.rs
deleted file mode 100644
index 8ad4c828..00000000
--- a/packages/wm-platform/src/mod.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-mod com;
-mod event_listener;
-mod event_window;
-mod keyboard_hook;
-mod native_monitor;
-mod native_window;
-mod platform;
-mod single_instance;
-mod window_event_hook;
-
-pub use com::*;
-pub use event_listener::*;
-pub use event_window::*;
-pub use keyboard_hook::*;
-pub use native_monitor::*;
-pub use native_window::*;
-pub use platform::*;
-pub use single_instance::*;
-pub use window_event_hook::*;
diff --git a/packages/wm-common/src/color.rs b/packages/wm-platform/src/models/color.rs
similarity index 57%
rename from packages/wm-common/src/color.rs
rename to packages/wm-platform/src/models/color.rs
index 40568eed..c2b35e83 100644
--- a/packages/wm-common/src/color.rs
+++ b/packages/wm-platform/src/models/color.rs
@@ -1,6 +1,5 @@
use std::str::FromStr;
-use anyhow::bail;
use serde::{Deserialize, Deserializer, Serialize};
#[derive(Debug, Clone, Serialize)]
@@ -12,32 +11,38 @@ pub struct Color {
}
impl Color {
- pub fn to_bgr(&self) -> anyhow::Result<u32> {
+ #[must_use]
+ #[allow(clippy::missing_panics_doc)]
+ pub fn to_bgr(&self) -> u32 {
let bgr = format!("{:02x}{:02x}{:02x}", self.b, self.g, self.r);
- Ok(u32::from_str_radix(&bgr, 16)?)
+ // SAFETY: An invalid hex value is unrepresentable.
+ u32::from_str_radix(&bgr, 16).unwrap()
}
}
impl FromStr for Color {
- type Err = anyhow::Error;
+ type Err = crate::ParseError;
- fn from_str(unparsed: &str) -> anyhow::Result<Self> {
+ fn from_str(unparsed: &str) -> Result<Self, crate::ParseError> {
let mut chars = unparsed.chars();
if chars.next() != Some('#') {
- bail!("Color must start with a `#`.");
+ return Err(crate::ParseError::Color(unparsed.to_string()));
}
- let r = u8::from_str_radix(&unparsed[1..3], 16)?;
- let g = u8::from_str_radix(&unparsed[3..5], 16)?;
- let b = u8::from_str_radix(&unparsed[5..7], 16)?;
+ let parse_hex = |slice: &str| -> Result<u8, crate::ParseError> {
+ u8::from_str_radix(slice, 16)
+ .map_err(|_| crate::ParseError::Color(unparsed.to_string()))
+ };
+
+ let r = parse_hex(&unparsed[1..3])?;
+ let g = parse_hex(&unparsed[3..5])?;
+ let b = parse_hex(&unparsed[5..7])?;
let a = match unparsed.len() {
- 9 => u8::from_str_radix(&unparsed[7..9], 16)?,
+ 9 => parse_hex(&unparsed[7..9])?,
7 => 255,
- _ => bail!(
- "Expected color to be either a 6 or 8 character long hex value."
- ),
+ _ => return Err(crate::ParseError::Color(unparsed.to_string())),
};
Ok(Self { r, g, b, a })
diff --git a/packages/wm-platform/src/models/corner_style.rs b/packages/wm-platform/src/models/corner_style.rs
new file mode 100644
index 00000000..bec6b4ff
--- /dev/null
+++ b/packages/wm-platform/src/models/corner_style.rs
@@ -0,0 +1,16 @@
+use serde::{Deserialize, Serialize};
+
+/// Corner style of a window's frame.
+///
+/// # Platform-specific
+///
+/// Only has an effect on Windows 11.
+#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum CornerStyle {
+ #[default]
+ Default,
+ Square,
+ Rounded,
+ SmallRounded,
+}
diff --git a/packages/wm-common/src/delta.rs b/packages/wm-platform/src/models/delta.rs
similarity index 68%
rename from packages/wm-common/src/delta.rs
rename to packages/wm-platform/src/models/delta.rs
index fe3b4503..e3b148e8 100644
--- a/packages/wm-common/src/delta.rs
+++ b/packages/wm-platform/src/models/delta.rs
@@ -1,6 +1,5 @@
use std::str::FromStr;
-use anyhow::bail;
use serde::Serialize;
/// A wrapper that indicates a value should be interpreted as a delta
@@ -11,21 +10,21 @@ pub struct Delta<T> {
pub is_negative: bool,
}
-impl<T: FromStr<Err = anyhow::Error>> FromStr for Delta<T> {
- type Err = anyhow::Error;
+impl<T: FromStr<Err = crate::ParseError>> FromStr for Delta<T> {
+ type Err = crate::ParseError;
- fn from_str(unparsed: &str) -> anyhow::Result<Self> {
+ fn from_str(unparsed: &str) -> Result<Self, crate::ParseError> {
let unparsed = unparsed.trim();
let (raw, is_negative) = match unparsed.chars().next() {
Some('+') => (&unparsed[1..], false),
Some('-') => (&unparsed[1..], true),
- // No sign means positive.
+ // No sign is interpreted as positive.
_ => (unparsed, false),
};
if raw.is_empty() {
- bail!("Empty value.");
+ return Err(crate::ParseError::Delta(unparsed.to_string()));
}
let inner = T::from_str(raw)?;
diff --git a/packages/wm-common/src/direction.rs b/packages/wm-platform/src/models/direction.rs
similarity index 81%
rename from packages/wm-common/src/direction.rs
rename to packages/wm-platform/src/models/direction.rs
index bfb3b237..35f22779 100644
--- a/packages/wm-common/src/direction.rs
+++ b/packages/wm-platform/src/models/direction.rs
@@ -1,6 +1,5 @@
use std::str::FromStr;
-use anyhow::bail;
use serde::Serialize;
#[derive(Clone, Debug, PartialEq, Serialize)]
@@ -17,7 +16,7 @@ impl Direction {
///
/// Example:
/// ```
- /// # use wm::common::Direction;
+ /// # use wm_platform::Direction;
/// let dir = Direction::Left.inverse();
/// assert_eq!(dir, Direction::Right);
/// ```
@@ -33,24 +32,24 @@ impl Direction {
}
impl FromStr for Direction {
- type Err = anyhow::Error;
+ type Err = crate::ParseError;
/// Parses a string into a direction.
///
/// Example:
/// ```
- /// # use wm::common::Direction;
+ /// # use wm_platform::Direction;
/// # use std::str::FromStr;
/// let dir = Direction::from_str("left");
/// assert_eq!(dir.unwrap(), Direction::Left);
/// ```
- fn from_str(unparsed: &str) -> anyhow::Result<Self> {
+ fn from_str(unparsed: &str) -> Result<Self, crate::ParseError> {
match unparsed {
"left" => Ok(Direction::Left),
"right" => Ok(Direction::Right),
"up" => Ok(Direction::Up),
"down" => Ok(Direction::Down),
- _ => bail!("Not a valid direction: {}", unparsed),
+ _ => Err(crate::ParseError::Direction(unparsed.to_string())),
}
}
}
diff --git a/packages/wm-platform/src/models/key.rs b/packages/wm-platform/src/models/key.rs
new file mode 100644
index 00000000..f42fabb4
--- /dev/null
+++ b/packages/wm-platform/src/models/key.rs
@@ -0,0 +1,442 @@
+use std::{fmt, str::FromStr};
+
+use serde::{Deserialize, Serialize};
+
+/// Platform-specific keyboard key code.
+///
+/// Represents the raw key code from the underlying platform's keyboard
+/// API.
+///
+/// # Platform-specific
+///
+/// - **Windows**: `u16` (Virtual key code from Windows API). See <https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes>
+/// - **macOS**: `i64` (Virtual key code from `CGEvent`). See <https://developer.apple.com/documentation/coregraphics/cgeventfield/keyboardeventkeycode>
+#[derive(
+ Debug,
+ Copy,
+ Clone,
+ PartialEq,
+ Eq,
+ PartialOrd,
+ Ord,
+ Hash,
+ Serialize,
+ Deserialize,
+)]
+pub struct KeyCode(
+ #[cfg(target_os = "windows")] pub(crate) u16,
+ #[cfg(target_os = "macos")] pub(crate) i64,
+);
+
+impl fmt::Display for KeyCode {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.0)
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum KeyParseError {
+ #[error("Unknown key: {0}")]
+ UnknownKey(String),
+}
+
+/// Cross-platform key representation.
+#[allow(clippy::unsafe_derive_deserialize)]
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum Key {
+ // Letter keys
+ A,
+ B,
+ C,
+ D,
+ E,
+ F,
+ G,
+ H,
+ I,
+ J,
+ K,
+ L,
+ M,
+ N,
+ O,
+ P,
+ Q,
+ R,
+ S,
+ T,
+ U,
+ V,
+ W,
+ X,
+ Y,
+ Z,
+
+ // Number keys
+ D0,
+ D1,
+ D2,
+ D3,
+ D4,
+ D5,
+ D6,
+ D7,
+ D8,
+ D9,
+
+ // Function keys
+ F1,
+ F2,
+ F3,
+ F4,
+ F5,
+ F6,
+ F7,
+ F8,
+ F9,
+ F10,
+ F11,
+ F12,
+ F13,
+ F14,
+ F15,
+ F16,
+ F17,
+ F18,
+ F19,
+ F20,
+ F21,
+ F22,
+ F23,
+ F24,
+
+ // Modifier keys
+ Cmd,
+ Ctrl,
+ Alt,
+ Shift,
+ Win,
+ LCmd,
+ RCmd,
+ LCtrl,
+ RCtrl,
+ LAlt,
+ RAlt,
+ LShift,
+ RShift,
+ LWin,
+ RWin,
+
+ // Special keys
+ Space,
+ Tab,
+ Enter,
+ Delete,
+ Escape,
+ Backspace,
+
+ // Arrow keys
+ Left,
+ Right,
+ Up,
+ Down,
+
+ // Navigation keys
+ Home,
+ End,
+ PageUp,
+ PageDown,
+ Insert,
+
+ // Lock keys
+ NumLock,
+ ScrollLock,
+ CapsLock,
+
+ // Numpad
+ Numpad0,
+ Numpad1,
+ Numpad2,
+ Numpad3,
+ Numpad4,
+ Numpad5,
+ Numpad6,
+ Numpad7,
+ Numpad8,
+ Numpad9,
+ NumpadAdd,
+ NumpadSubtract,
+ NumpadMultiply,
+ NumpadDivide,
+ NumpadDecimal,
+
+ // Media keys
+ VolumeUp,
+ VolumeDown,
+ VolumeMute,
+ MediaNextTrack,
+ MediaPrevTrack,
+ MediaStop,
+ MediaPlayPause,
+ PrintScreen,
+
+ // Language-specific keys
+ Muhenkan,
+ Henkan,
+
+ // OEM keys
+ OemSemicolon,
+ OemQuestion,
+ OemTilde,
+ OemOpenBrackets,
+ OemPipe,
+ OemCloseBrackets,
+ OemQuotes,
+ OemPlus,
+ OemComma,
+ OemMinus,
+ OemPeriod,
+}
+
+impl Key {
+ /// Attempts to parse a key from a literal string (e.g. `a`, `;`, `à`).
+ ///
+ /// # Platform-specific
+ ///
+ /// - **macOS**: Not implemented. Returns `KeyParseError::UnknownKey` for
+ /// all keys.
+ ///
+ /// # Errors
+ ///
+ /// Returns `KeyParseError::UnknownKey` if the key is not found on the
+ /// current keyboard layout.
+ pub fn try_from_literal(key_str: &str) -> Result<Self, KeyParseError> {
+ #[cfg(target_os = "macos")]
+ {
+ Err(KeyParseError::UnknownKey(key_str.to_string()))
+ }
+ #[cfg(target_os = "windows")]
+ {
+ use windows::Win32::UI::Input::KeyboardAndMouse::{
+ GetKeyboardLayout, VkKeyScanExW,
+ };
+
+ // Check if the key exists on the current keyboard layout.
+ let utf16_key = key_str
+ .encode_utf16()
+ .next()
+ .ok_or_else(|| KeyParseError::UnknownKey(key_str.to_string()))?;
+
+ let layout = unsafe { GetKeyboardLayout(0) };
+ let vk_code = unsafe { VkKeyScanExW(utf16_key, layout) };
+
+ if vk_code == -1 {
+ return Err(KeyParseError::UnknownKey(key_str.to_string()));
+ }
+
+ // The low-order byte contains the virtual-key code and the high-
+ // order byte contains the shift state.
+ let [high_order, low_order] = vk_code.to_be_bytes();
+
+ // Key is valid if it doesn't require shift or alt to be pressed.
+ match high_order {
+ 0 => Key::try_from(KeyCode(u16::from(low_order)))
+ .map_err(|_| KeyParseError::UnknownKey(key_str.to_string())),
+ _ => Err(KeyParseError::UnknownKey(key_str.to_string())),
+ }
+ }
+ }
+}
+
+/// Generates `FromStr` and `Display` implementations for the `Key` enum.
+///
+/// Each variant can have multiple string aliases, with the first used for
+/// the `Display` implementation.
+///
+/// # Example
+/// ```no_run,compile_fail
+/// impl_key_parsing! {
+/// Enter => ["enter", "return", "cr"],
+/// Space => ["space", "spacebar", " "],
+/// }
+/// ```
+macro_rules! impl_key_parsing {
+ ($( $variant:ident => [$($str_name:literal),+ $(,)?]),* $(,)?) => {
+ impl FromStr for Key {
+ type Err = KeyParseError;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s {
+ $($($str_name)|+ => Ok(Key::$variant),)*
+ _ => Err(KeyParseError::UnknownKey(s.to_string())),
+ }
+ }
+ }
+
+ impl fmt::Display for Key {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ $(Key::$variant => {
+ // Return the first string alias as the display name.
+ let aliases = &[$($str_name),+];
+ write!(f, "{}", aliases[0])
+ },)*
+ }
+ }
+ }
+
+ impl Key {
+ /// Returns all string aliases for this key variant.
+ pub fn all_aliases(&self) -> Option<&'static [&'static str]> {
+ match self {
+ $(Key::$variant => Some(&[$($str_name),+]),)*
+ }
+ }
+ }
+ };
+}
+
+impl_key_parsing! {
+ // Letter keys
+ A => ["a"], B => ["b"], C => ["c"], D => ["d"], E => ["e"], F => ["f"],
+ G => ["g"], H => ["h"], I => ["i"], J => ["j"], K => ["k"], L => ["l"],
+ M => ["m"], N => ["n"], O => ["o"], P => ["p"], Q => ["q"], R => ["r"],
+ S => ["s"], T => ["t"], U => ["u"], V => ["v"], W => ["w"], X => ["x"],
+ Y => ["y"], Z => ["z"],
+
+ // Number keys
+ D0 => ["0", "d0"],
+ D1 => ["1", "d1"],
+ D2 => ["2", "d2"],
+ D3 => ["3", "d3"],
+ D4 => ["4", "d4"],
+ D5 => ["5", "d5"],
+ D6 => ["6", "d6"],
+ D7 => ["7", "d7"],
+ D8 => ["8", "d8"],
+ D9 => ["9", "d9"],
+
+ // Function keys
+ F1 => ["f1"], F2 => ["f2"], F3 => ["f3"], F4 => ["f4"], F5 => ["f5"],
+ F6 => ["f6"], F7 => ["f7"], F8 => ["f8"], F9 => ["f9"], F10 => ["f10"],
+ F11 => ["f11"], F12 => ["f12"], F13 => ["f13"], F14 => ["f14"],
+ F15 => ["f15"], F16 => ["f16"], F17 => ["f17"], F18 => ["f18"],
+ F19 => ["f19"], F20 => ["f20"], F21 => ["f21"], F22 => ["f22"],
+ F23 => ["f23"], F24 => ["f24"],
+
+ // Modifier keys
+ Cmd => ["cmd"],
+ Ctrl => ["ctrl", "control"],
+ Alt => ["alt", "menu"],
+ Shift => ["shift"],
+ Win => ["win"],
+ LCmd => ["lcmd"],
+ RCmd => ["rcmd"],
+ LCtrl => ["lctrl"],
+ RCtrl => ["rctrl"],
+ LAlt => ["lalt", "lmenu"],
+ RAlt => ["ralt", "rmenu"],
+ LShift => ["lshift"],
+ RShift => ["rshift"],
+ LWin => ["lwin"],
+ RWin => ["rwin"],
+
+ // Special keys
+ Space => ["space"],
+ Tab => ["tab"],
+ Enter => ["enter", "return"],
+ Delete => ["delete"],
+ Escape => ["escape"],
+ Backspace => ["backspace"],
+
+ // Arrow keys
+ Left => ["left"],
+ Right => ["right"],
+ Up => ["up"],
+ Down => ["down"],
+
+ // Navigation keys
+ Home => ["home"],
+ End => ["end"],
+ PageUp => ["page_up"],
+ PageDown => ["page_down"],
+ Insert => ["insert"],
+
+ // Lock keys
+ NumLock => ["num_lock"],
+ ScrollLock => ["scroll_lock"],
+ CapsLock => ["caps_lock"],
+
+ // Numpad
+ Numpad0 => ["numpad0"],
+ Numpad1 => ["numpad1"],
+ Numpad2 => ["numpad2"],
+ Numpad3 => ["numpad3"],
+ Numpad4 => ["numpad4"],
+ Numpad5 => ["numpad5"],
+ Numpad6 => ["numpad6"],
+ Numpad7 => ["numpad7"],
+ Numpad8 => ["numpad8"],
+ Numpad9 => ["numpad9"],
+ NumpadAdd => ["numpad_add", "add"],
+ NumpadSubtract => ["numpad_subtract", "subtract"],
+ NumpadMultiply => ["numpad_multiply", "multiply"],
+ NumpadDivide => ["numpad_divide", "divide"],
+ NumpadDecimal => ["numpad_decimal", "decimal"],
+
+ // Media keys
+ VolumeUp => ["volume_up"],
+ VolumeDown => ["volume_down"],
+ VolumeMute => ["volume_mute"],
+ MediaNextTrack => ["media_next_track"],
+ MediaPrevTrack => ["media_prev_track"],
+ MediaStop => ["media_stop"],
+ MediaPlayPause => ["media_play_pause"],
+ PrintScreen => ["print_screen"],
+
+ // OEM keys
+ OemSemicolon => ["oem_semicolon"],
+ OemQuestion => ["oem_question"],
+ OemTilde => ["oem_tilde"],
+ OemOpenBrackets => ["oem_open_brackets"],
+ OemPipe => ["oem_pipe"],
+ OemCloseBrackets => ["oem_close_brackets"],
+ OemQuotes => ["oem_quotes"],
+ OemPlus => ["oem_plus"],
+ OemComma => ["oem_comma"],
+ OemMinus => ["oem_minus"],
+ OemPeriod => ["oem_period"],
+
+ // Language-specific keys
+ Muhenkan => ["muhenkan"],
+ Henkan => ["henkan"],
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_key_parsing() {
+ assert_eq!("a".parse::<Key>().unwrap(), Key::A);
+ assert_eq!("cmd".parse::<Key>().unwrap(), Key::Cmd);
+ assert_eq!("f1".parse::<Key>().unwrap(), Key::F1);
+ assert_eq!("space".parse::<Key>().unwrap(), Key::Space);
+ assert_eq!("enter".parse::<Key>().unwrap(), Key::Enter);
+ assert_eq!("return".parse::<Key>().unwrap(), Key::Enter);
+
+ // Should fail for unknown keys.
+ assert!("invalid".parse::<Key>().is_err());
+ }
+
+ #[test]
+ fn test_key_display() {
+ assert_eq!(Key::A.to_string(), "a");
+ assert_eq!(Key::Cmd.to_string(), "cmd");
+ assert_eq!(Key::F1.to_string(), "f1");
+ assert_eq!(Key::Space.to_string(), "space");
+ }
+}
diff --git a/packages/wm-platform/src/models/key_code.rs b/packages/wm-platform/src/models/key_code.rs
new file mode 100644
index 00000000..46ad047d
--- /dev/null
+++ b/packages/wm-platform/src/models/key_code.rs
@@ -0,0 +1,278 @@
+#[cfg(target_os = "windows")]
+use windows::Win32::UI::Input::KeyboardAndMouse::{
+ VIRTUAL_KEY, VK_0, VK_1, VK_2, VK_3, VK_4, VK_5, VK_6, VK_7, VK_8, VK_9,
+ VK_A, VK_ADD, VK_B, VK_BACK, VK_C, VK_CAPITAL, VK_CONVERT, VK_D,
+ VK_DECIMAL, VK_DELETE, VK_DIVIDE, VK_DOWN, VK_E, VK_END, VK_ESCAPE,
+ VK_F, VK_F1, VK_F10, VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16,
+ VK_F17, VK_F18, VK_F19, VK_F2, VK_F20, VK_F21, VK_F22, VK_F23, VK_F24,
+ VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_G, VK_H, VK_HOME,
+ VK_I, VK_INSERT, VK_J, VK_K, VK_L, VK_LCONTROL, VK_LEFT, VK_LMENU,
+ VK_LSHIFT, VK_LWIN, VK_M, VK_MEDIA_NEXT_TRACK, VK_MEDIA_PLAY_PAUSE,
+ VK_MEDIA_PREV_TRACK, VK_MEDIA_STOP, VK_MULTIPLY, VK_N, VK_NEXT,
+ VK_NONCONVERT, VK_NUMLOCK, VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2,
+ VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, VK_NUMPAD8,
+ VK_NUMPAD9, VK_O, VK_OEM_1, VK_OEM_2, VK_OEM_3, VK_OEM_4, VK_OEM_5,
+ VK_OEM_6, VK_OEM_7, VK_OEM_COMMA, VK_OEM_MINUS, VK_OEM_PERIOD,
+ VK_OEM_PLUS, VK_P, VK_PRIOR, VK_Q, VK_R, VK_RCONTROL, VK_RETURN,
+ VK_RIGHT, VK_RMENU, VK_RSHIFT, VK_RWIN, VK_S, VK_SCROLL, VK_SNAPSHOT,
+ VK_SPACE, VK_SUBTRACT, VK_T, VK_TAB, VK_U, VK_UP, VK_V, VK_VOLUME_DOWN,
+ VK_VOLUME_MUTE, VK_VOLUME_UP, VK_W, VK_X, VK_Y, VK_Z,
+};
+
+use crate::{Key, KeyCode};
+
+#[derive(Debug, thiserror::Error)]
+pub enum KeyConversionError {
+ #[error("Unknown key code: {0}")]
+ UnknownKeyCode(KeyCode),
+}
+
+/// Generates `TryFrom` implementations for converting between `Key` and
+/// `KeyCode`.
+///
+/// For Windows, the key code is assumed to be a `VK_*` constant (accessed
+/// via .0).
+///
+/// # Example
+/// ```no_run,compile_fail
+/// impl_key_code_conversion! {
+/// Enter => { windows: VK_RETURN, macos: 0x24, },
+/// Space => { windows: VK_SPACE, macos: 0x31, },
+/// PrintScreen => { windows: VK_SNAPSHOT, }, // Only supported on Windows.
+/// }
+/// ```
+macro_rules! impl_key_code_conversion {
+ (
+ $(
+ $variant:ident => {
+ $(windows: $win_code:expr,)?
+ $(macos: $mac_code:expr,)?
+ }
+ ),* $(,)?
+ ) => {
+ #[cfg(target_os = "windows")]
+ impl TryFrom<KeyCode> for Key {
+ type Error = KeyConversionError;
+
+ fn try_from(key_code: KeyCode) -> Result<Self, Self::Error> {
+ let vk = VIRTUAL_KEY(key_code.0);
+ $($(if vk == $win_code { return Ok(Key::$variant); })?)*
+ Err(KeyConversionError::UnknownKeyCode(key_code))
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ impl TryFrom<KeyCode> for Key {
+ type Error = KeyConversionError;
+
+ fn try_from(key_code: KeyCode) -> Result<Self, Self::Error> {
+ $($(if key_code.0 == $mac_code { return Ok(Key::$variant); })?)*
+ Err(KeyConversionError::UnknownKeyCode(key_code))
+ }
+ }
+
+ impl TryFrom<Key> for KeyCode {
+ type Error = KeyConversionError;
+
+ fn try_from(key: Key) -> Result<Self, Self::Error> {
+ match key {
+ $(Key::$variant => {
+ #[cfg(target_os = "windows")]
+ {
+ $(return Ok(KeyCode($win_code.0));)?
+ #[allow(unreachable_code)]
+ return Err(KeyConversionError::UnknownKeyCode(KeyCode(0)));
+ }
+ #[cfg(target_os = "macos")]
+ {
+ $(return Ok(KeyCode($mac_code));)?
+ #[allow(unreachable_code)]
+ return Err(KeyConversionError::UnknownKeyCode(KeyCode(0)));
+ }
+ }),*
+ }
+ }
+ }
+ };
+}
+
+impl_key_code_conversion! {
+ // Letter keys
+ A => { windows: VK_A, macos: 0x00, },
+ B => { windows: VK_B, macos: 0x0B, },
+ C => { windows: VK_C, macos: 0x08, },
+ D => { windows: VK_D, macos: 0x02, },
+ E => { windows: VK_E, macos: 0x0E, },
+ F => { windows: VK_F, macos: 0x03, },
+ G => { windows: VK_G, macos: 0x05, },
+ H => { windows: VK_H, macos: 0x04, },
+ I => { windows: VK_I, macos: 0x22, },
+ J => { windows: VK_J, macos: 0x26, },
+ K => { windows: VK_K, macos: 0x28, },
+ L => { windows: VK_L, macos: 0x25, },
+ M => { windows: VK_M, macos: 0x2E, },
+ N => { windows: VK_N, macos: 0x2D, },
+ O => { windows: VK_O, macos: 0x1F, },
+ P => { windows: VK_P, macos: 0x23, },
+ Q => { windows: VK_Q, macos: 0x0C, },
+ R => { windows: VK_R, macos: 0x0F, },
+ S => { windows: VK_S, macos: 0x01, },
+ T => { windows: VK_T, macos: 0x11, },
+ U => { windows: VK_U, macos: 0x20, },
+ V => { windows: VK_V, macos: 0x09, },
+ W => { windows: VK_W, macos: 0x0D, },
+ X => { windows: VK_X, macos: 0x07, },
+ Y => { windows: VK_Y, macos: 0x10, },
+ Z => { windows: VK_Z, macos: 0x06, },
+ // Number keys
+ D0 => { windows: VK_0, macos: 0x1D, },
+ D1 => { windows: VK_1, macos: 0x12, },
+ D2 => { windows: VK_2, macos: 0x13, },
+ D3 => { windows: VK_3, macos: 0x14, },
+ D4 => { windows: VK_4, macos: 0x15, },
+ D5 => { windows: VK_5, macos: 0x17, },
+ D6 => { windows: VK_6, macos: 0x16, },
+ D7 => { windows: VK_7, macos: 0x1A, },
+ D8 => { windows: VK_8, macos: 0x1C, },
+ D9 => { windows: VK_9, macos: 0x19, },
+ // Function keys
+ F1 => { windows: VK_F1, macos: 0x7A, },
+ F2 => { windows: VK_F2, macos: 0x78, },
+ F3 => { windows: VK_F3, macos: 0x63, },
+ F4 => { windows: VK_F4, macos: 0x76, },
+ F5 => { windows: VK_F5, macos: 0x60, },
+ F6 => { windows: VK_F6, macos: 0x61, },
+ F7 => { windows: VK_F7, macos: 0x62, },
+ F8 => { windows: VK_F8, macos: 0x64, },
+ F9 => { windows: VK_F9, macos: 0x65, },
+ F10 => { windows: VK_F10, macos: 0x6D, },
+ F11 => { windows: VK_F11, macos: 0x67, },
+ F12 => { windows: VK_F12, macos: 0x6F, },
+ F13 => { windows: VK_F13, macos: 0x69, },
+ F14 => { windows: VK_F14, macos: 0x6B, },
+ F15 => { windows: VK_F15, macos: 0x71, },
+ F16 => { windows: VK_F16, macos: 0x6A, },
+ F17 => { windows: VK_F17, macos: 0x40, },
+ F18 => { windows: VK_F18, macos: 0x4F, },
+ F19 => { windows: VK_F19, macos: 0x50, },
+ F20 => { windows: VK_F20, macos: 0x5A, },
+ // Windows-only function keys; macOS has no F21-F24.
+ F21 => { windows: VK_F21, },
+ F22 => { windows: VK_F22, },
+ F23 => { windows: VK_F23, },
+ F24 => { windows: VK_F24, },
+ // Modifier keys - use platform-specific primary variants
+ LShift => { windows: VK_LSHIFT, macos: 0x38, },
+ RShift => { windows: VK_RSHIFT, macos: 0x3C, },
+ LCtrl => { windows: VK_LCONTROL, macos: 0x3B, },
+ RCtrl => { windows: VK_RCONTROL, macos: 0x3E, },
+ LAlt => { windows: VK_LMENU, macos: 0x3A, },
+ RAlt => { windows: VK_RMENU, macos: 0x3D, },
+ // General modifiers (canonical mapping)
+ Shift => { windows: VK_LSHIFT, macos: 0x38, },
+ Ctrl => { windows: VK_LCONTROL, macos: 0x3B, },
+ Alt => { windows: VK_LMENU, macos: 0x3A, },
+ Cmd => { windows: VK_LWIN, macos: 0x37, },
+ Win => { windows: VK_LWIN, macos: 0x37, },
+ // Platform-specific key mappings (aliases)
+ LWin => { windows: VK_LWIN, macos: 0x37, },
+ RWin => { windows: VK_RWIN, macos: 0x36, },
+ LCmd => { windows: VK_LWIN, macos: 0x37, },
+ RCmd => { windows: VK_RWIN, macos: 0x36, },
+ // Special keys
+ Space => { windows: VK_SPACE, macos: 0x31, },
+ Tab => { windows: VK_TAB, macos: 0x30, },
+ Enter => { windows: VK_RETURN, macos: 0x24, },
+ // macOS: Backspace == 0x33, Forward Delete == 0x75
+ Delete => { windows: VK_DELETE, macos: 0x75, },
+ Escape => { windows: VK_ESCAPE, macos: 0x35, },
+ Backspace => { windows: VK_BACK, macos: 0x33, },
+ // Arrow keys
+ Left => { windows: VK_LEFT, macos: 0x7B, },
+ Right => { windows: VK_RIGHT, macos: 0x7C, },
+ Up => { windows: VK_UP, macos: 0x7E, },
+ Down => { windows: VK_DOWN, macos: 0x7D, },
+ // Navigation keys
+ Home => { windows: VK_HOME, macos: 0x73, },
+ End => { windows: VK_END, macos: 0x77, },
+ PageUp => { windows: VK_PRIOR, macos: 0x74, },
+ PageDown => { windows: VK_NEXT, macos: 0x79, },
+ Insert => { windows: VK_INSERT, macos: 0x72, }, // Note: macOS 0x72 is Help
+ // OEM keys
+ OemSemicolon => { windows: VK_OEM_1, macos: 0x29, },
+ OemQuestion => { windows: VK_OEM_2, macos: 0x2C, },
+ OemTilde => { windows: VK_OEM_3, macos: 0x32, },
+ OemOpenBrackets => { windows: VK_OEM_4, macos: 0x21, },
+ OemPipe => { windows: VK_OEM_5, macos: 0x2A, },
+ OemCloseBrackets => { windows: VK_OEM_6, macos: 0x1E, },
+ OemQuotes => { windows: VK_OEM_7, macos: 0x27, },
+ OemPlus => { windows: VK_OEM_PLUS, macos: 0x18, },
+ OemComma => { windows: VK_OEM_COMMA, macos: 0x2B, },
+ OemMinus => { windows: VK_OEM_MINUS, macos: 0x1B, },
+ OemPeriod => { windows: VK_OEM_PERIOD, macos: 0x2F, },
+ // Numpad
+ Numpad0 => { windows: VK_NUMPAD0, macos: 0x52, },
+ Numpad1 => { windows: VK_NUMPAD1, macos: 0x53, },
+ Numpad2 => { windows: VK_NUMPAD2, macos: 0x54, },
+ Numpad3 => { windows: VK_NUMPAD3, macos: 0x55, },
+ Numpad4 => { windows: VK_NUMPAD4, macos: 0x56, },
+ Numpad5 => { windows: VK_NUMPAD5, macos: 0x57, },
+ Numpad6 => { windows: VK_NUMPAD6, macos: 0x58, },
+ Numpad7 => { windows: VK_NUMPAD7, macos: 0x59, },
+ Numpad8 => { windows: VK_NUMPAD8, macos: 0x5B, },
+ Numpad9 => { windows: VK_NUMPAD9, macos: 0x5C, },
+ NumpadAdd => { windows: VK_ADD, macos: 0x45, },
+ NumpadSubtract => { windows: VK_SUBTRACT, macos: 0x4E, },
+ NumpadMultiply => { windows: VK_MULTIPLY, macos: 0x43, },
+ NumpadDivide => { windows: VK_DIVIDE, macos: 0x4B, },
+ NumpadDecimal => { windows: VK_DECIMAL, macos: 0x41, },
+ // Lock keys
+ NumLock => { windows: VK_NUMLOCK, macos: 0x47, },
+ ScrollLock => { windows: VK_SCROLL, macos: 0x6B, },
+ CapsLock => { windows: VK_CAPITAL, macos: 0x39, },
+ // Media keys
+ VolumeUp => { windows: VK_VOLUME_UP, macos: 0x48, },
+ VolumeDown => { windows: VK_VOLUME_DOWN, macos: 0x49, },
+ VolumeMute => { windows: VK_VOLUME_MUTE, macos: 0x4A, },
+ // TODO: Verify these media keys for macOS.
+ MediaNextTrack => { windows: VK_MEDIA_NEXT_TRACK, macos: 0x42, },
+ MediaPrevTrack => { windows: VK_MEDIA_PREV_TRACK, macos: 0x4D, },
+ MediaStop => { windows: VK_MEDIA_STOP, macos: 0x4C, },
+ MediaPlayPause => { windows: VK_MEDIA_PLAY_PAUSE, macos: 0x34, },
+ PrintScreen => { windows: VK_SNAPSHOT, },
+ // Language-specific keys
+ Muhenkan => { windows: VK_NONCONVERT, },
+ Henkan => { windows: VK_CONVERT, },
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_key_conversion_roundtrip() {
+ let test_keys = [
+ Key::A,
+ Key::S,
+ Key::D,
+ Key::F,
+ Key::Cmd,
+ Key::LAlt,
+ Key::RCtrl,
+ Key::LShift,
+ Key::Space,
+ Key::Tab,
+ Key::Enter,
+ Key::F1,
+ Key::F12,
+ Key::Left,
+ Key::Right,
+ ];
+
+ for key in test_keys {
+ let code: KeyCode = key.try_into().unwrap();
+ let key2: Key = code.try_into().unwrap();
+ assert_eq!(key, key2, "Roundtrip failed for key: {key:?}");
+ }
+ }
+}
diff --git a/packages/wm-common/src/length_value.rs b/packages/wm-platform/src/models/length_value.rs
similarity index 76%
rename from packages/wm-common/src/length_value.rs
rename to packages/wm-platform/src/models/length_value.rs
index c1b0782a..5a95cf64 100644
--- a/packages/wm-common/src/length_value.rs
+++ b/packages/wm-platform/src/models/length_value.rs
@@ -1,6 +1,5 @@
use std::str::FromStr;
-use anyhow::{bail, Context};
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize};
@@ -49,14 +48,14 @@ impl LengthValue {
}
impl FromStr for LengthValue {
- type Err = anyhow::Error;
+ type Err = crate::ParseError;
/// Parses a string containing a number followed by a unit (`px`, `%`).
/// Allows for negative numbers.
///
/// Example:
/// ```
- /// # use wm::common::{LengthValue, LengthUnit};
+ /// # use wm_platform::{LengthValue, LengthUnit};
/// # use std::str::FromStr;
/// let check = LengthValue {
/// amount: 100.0,
@@ -65,32 +64,32 @@ impl FromStr for LengthValue {
/// let parsed = LengthValue::from_str("100px");
/// assert_eq!(parsed.unwrap(), check);
/// ```
- fn from_str(unparsed: &str) -> anyhow::Result<Self> {
- let units_regex = Regex::new(r"([+-]?\d+)(%|px)?")?;
+ fn from_str(unparsed: &str) -> Result<Self, crate::ParseError> {
+ let units_regex =
+ Regex::new(r"([+-]?\d+)(%|px)?").expect("Invalid regex.");
- let err_msg = format!(
- "Not a valid length value '{unparsed}'. Must be of format '10px' or '10%'."
- );
+ let captures = units_regex
+ .captures(unparsed)
+ .ok_or(crate::ParseError::Length(unparsed.to_string()))?;
- let captures =
- units_regex.captures(unparsed).context(err_msg.clone())?;
-
- let unit_str = captures.get(2).map_or("", |m| m.as_str());
- let unit = match unit_str {
+ let unit = match captures.get(2).map_or("", |m| m.as_str()) {
"px" | "" => LengthUnit::Pixel,
"%" => LengthUnit::Percentage,
- _ => bail!(err_msg),
+ _ => return Err(crate::ParseError::Length(unparsed.to_string())),
};
let amount = captures
.get(1)
- .and_then(|amount_str| f32::from_str(amount_str.into()).ok())
+ .and_then(|m| m.as_str().parse::<f32>().ok())
// Store percentage units as a fraction of 1.
- .map(|amount| match unit {
- LengthUnit::Pixel => amount,
- LengthUnit::Percentage => amount / 100.0,
+ .map(|amount| {
+ if unit == LengthUnit::Percentage {
+ amount / 100.0
+ } else {
+ amount
+ }
})
- .context(err_msg.clone())?;
+ .ok_or(crate::ParseError::Length(unparsed.to_string()))?;
Ok(LengthValue { amount, unit })
}
diff --git a/packages/wm-platform/src/models/mod.rs b/packages/wm-platform/src/models/mod.rs
new file mode 100644
index 00000000..e4609365
--- /dev/null
+++ b/packages/wm-platform/src/models/mod.rs
@@ -0,0 +1,23 @@
+mod color;
+mod corner_style;
+mod delta;
+mod direction;
+mod key;
+mod key_code;
+mod length_value;
+mod opacity_value;
+mod point;
+mod rect;
+mod rect_delta;
+
+pub use color::*;
+pub use corner_style::*;
+pub use delta::*;
+pub use direction::*;
+pub use key::*;
+pub use key_code::*;
+pub use length_value::*;
+pub use opacity_value::*;
+pub use point::*;
+pub use rect::*;
+pub use rect_delta::*;
diff --git a/packages/wm-common/src/opacity_value.rs b/packages/wm-platform/src/models/opacity_value.rs
similarity index 84%
rename from packages/wm-common/src/opacity_value.rs
rename to packages/wm-platform/src/models/opacity_value.rs
index dd7ebdb0..1091aa52 100644
--- a/packages/wm-common/src/opacity_value.rs
+++ b/packages/wm-platform/src/models/opacity_value.rs
@@ -1,10 +1,9 @@
use std::str::FromStr;
-use anyhow::Context;
use serde::{Deserialize, Deserializer, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize)]
-pub struct OpacityValue(f32);
+pub struct OpacityValue(pub f32);
impl OpacityValue {
#[must_use]
@@ -27,34 +26,34 @@ impl Default for OpacityValue {
}
impl FromStr for OpacityValue {
- type Err = anyhow::Error;
+ type Err = crate::ParseError;
/// Parses a string for an opacity value. The string must be a percentage
/// or a decimal number.
///
/// Example:
/// ```
- /// # use wm::common::{OpacityValue};
+ /// # use wm_platform::{OpacityValue};
/// # use std::str::FromStr;
/// let check = OpacityValue(0.75);
/// let parsed = OpacityValue::from_str("75%");
/// assert_eq!(parsed.unwrap(), check);
/// ```
- fn from_str(unparsed: &str) -> anyhow::Result<Self> {
+ fn from_str(unparsed: &str) -> Result<Self, crate::ParseError> {
let unparsed = unparsed.trim();
if unparsed.ends_with('%') {
let percentage = unparsed
.trim_end_matches('%')
.parse::<f32>()
- .context("Invalid percentage format.")?;
+ .map_err(|_| crate::ParseError::Opacity(unparsed.to_string()))?;
Ok(Self(percentage / 100.0))
} else {
unparsed
.parse::<f32>()
.map(Self)
- .context("Invalid decimal format.")
+ .map_err(|_| crate::ParseError::Opacity(unparsed.to_string()))
}
}
}
diff --git a/packages/wm-platform/src/models/point.rs b/packages/wm-platform/src/models/point.rs
new file mode 100644
index 00000000..892d71ce
--- /dev/null
+++ b/packages/wm-platform/src/models/point.rs
@@ -0,0 +1,19 @@
+/// Represents an x-y coordinate.
+#[derive(Debug, Clone)]
+pub struct Point {
+ pub x: i32,
+ pub y: i32,
+}
+
+impl Point {
+ /// Calculates the Euclidean distance between this point and another
+ /// point.
+ #[must_use]
+ pub fn distance_between(&self, other: &Point) -> f32 {
+ let dx = self.x - other.x;
+ let dy = self.y - other.y;
+
+ #[allow(clippy::cast_precision_loss)]
+ ((dx * dx + dy * dy) as f32).sqrt()
+ }
+}
diff --git a/packages/wm-common/src/rect.rs b/packages/wm-platform/src/models/rect.rs
similarity index 57%
rename from packages/wm-common/src/rect.rs
rename to packages/wm-platform/src/models/rect.rs
index 66308391..4e5e2ecd 100644
--- a/packages/wm-common/src/rect.rs
+++ b/packages/wm-platform/src/models/rect.rs
@@ -1,6 +1,14 @@
use serde::{Deserialize, Serialize};
-use super::{Direction, LengthValue, Point, RectDelta};
+use crate::{Direction, LengthValue, Point, RectDelta};
+
+#[derive(Debug, Deserialize, Clone, Serialize, Eq, PartialEq)]
+pub enum Corner {
+ TopLeft,
+ TopRight,
+ BottomLeft,
+ BottomRight,
+}
#[derive(Debug, Deserialize, Clone, Serialize, Eq, PartialEq)]
pub struct Rect {
@@ -127,6 +135,28 @@ impl Rect {
}
}
+ #[must_use]
+ pub fn corner(&self, corner: &Corner) -> Point {
+ match corner {
+ Corner::TopLeft => Point {
+ x: self.left,
+ y: self.top,
+ },
+ Corner::TopRight => Point {
+ x: self.right,
+ y: self.top,
+ },
+ Corner::BottomLeft => Point {
+ x: self.left,
+ y: self.bottom,
+ },
+ Corner::BottomRight => Point {
+ x: self.right,
+ y: self.bottom,
+ },
+ }
+ }
+
/// Gets the delta between this rect and another rect.
#[must_use]
pub fn delta(&self, other: &Rect) -> RectDelta {
@@ -152,34 +182,29 @@ impl Rect {
)
}
+ // Gets the amount of overlap between the x-coordinates of the two rects.
#[must_use]
- pub fn apply_inverse_delta(
- &self,
- delta: &RectDelta,
- scale_factor: Option<f32>,
- ) -> Self {
- Self::from_ltrb(
- self.left + delta.left.to_px(self.width(), scale_factor),
- self.top + delta.top.to_px(self.height(), scale_factor),
- self.right - delta.right.to_px(self.width(), scale_factor),
- self.bottom - delta.bottom.to_px(self.height(), scale_factor),
- )
+ pub fn x_overlap(&self, other: &Rect) -> i32 {
+ self.right.min(other.right) - self.x().max(other.x())
}
- // Gets whether the x-coordinate overlaps with the x-coordinate of the
- // other rect.
+ // Gets the amount of overlap between the y-coordinates of the two rects.
#[must_use]
- pub fn has_overlap_x(&self, other: &Rect) -> bool {
- !(self.x() + self.width() <= other.x()
- || other.x() + other.width() <= self.x())
+ pub fn y_overlap(&self, other: &Rect) -> i32 {
+ self.bottom.min(other.bottom) - self.y().max(other.y())
}
- // Gets whether the y-coordinate overlaps with the y-coordinate of the
- // other rect.
+ /// Gets the intersection area of this rect and another rect.
#[must_use]
- pub fn has_overlap_y(&self, other: &Rect) -> bool {
- !(self.y() + self.height() <= other.y()
- || other.y() + other.height() <= self.y())
+ pub fn intersection_area(&self, other: &Rect) -> i32 {
+ let x_overlap = self.x_overlap(other);
+ let y_overlap = self.y_overlap(other);
+
+ if x_overlap > 0 && y_overlap > 0 {
+ x_overlap * y_overlap
+ } else {
+ 0
+ }
}
#[must_use]
@@ -189,6 +214,30 @@ impl Rect {
is_in_x && is_in_y
}
+ /// Gets whether this rect fully encloses another rect.
+ #[must_use]
+ pub fn contains_rect(&self, other: &Rect) -> bool {
+ self.left <= other.left
+ && self.top <= other.top
+ && self.right >= other.right
+ && self.bottom >= other.bottom
+ }
+
+ /// Creates a new rect that is inset by the given amount of pixels on all
+ /// sides.
+ ///
+ /// The `inset_px` can be a positive number to create a smaller rect
+ /// (inset), or a negative number to create a larger rect (outset).
+ #[must_use]
+ pub fn inset(&self, inset_px: i32) -> Self {
+ Self::from_ltrb(
+ self.left + inset_px,
+ self.top + inset_px,
+ self.right - inset_px,
+ self.bottom - inset_px,
+ )
+ }
+
#[must_use]
pub fn distance_to_point(&self, point: &Point) -> f32 {
let dx = (self.x() - point.x)
@@ -202,4 +251,46 @@ impl Rect {
#[allow(clippy::cast_precision_loss)]
((dx * dx + dy * dy) as f32).sqrt()
}
+
+ /// Returns the union of this rect and another rect.
+ ///
+ /// The union is the smallest rect that contains both rects, taking the
+ /// minimum left/top and maximum right/bottom coordinates.
+ #[must_use]
+ pub fn union(&self, other: &Rect) -> Self {
+ Self::from_ltrb(
+ self.left.min(other.left),
+ self.top.min(other.top),
+ self.right.max(other.right),
+ self.bottom.max(other.bottom),
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn intersection_area() {
+ // Full overlap.
+ let r1 = Rect::from_xy(0, 0, 100, 100);
+ let r2 = Rect::from_xy(0, 0, 100, 100);
+ assert_eq!(r1.intersection_area(&r2), 10000); // 100 * 100
+
+ // Partial overlap.
+ let r1 = Rect::from_xy(0, 0, 100, 100);
+ let r2 = Rect::from_xy(50, 50, 100, 100);
+ assert_eq!(r1.intersection_area(&r2), 2500); // 50 * 50
+
+ // No overlap.
+ let r1 = Rect::from_xy(0, 0, 100, 100);
+ let r2 = Rect::from_xy(200, 200, 100, 100);
+ assert_eq!(r1.intersection_area(&r2), 0);
+
+ // No overlap (edges touching).
+ let r1 = Rect::from_xy(0, 0, 100, 100);
+ let r2 = Rect::from_xy(100, 0, 100, 100);
+ assert_eq!(r1.intersection_area(&r2), 0);
+ }
}
diff --git a/packages/wm-common/src/rect_delta.rs b/packages/wm-platform/src/models/rect_delta.rs
similarity index 54%
rename from packages/wm-common/src/rect_delta.rs
rename to packages/wm-platform/src/models/rect_delta.rs
index 4eeb5a67..ea277ba0 100644
--- a/packages/wm-common/src/rect_delta.rs
+++ b/packages/wm-platform/src/models/rect_delta.rs
@@ -42,4 +42,40 @@ impl RectDelta {
|| self.left.amount > 1.0
|| self.right.amount > 1.0
}
+
+ /// Creates a new `RectDelta` with all sides set to 0px.
+ #[must_use]
+ pub fn zero() -> Self {
+ Self::new(
+ LengthValue::from_px(0),
+ LengthValue::from_px(0),
+ LengthValue::from_px(0),
+ LengthValue::from_px(0),
+ )
+ }
+
+ /// Gets the inverse of this delta by negating all values.
+ ///
+ /// Returns a new `RectDelta` instance.
+ #[must_use]
+ pub fn inverse(&self) -> Self {
+ RectDelta::new(
+ LengthValue {
+ amount: -self.left.amount,
+ unit: self.left.unit.clone(),
+ },
+ LengthValue {
+ amount: -self.top.amount,
+ unit: self.top.unit.clone(),
+ },
+ LengthValue {
+ amount: -self.right.amount,
+ unit: self.right.unit.clone(),
+ },
+ LengthValue {
+ amount: -self.bottom.amount,
+ unit: self.bottom.unit.clone(),
+ },
+ )
+ }
}
diff --git a/packages/wm-platform/src/mouse_listener.rs b/packages/wm-platform/src/mouse_listener.rs
new file mode 100644
index 00000000..08071c50
--- /dev/null
+++ b/packages/wm-platform/src/mouse_listener.rs
@@ -0,0 +1,64 @@
+use tokio::sync::mpsc;
+
+use crate::{platform_event::MouseEvent, platform_impl, Dispatcher};
+
+/// Available mouse events that [`MouseListener`] can listen for.
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
+pub enum MouseEventKind {
+ Move,
+ LeftButtonDown,
+ LeftButtonUp,
+ RightButtonDown,
+ RightButtonUp,
+}
+
+/// A listener for system-wide mouse events.
+pub struct MouseListener {
+ /// Receiver for outgoing mouse events.
+ event_rx: mpsc::UnboundedReceiver<MouseEvent>,
+
+ /// Inner platform-specific mouse listener.
+ inner: platform_impl::MouseListener,
+}
+
+impl MouseListener {
+ /// Creates a new [`MouseListener`] with the specified enabled events.
+ pub fn new(
+ enabled_events: &[MouseEventKind],
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<Self> {
+ let (event_tx, event_rx) = mpsc::unbounded_channel();
+ let inner = platform_impl::MouseListener::new(
+ enabled_events,
+ event_tx,
+ dispatcher,
+ )?;
+
+ Ok(Self { event_rx, inner })
+ }
+
+ /// Returns the next mouse event from the listener.
+ ///
+ /// This will block until a mouse event is available.
+ pub async fn next_event(&mut self) -> Option<MouseEvent> {
+ self.event_rx.recv().await
+ }
+
+ /// Enables or disables the underlying mouse listener.
+ pub fn enable(&mut self, enabled: bool) -> crate::Result<()> {
+ self.inner.enable(enabled)
+ }
+
+ /// Updates the set of enabled mouse events to listen for.
+ pub fn set_enabled_events(
+ &mut self,
+ enabled_events: &[MouseEventKind],
+ ) -> crate::Result<()> {
+ self.inner.set_enabled_events(enabled_events)
+ }
+
+ /// Terminates the mouse listener.
+ pub fn terminate(&mut self) -> crate::Result<()> {
+ self.inner.terminate()
+ }
+}
diff --git a/packages/wm-platform/src/native_monitor.rs b/packages/wm-platform/src/native_monitor.rs
deleted file mode 100644
index ca0dbdb4..00000000
--- a/packages/wm-platform/src/native_monitor.rs
+++ /dev/null
@@ -1,241 +0,0 @@
-use std::cell::OnceCell;
-
-use windows::{
- core::PCWSTR,
- Win32::{
- Foundation::{BOOL, HWND, LPARAM, RECT},
- Graphics::Gdi::{
- EnumDisplayDevicesW, EnumDisplayMonitors, GetMonitorInfoW,
- MonitorFromWindow, DISPLAY_DEVICEW, DISPLAY_DEVICE_ACTIVE, HDC,
- HMONITOR, MONITORINFO, MONITORINFOEXW, MONITOR_DEFAULTTONEAREST,
- },
- UI::{
- HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI},
- WindowsAndMessaging::EDD_GET_DEVICE_INTERFACE_NAME,
- },
- },
-};
-use wm_common::Rect;
-
-#[derive(Clone, Debug)]
-pub struct NativeMonitor {
- pub handle: isize,
- info: OnceCell<MonitorInfo>,
-}
-
-#[derive(Clone, Debug)]
-struct MonitorInfo {
- device_name: String,
- device_path: Option<String>,
- hardware_id: Option<String>,
- rect: Rect,
- working_rect: Rect,
- dpi: u32,
- scale_factor: f32,
-}
-
-impl NativeMonitor {
- #[must_use]
- pub fn new(handle: isize) -> Self {
- Self {
- handle,
- info: OnceCell::new(),
- }
- }
-
- pub fn device_name(&self) -> anyhow::Result<&String> {
- self.monitor_info().map(|info| &info.device_name)
- }
-
- pub fn device_path(&self) -> anyhow::Result<Option<&String>> {
- self.monitor_info().map(|info| info.device_path.as_ref())
- }
-
- pub fn hardware_id(&self) -> anyhow::Result<Option<&String>> {
- self.monitor_info().map(|info| info.hardware_id.as_ref())
- }
-
- pub fn rect(&self) -> anyhow::Result<&Rect> {
- self.monitor_info().map(|info| &info.rect)
- }
-
- pub fn working_rect(&self) -> anyhow::Result<&Rect> {
- self.monitor_info().map(|info| &info.working_rect)
- }
-
- pub fn dpi(&self) -> anyhow::Result<u32> {
- self.monitor_info().map(|info| info.dpi)
- }
-
- pub fn scale_factor(&self) -> anyhow::Result<f32> {
- self.monitor_info().map(|info| info.scale_factor)
- }
-
- fn monitor_info(&self) -> anyhow::Result<&MonitorInfo> {
- self.info.get_or_try_init(|| {
- let mut monitor_info = MONITORINFOEXW {
- monitorInfo: MONITORINFO {
- #[allow(clippy::cast_possible_truncation)]
- cbSize: std::mem::size_of::<MONITORINFOEXW>() as u32,
- ..Default::default()
- },
- ..Default::default()
- };
-
- unsafe {
- GetMonitorInfoW(
- HMONITOR(self.handle),
- std::ptr::from_mut(&mut monitor_info).cast(),
- )
- }
- .ok()?;
-
- // Get the display devices associated with the monitor.
- let mut display_devices = (0..)
- .map_while(|index| {
- #[allow(clippy::cast_possible_truncation)]
- let mut display_device = DISPLAY_DEVICEW {
- cb: std::mem::size_of::<DISPLAY_DEVICEW>() as u32,
- ..Default::default()
- };
-
- // Due to the `EDD_GET_DEVICE_INTERFACE_NAME` flag, the device
- // struct will contain the DOS device path under the `DeviceId`
- // field.
- unsafe {
- EnumDisplayDevicesW(
- PCWSTR(monitor_info.szDevice.as_ptr()),
- index,
- &raw mut display_device,
- EDD_GET_DEVICE_INTERFACE_NAME,
- )
- }
- .as_bool()
- .then_some(display_device)
- })
- // Filter out any devices that are not active.
- .filter(|device| device.StateFlags & DISPLAY_DEVICE_ACTIVE != 0);
-
- // Get the device path and hardware ID from the first valid device.
- let (device_path, hardware_id) =
- display_devices.next().map_or((None, None), |device| {
- let device_path = String::from_utf16_lossy(&device.DeviceID)
- .trim_end_matches('\0')
- .to_string();
-
- let hardware_id = device_path
- .split('#')
- .collect::<Vec<_>>()
- .get(1)
- .map(|id| (*id).to_string());
-
- (Some(device_path), hardware_id)
- });
-
- let device_name = String::from_utf16_lossy(&monitor_info.szDevice);
- let dpi = monitor_dpi(self.handle)?;
- #[allow(clippy::cast_precision_loss)]
- let scale_factor = dpi as f32 / 96.0;
-
- let rc_monitor = monitor_info.monitorInfo.rcMonitor;
- let rect = Rect::from_ltrb(
- rc_monitor.left,
- rc_monitor.top,
- rc_monitor.right,
- rc_monitor.bottom,
- );
-
- let rc_work = monitor_info.monitorInfo.rcWork;
- let working_rect = Rect::from_ltrb(
- rc_work.left,
- rc_work.top,
- rc_work.right,
- rc_work.bottom,
- );
-
- Ok(MonitorInfo {
- device_name,
- device_path,
- hardware_id,
- rect,
- working_rect,
- dpi,
- scale_factor,
- })
- })
- }
-}
-
-impl PartialEq for NativeMonitor {
- fn eq(&self, other: &Self) -> bool {
- self.handle == other.handle
- }
-}
-
-impl Eq for NativeMonitor {}
-
-/// Gets all available monitors.
-pub fn available_monitors() -> anyhow::Result<Vec<NativeMonitor>> {
- Ok(
- available_monitor_handles()?
- .into_iter()
- .map(NativeMonitor::new)
- .collect(),
- )
-}
-
-/// Gets all available monitor handles.
-fn available_monitor_handles() -> anyhow::Result<Vec<isize>> {
- let mut monitors: Vec<isize> = Vec::new();
-
- unsafe {
- EnumDisplayMonitors(
- HDC::default(),
- None,
- Some(available_monitor_handles_proc),
- LPARAM(std::ptr::from_mut(&mut monitors) as _),
- )
- }
- .ok()?;
-
- Ok(monitors)
-}
-
-/// Callback passed to `EnumDisplayMonitors` to get all available monitor
-/// handles.
-extern "system" fn available_monitor_handles_proc(
- handle: HMONITOR,
- _hdc: HDC,
- _clip: *mut RECT,
- data: LPARAM,
-) -> BOOL {
- let handles = data.0 as *mut Vec<isize>;
- unsafe { (*handles).push(handle.0) };
- true.into()
-}
-
-#[must_use]
-pub fn nearest_monitor(window_handle: isize) -> NativeMonitor {
- let handle = unsafe {
- MonitorFromWindow(HWND(window_handle), MONITOR_DEFAULTTONEAREST)
- };
-
- NativeMonitor::new(handle.0)
-}
-
-fn monitor_dpi(handle: isize) -> anyhow::Result<u32> {
- let mut dpi_x = u32::default();
- let mut dpi_y = u32::default();
-
- unsafe {
- GetDpiForMonitor(
- HMONITOR(handle),
- MDT_EFFECTIVE_DPI,
- &raw mut dpi_x,
- &raw mut dpi_y,
- )
- }?;
-
- // Arbitrarily choose the Y DPI.
- Ok(dpi_y)
-}
diff --git a/packages/wm-platform/src/native_window.rs b/packages/wm-platform/src/native_window.rs
index 464eb8ed..7f916a20 100644
--- a/packages/wm-platform/src/native_window.rs
+++ b/packages/wm-platform/src/native_window.rs
@@ -1,954 +1,568 @@
-use std::time::Duration;
-
-use anyhow::{bail, Context};
-use tokio::task;
-use tracing::warn;
-use windows::{
- core::PWSTR,
- Win32::{
- Foundation::{CloseHandle, BOOL, HWND, LPARAM, RECT},
- Graphics::Dwm::{
- DwmGetWindowAttribute, DwmSetWindowAttribute, DWMWA_BORDER_COLOR,
- DWMWA_CLOAKED, DWMWA_COLOR_NONE, DWMWA_EXTENDED_FRAME_BOUNDS,
- DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_DEFAULT, DWMWCP_DONOTROUND,
- DWMWCP_ROUND, DWMWCP_ROUNDSMALL,
- },
- System::Threading::{
- OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32,
- PROCESS_QUERY_LIMITED_INFORMATION,
- },
- UI::{
- Input::KeyboardAndMouse::{
- SendInput, INPUT, INPUT_0, INPUT_MOUSE, MOUSEINPUT,
- },
- WindowsAndMessaging::{
- EnumWindows, GetClassNameW, GetLayeredWindowAttributes, GetWindow,
- GetWindowLongPtrW, GetWindowRect, GetWindowTextW,
- GetWindowThreadProcessId, IsIconic, IsWindow, IsWindowVisible, IsZoomed,
- SendNotifyMessageW, SetForegroundWindow,
- SetLayeredWindowAttributes, SetWindowLongPtrW, SetWindowPlacement,
- SetWindowPos, ShowWindowAsync, GWL_EXSTYLE, GWL_STYLE, GW_OWNER,
- HWND_NOTOPMOST, HWND_TOP, HWND_TOPMOST,
- LAYERED_WINDOW_ATTRIBUTES_FLAGS, LWA_ALPHA, LWA_COLORKEY,
- SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED, SWP_NOACTIVATE,
- SWP_NOCOPYBITS, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSENDCHANGING,
- SWP_NOSIZE, SWP_NOZORDER, SWP_SHOWWINDOW, SW_HIDE, SW_MAXIMIZE,
- SW_MINIMIZE, SW_RESTORE, SW_SHOWNA, WINDOWPLACEMENT,
- WINDOW_EX_STYLE, WINDOW_STYLE, WM_CLOSE, WPF_ASYNCWINDOWPLACEMENT,
- WS_CAPTION, WS_CHILD, WS_DLGFRAME, WS_EX_LAYERED,
- WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_MAXIMIZEBOX, WS_THICKFRAME,
- },
- },
+#[cfg(target_os = "macos")]
+use objc2_application_services::AXUIElement;
+#[cfg(target_os = "macos")]
+use objc2_core_foundation::{CFBoolean, CFRetained, CFString};
+#[cfg(target_os = "windows")]
+use windows::Win32::{
+ Foundation::HWND,
+ UI::WindowsAndMessaging::{
+ SET_WINDOW_POS_FLAGS, WINDOW_EX_STYLE, WINDOW_STYLE,
},
};
-use wm_common::{
- Color, CornerStyle, Delta, HideMethod, LengthValue, Memo, OpacityValue,
- Rect, RectDelta, WindowState,
-};
-use super::COM_INIT;
+use crate::{platform_impl, Rect};
+#[cfg(target_os = "macos")]
+use crate::{platform_impl::AXUIElementExt, ThreadBound};
+#[cfg(target_os = "windows")]
+use crate::{Color, CornerStyle, Delta, OpacityValue, RectDelta};
+
+/// Unique identifier of a window.
+///
+/// Can be obtained with `window.id()`.
+///
+/// # Platform-specific
+///
+/// - **Windows**: `isize` (`HWND`)
+/// - **macOS**: `u32` (`CGWindowID`)
+#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct WindowId(
+ #[cfg(target_os = "windows")] pub isize,
+ #[cfg(target_os = "macos")] pub u32,
+);
+
+impl WindowId {
+ #[cfg(target_os = "macos")]
+ pub(crate) fn from_window_element(el: &CFRetained<AXUIElement>) -> Self {
+ let mut window_id = 0;
-/// Magic number used to identify programmatic mouse inputs from our own
-/// process.
-pub const FOREGROUND_INPUT_IDENTIFIER: u32 = 6379;
+ unsafe {
+ platform_impl::ffi::_AXUIElementGetWindow(
+ CFRetained::as_ptr(el),
+ &raw mut window_id,
+ )
+ };
+
+ Self(window_id)
+ }
+}
-#[derive(Clone, Debug, PartialEq)]
-pub enum ZOrder {
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum WindowZOrder {
Normal,
- AfterWindow(isize),
+ AfterWindow(WindowId),
Top,
TopMost,
}
-#[derive(Clone, Debug)]
-pub struct NativeWindow {
- pub handle: isize,
- title: Memo<String>,
- process_name: Memo<String>,
- class_name: Memo<String>,
- frame_position: Memo<Rect>,
- border_position: Memo<Rect>,
- is_minimized: Memo<bool>,
- is_maximized: Memo<bool>,
-}
+/// macOS-specific extension trait for [`NativeWindow`].
+#[cfg(target_os = "macos")]
+pub trait NativeWindowExtMacOs {
+ /// Gets the `AXUIElement` instance for this window.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on macOS.
+ fn ax_ui_element(&self) -> &ThreadBound<CFRetained<AXUIElement>>;
-impl NativeWindow {
- /// Creates a new `NativeWindow` instance with the given window handle.
- #[must_use]
- pub fn new(handle: isize) -> Self {
- Self {
- handle,
- title: Memo::new(),
- process_name: Memo::new(),
- class_name: Memo::new(),
- frame_position: Memo::new(),
- border_position: Memo::new(),
- is_minimized: Memo::new(),
- is_maximized: Memo::new(),
- }
- }
+ /// Gets the bundle ID of the application that owns the window.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on macOS.
+ fn bundle_id(&self) -> Option<String>;
+
+ /// Gets the role of the window (e.g. `AXWindow`).
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on macOS.
+ fn role(&self) -> crate::Result<String>;
+
+ /// Gets the sub-role of the window (e.g. `AXStandardWindow`).
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on macOS.
+ fn subrole(&self) -> crate::Result<String>;
- /// Gets the window's title. If the window is invalid, returns an empty
- /// string.
+ /// Whether the window is modal.
///
- /// This value is lazily retrieved and cached after first retrieval.
- pub fn title(&self) -> anyhow::Result<String> {
- self.title.get_or_init(Self::updated_title, self)
+ /// # Platform-specific
+ ///
+ /// This method is only available on macOS.
+ fn is_modal(&self) -> crate::Result<bool>;
+
+ /// Whether the window is the main window for its application.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on macOS.
+ fn is_main(&self) -> crate::Result<bool>;
+}
+
+#[cfg(target_os = "macos")]
+impl NativeWindowExtMacOs for NativeWindow {
+ fn ax_ui_element(&self) -> &ThreadBound<CFRetained<AXUIElement>> {
+ &self.inner.element
}
- /// Updates the cached window title.
- pub fn refresh_title(&self) -> anyhow::Result<String> {
- self.title.update(Self::updated_title, self)
+ fn bundle_id(&self) -> Option<String> {
+ self.inner.application.bundle_id()
}
- /// Gets the window's title. If the window is invalid, returns an empty
- /// string.
- #[allow(clippy::unnecessary_wraps)]
- fn updated_title(&self) -> anyhow::Result<String> {
- let mut text: [u16; 512] = [0; 512];
- let length = unsafe { GetWindowTextW(HWND(self.handle), &mut text) };
+ fn role(&self) -> crate::Result<String> {
+ self.inner.element.with(|el| {
+ el.get_attribute::<CFString>("AXRole")
+ .map(|cf_string| cf_string.to_string())
+ })?
+ }
- #[allow(clippy::cast_sign_loss)]
- Ok(String::from_utf16_lossy(&text[..length as usize]))
+ fn subrole(&self) -> crate::Result<String> {
+ self.inner.element.with(|el| {
+ el.get_attribute::<CFString>("AXSubrole")
+ .map(|cf_string| cf_string.to_string())
+ })?
}
- /// Gets the process name associated with the window.
- ///
- /// This value is lazily retrieved and cached after first retrieval.
- pub fn process_name(&self) -> anyhow::Result<String> {
- self
- .process_name
- .get_or_init(Self::updated_process_name, self)
+ fn is_modal(&self) -> crate::Result<bool> {
+ self.inner.element.with(|el| {
+ el.get_attribute::<CFBoolean>("AXModal")
+ .map(|cf_bool| cf_bool.value())
+ })?
}
- /// Gets the process name associated with the window.
- fn updated_process_name(&self) -> anyhow::Result<String> {
- let mut process_id = 0u32;
- unsafe {
- GetWindowThreadProcessId(
- HWND(self.handle),
- Some(&raw mut process_id),
- );
- }
-
- let process_handle = unsafe {
- OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, process_id)
- }?;
-
- let mut buffer = [0u16; 256];
- let mut length = u32::try_from(buffer.len())?;
- unsafe {
- QueryFullProcessImageNameW(
- process_handle,
- PROCESS_NAME_WIN32,
- PWSTR(buffer.as_mut_ptr()),
- &raw mut length,
- )?;
-
- CloseHandle(process_handle)?;
- };
+ fn is_main(&self) -> crate::Result<bool> {
+ self.inner.element.with(|el| {
+ el.get_attribute::<CFBoolean>("AXMain")
+ .map(|cf_bool| cf_bool.value())
+ })?
+ }
+}
- let exe_path = String::from_utf16_lossy(&buffer[..length as usize]);
+/// Windows-specific extensions for [`NativeWindow`].
+#[cfg(target_os = "windows")]
+pub trait NativeWindowWindowsExt {
+ /// Creates a [`NativeWindow`] from a window handle.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn from_handle(handle: isize) -> NativeWindow;
- exe_path
- .split('\\')
- .next_back()
- .map(|file_name| {
- file_name.split('.').next().unwrap_or(file_name).to_string()
- })
- .context("Failed to parse process name.")
- }
+ /// Gets the window handle.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn hwnd(&self) -> HWND;
/// Gets the class name of the window.
///
- /// This value is lazily retrieved and cached after first retrieval.
- pub fn class_name(&self) -> anyhow::Result<String> {
- self.class_name.get_or_init(Self::updated_class_name, self)
- }
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn class_name(&self) -> crate::Result<String>;
- /// Gets the class name of the window.
- fn updated_class_name(&self) -> anyhow::Result<String> {
- let mut buffer = [0u16; 256];
- let result = unsafe { GetClassNameW(HWND(self.handle), &mut buffer) };
+ /// Gets the window's frame, including the window's shadow borders.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn frame_with_shadows(&self) -> crate::Result<Rect>;
- if result == 0 {
- return Err(windows::core::Error::from_win32().into());
- }
+ /// Gets the delta between the window's frame and the window's border.
+ /// This represents the size of a window's shadow borders.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn shadow_borders(&self) -> crate::Result<RectDelta>;
- #[allow(clippy::cast_sign_loss)]
- let class_name = String::from_utf16_lossy(&buffer[..result as usize]);
- Ok(class_name)
- }
+ /// Whether the window has an owner window.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn has_owner_window(&self) -> bool;
- /// Whether the window is still valid.
+ /// Whether the window has the given window style flag(s) set.
///
- /// Returns `true` if the underlying window handle refers to an existing window.
- pub fn is_valid(&self) -> bool {
- unsafe { IsWindow(HWND(self.handle)) }.as_bool()
- }
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn has_window_style(&self, style: WINDOW_STYLE) -> bool;
- /// Whether the window is actually visible.
- pub fn is_visible(&self) -> anyhow::Result<bool> {
- let is_visible =
- unsafe { IsWindowVisible(HWND(self.handle)) }.as_bool();
+ /// Whether the window has the given extended window style flag(s) set.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn has_window_style_ex(&self, style: WINDOW_EX_STYLE) -> bool;
- Ok(is_visible && !self.is_cloaked()?)
- }
+ /// Thin wrapper around [`SetWindowPos`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowpos).
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn set_window_pos(
+ &self,
+ z_order: &WindowZOrder,
+ rect: &Rect,
+ flags: SET_WINDOW_POS_FLAGS,
+ ) -> crate::Result<()>;
- /// Whether the window is cloaked. For some UWP apps, `WS_VISIBLE` will
- /// be present even if the window isn't actually visible. The
- /// `DWMWA_CLOAKED` attribute is used to check whether these apps are
- /// visible.
- fn is_cloaked(&self) -> anyhow::Result<bool> {
- let mut cloaked = 0u32;
+ /// Shows the window asynchronously.
+ ///
+ /// NOTE: Cloaked windows do not get shown until uncloaked.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn show(&self) -> crate::Result<()>;
- unsafe {
- #[allow(clippy::cast_possible_truncation)]
- DwmGetWindowAttribute(
- HWND(self.handle),
- DWMWA_CLOAKED,
- std::ptr::from_mut::<u32>(&mut cloaked).cast(),
- std::mem::size_of::<u32>() as u32,
- )
- }?;
+ /// Hides the window asynchronously.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn hide(&self) -> crate::Result<()>;
- Ok(cloaked != 0)
- }
+ /// Restores the window (unminimizes and unmaximizes).
+ ///
+ /// If `outer_frame` is provided, the window will be restored to the
+ /// specified position. This avoids flickering compared to restoring
+ /// and then repositioning the window.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn restore(&self, outer_frame: Option<&Rect>) -> crate::Result<()>;
- pub fn is_manageable(&self) -> anyhow::Result<bool> {
- // Ignore windows that are hidden.
- if !self.is_visible()? {
- return Ok(false);
- }
+ /// Cloaks or uncloaks the window.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn set_cloaked(&self, cloaked: bool) -> crate::Result<()>;
- // Ensure window has a valid process name, title, and class name.
- let process_name = self.process_name()?;
- let title = self.title()?;
- let _ = self.class_name()?;
+ /// Marks the window as fullscreen.
+ ///
+ /// Causes the native Windows taskbar to be moved to the bottom of the
+ /// z-order when this window is active.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn mark_fullscreen(&self, fullscreen: bool) -> crate::Result<()>;
- // TODO: Temporary fix for managing Flow Launcher until a force manage
- // command is added.
- if process_name == "Flow.Launcher" && title == "Flow.Launcher" {
- return Ok(true);
- }
+ /// Adds or removes the window from the native taskbar.
+ ///
+ /// Cloaked windows are normally always shown in the taskbar, but can be
+ /// manually toggled. Hidden windows (`SW_HIDE`) can never be shown in
+ /// the taskbar.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn set_taskbar_visibility(&self, visible: bool) -> crate::Result<()>;
- // Ensure window is top-level (i.e. not a child window). Ignore windows
- // that cannot be focused or if they're unavailable in task switcher
- // (alt+tab menu).
- let is_application_window = !self.has_window_style(WS_CHILD)
- && !self.has_window_style_ex(WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW);
+ /// Adds the given extended window style flag(s) to the window.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn add_window_style_ex(&self, style: WINDOW_EX_STYLE);
- if !is_application_window {
- return Ok(false);
- }
+ /// Sets the window's z-order.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn set_z_order(&self, zorder: &WindowZOrder) -> crate::Result<()>;
- // Ensure window position is accessible.
- self.refresh_frame_position()?;
+ /// Sets the visibility of the window's title bar.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn set_title_bar_visibility(&self, visible: bool) -> crate::Result<()>;
- // Some applications spawn top-level windows for menus that should be
- // ignored. This includes the autocomplete popup in Notepad++ and title
- // bar menu in Keepass. Although not foolproof, these can typically be
- // identified by having an owner window and no title bar.
- let is_menu_window =
- unsafe { GetWindow(HWND(self.handle), GW_OWNER) }.0 != 0
- && !self.has_window_style(WS_CAPTION);
+ /// Sets the color of the window's border.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn set_border_color(&self, color: Option<&Color>) -> crate::Result<()>;
- Ok(!is_menu_window)
- }
+ /// Sets the corner style of the window.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn set_corner_style(
+ &self,
+ corner_style: &CornerStyle,
+ ) -> crate::Result<()>;
- /// Whether the window is minimized.
+ /// Sets the transparency of the window.
///
- /// This value is lazily retrieved and cached after first retrieval.
- pub fn is_minimized(&self) -> anyhow::Result<bool> {
- self
- .is_minimized
- .get_or_init(Self::updated_is_minimized, self)
- }
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn set_transparency(
+ &self,
+ opacity_value: &OpacityValue,
+ ) -> crate::Result<()>;
- /// Updates the cached minimized status.
- pub fn refresh_is_minimized(&self) -> anyhow::Result<bool> {
- self.is_minimized.update(Self::updated_is_minimized, self)
- }
+ /// Adjusts the window's transparency by a relative delta.
+ ///
+ /// # Platform-specific
+ ///
+ /// This method is only available on Windows.
+ fn adjust_transparency(
+ &self,
+ opacity_delta: &Delta<OpacityValue>,
+ ) -> crate::Result<()>;
+}
- /// Whether the window is minimized.
- #[allow(clippy::unnecessary_wraps)]
- fn updated_is_minimized(&self) -> anyhow::Result<bool> {
- Ok(unsafe { IsIconic(HWND(self.handle)) }.as_bool())
+#[cfg(target_os = "windows")]
+impl NativeWindowWindowsExt for NativeWindow {
+ fn from_handle(handle: isize) -> Self {
+ platform_impl::NativeWindow::new(handle).into()
}
- /// Whether the window is maximized.
- ///
- /// This value is lazily retrieved and cached after first retrieval.
- pub fn is_maximized(&self) -> anyhow::Result<bool> {
- self
- .is_maximized
- .get_or_init(Self::updated_is_maximized, self)
+ fn hwnd(&self) -> HWND {
+ self.inner.hwnd()
}
- /// Updates the cached maximized status.
- pub fn refresh_is_maximized(&self) -> anyhow::Result<bool> {
- self.is_maximized.update(Self::updated_is_maximized, self)
+ fn class_name(&self) -> crate::Result<String> {
+ self.inner.class_name()
}
- /// Whether the window is maximized.
- #[allow(clippy::unnecessary_wraps)]
- fn updated_is_maximized(&self) -> anyhow::Result<bool> {
- Ok(unsafe { IsZoomed(HWND(self.handle)) }.as_bool())
+ fn frame_with_shadows(&self) -> crate::Result<Rect> {
+ self.inner.frame_with_shadows()
}
- /// Whether the window has resize handles.
- #[must_use]
- pub fn is_resizable(&self) -> bool {
- self.has_window_style(WS_THICKFRAME)
+ fn shadow_borders(&self) -> crate::Result<RectDelta> {
+ self.inner.shadow_borders()
}
- /// Whether the window is fullscreen.
- ///
- /// Returns `false` if the window is maximized.
- pub fn is_fullscreen(
- &self,
- monitor_rect: &Rect,
- ) -> anyhow::Result<bool> {
- if self.is_maximized()? {
- return Ok(false);
- }
-
- let position = self.frame_position()?;
-
- // Allow for 1px of leeway around edges of monitor.
- Ok(
- position.left <= monitor_rect.left + 1
- && position.top <= monitor_rect.top + 1
- && position.right >= monitor_rect.right - 1
- && position.bottom >= monitor_rect.bottom - 1,
- )
- }
-
- pub fn set_foreground(&self) -> anyhow::Result<()> {
- let input = [INPUT {
- r#type: INPUT_MOUSE,
- Anonymous: INPUT_0 {
- mi: MOUSEINPUT {
- dwExtraInfo: FOREGROUND_INPUT_IDENTIFIER as usize,
- ..Default::default()
- },
- },
- }];
-
- // Bypass restriction for setting the foreground window by sending an
- // input to our own process first.
- #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
- unsafe {
- SendInput(&input, std::mem::size_of::<INPUT>() as i32)
- };
+ fn has_owner_window(&self) -> bool {
+ self.inner.has_owner_window()
+ }
- // Set as the foreground window.
- unsafe { SetForegroundWindow(HWND(self.handle)) }.ok()?;
+ fn has_window_style(&self, style: WINDOW_STYLE) -> bool {
+ self.inner.has_window_style(style)
+ }
- Ok(())
+ fn has_window_style_ex(&self, style: WINDOW_EX_STYLE) -> bool {
+ self.inner.has_window_style_ex(style)
}
- pub fn set_border_color(
+ fn set_window_pos(
&self,
- color: Option<&Color>,
- ) -> anyhow::Result<()> {
- let bgr = match color {
- Some(color) => color.to_bgr()?,
- None => DWMWA_COLOR_NONE,
- };
-
- unsafe {
- #[allow(clippy::cast_possible_truncation)]
- DwmSetWindowAttribute(
- HWND(self.handle),
- DWMWA_BORDER_COLOR,
- std::ptr::from_ref(&bgr).cast(),
- std::mem::size_of::<u32>() as u32,
- )?;
- }
+ z_order: &WindowZOrder,
+ rect: &Rect,
+ flags: SET_WINDOW_POS_FLAGS,
+ ) -> crate::Result<()> {
+ self.inner.set_window_pos(z_order, rect, flags)
+ }
- Ok(())
+ fn show(&self) -> crate::Result<()> {
+ self.inner.show()
}
- pub fn set_corner_style(
- &self,
- corner_style: &CornerStyle,
- ) -> anyhow::Result<()> {
- let corner_preference = match corner_style {
- CornerStyle::Default => DWMWCP_DEFAULT,
- CornerStyle::Square => DWMWCP_DONOTROUND,
- CornerStyle::Rounded => DWMWCP_ROUND,
- CornerStyle::SmallRounded => DWMWCP_ROUNDSMALL,
- };
+ fn hide(&self) -> crate::Result<()> {
+ self.inner.hide()
+ }
- unsafe {
- #[allow(clippy::cast_possible_truncation)]
- DwmSetWindowAttribute(
- HWND(self.handle),
- DWMWA_WINDOW_CORNER_PREFERENCE,
- std::ptr::from_ref(&(corner_preference.0)).cast(),
- std::mem::size_of::<i32>() as u32,
- )?;
- }
+ fn restore(&self, outer_frame: Option<&Rect>) -> crate::Result<()> {
+ self.inner.restore(outer_frame)
+ }
- Ok(())
+ fn set_cloaked(&self, cloaked: bool) -> crate::Result<()> {
+ self.inner.set_cloaked(cloaked)
}
- pub fn set_title_bar_visibility(
- &self,
- visible: bool,
- ) -> anyhow::Result<()> {
- let style = unsafe { GetWindowLongPtrW(HWND(self.handle), GWL_STYLE) };
-
- #[allow(clippy::cast_possible_wrap)]
- let new_style = if visible {
- style | (WS_DLGFRAME.0 as isize)
- } else {
- style & !(WS_DLGFRAME.0 as isize)
- };
+ fn mark_fullscreen(&self, fullscreen: bool) -> crate::Result<()> {
+ self.inner.mark_fullscreen(fullscreen)
+ }
- if new_style != style {
- unsafe {
- SetWindowLongPtrW(HWND(self.handle), GWL_STYLE, new_style);
- SetWindowPos(
- HWND(self.handle),
- HWND_NOTOPMOST,
- 0,
- 0,
- 0,
- 0,
- SWP_FRAMECHANGED
- | SWP_NOMOVE
- | SWP_NOSIZE
- | SWP_NOZORDER
- | SWP_NOOWNERZORDER
- | SWP_NOACTIVATE
- | SWP_NOCOPYBITS
- | SWP_NOSENDCHANGING
- | SWP_ASYNCWINDOWPOS,
- )?;
- }
- }
-
- Ok(())
+ fn set_taskbar_visibility(&self, visible: bool) -> crate::Result<()> {
+ self.inner.set_taskbar_visibility(visible)
}
fn add_window_style_ex(&self, style: WINDOW_EX_STYLE) {
- let current_style =
- unsafe { GetWindowLongPtrW(HWND(self.handle), GWL_EXSTYLE) };
-
- #[allow(clippy::cast_possible_wrap)]
- if current_style & style.0 as isize == 0 {
- let new_style = current_style | style.0 as isize;
+ self.inner.add_window_style_ex(style);
+ }
- unsafe {
- SetWindowLongPtrW(HWND(self.handle), GWL_EXSTYLE, new_style)
- };
- }
+ fn set_z_order(&self, z_order: &WindowZOrder) -> crate::Result<()> {
+ self.inner.set_z_order(z_order)
}
- pub fn adjust_transparency(
- &self,
- opacity_delta: &Delta<OpacityValue>,
- ) -> anyhow::Result<()> {
- let mut alpha = u8::MAX;
- let mut flag = LAYERED_WINDOW_ATTRIBUTES_FLAGS::default();
+ fn set_title_bar_visibility(&self, visible: bool) -> crate::Result<()> {
+ self.inner.set_title_bar_visibility(visible)
+ }
- unsafe {
- GetLayeredWindowAttributes(
- HWND(self.handle),
- None,
- Some(&raw mut alpha),
- Some(&raw mut flag),
- )?;
- }
-
- if flag.contains(LWA_COLORKEY) {
- bail!(
- "Window uses color key for its transparency and cannot be adjusted."
- );
- }
-
- let target_alpha = if opacity_delta.is_negative {
- alpha.saturating_sub(opacity_delta.inner.to_alpha())
- } else {
- alpha.saturating_add(opacity_delta.inner.to_alpha())
- };
+ fn set_border_color(&self, color: Option<&Color>) -> crate::Result<()> {
+ self.inner.set_border_color(color)
+ }
- self.set_transparency(&OpacityValue::from_alpha(target_alpha))
+ fn set_corner_style(
+ &self,
+ corner_style: &CornerStyle,
+ ) -> crate::Result<()> {
+ self.inner.set_corner_style(corner_style)
}
- pub fn set_transparency(
+ fn set_transparency(
&self,
opacity_value: &OpacityValue,
- ) -> anyhow::Result<()> {
- // Make the window layered if it isn't already.
- self.add_window_style_ex(WS_EX_LAYERED);
-
- unsafe {
- SetLayeredWindowAttributes(
- HWND(self.handle),
- None,
- opacity_value.to_alpha(),
- LWA_ALPHA,
- )?;
- }
-
- Ok(())
+ ) -> crate::Result<()> {
+ self.inner.set_transparency(opacity_value)
}
- /// Gets the window's position, including the window's frame. Excludes
- /// the window's shadow borders.
- ///
- /// This value is lazily retrieved and cached after first retrieval.
- pub fn frame_position(&self) -> anyhow::Result<Rect> {
- self
- .frame_position
- .get_or_init(Self::updated_frame_position, self)
+ fn adjust_transparency(
+ &self,
+ opacity_delta: &Delta<OpacityValue>,
+ ) -> crate::Result<()> {
+ self.inner.adjust_transparency(opacity_delta)
}
+}
- /// Updates the cached frame position.
- pub fn refresh_frame_position(&self) -> anyhow::Result<Rect> {
- _ = self.refresh_border_position()?;
+#[derive(Clone, Debug)]
+pub struct NativeWindow {
+ pub(crate) inner: platform_impl::NativeWindow,
+}
- self
- .frame_position
- .update(Self::updated_frame_position, self)
+impl NativeWindow {
+ /// Gets the unique identifier for this window.
+ #[must_use]
+ pub fn id(&self) -> WindowId {
+ self.inner.id()
}
- /// Gets the window's position, including the window's frame. Excludes
- /// the window's shadow borders.
- fn updated_frame_position(&self) -> anyhow::Result<Rect> {
- let mut rect = RECT::default();
-
- let dwm_res = unsafe {
- #[allow(clippy::cast_possible_truncation)]
- DwmGetWindowAttribute(
- HWND(self.handle),
- DWMWA_EXTENDED_FRAME_BOUNDS,
- std::ptr::from_mut(&mut rect).cast(),
- std::mem::size_of::<RECT>() as u32,
- )
- };
+ /// Gets the window's title.
+ ///
+ /// Note that empty strings are valid window titles.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`Error::WindowNotFound`] if the window is invalid.
+ pub fn title(&self) -> crate::Result<String> {
+ self.inner.title()
+ }
- if let Ok(()) = dwm_res {
- Ok(Rect::from_ltrb(
- rect.left,
- rect.top,
- rect.right,
- rect.bottom,
- ))
- } else {
- warn!("Failed to get window's frame position. Falling back to border position.");
- self.border_position()
- }
+ pub fn process_name(&self) -> crate::Result<String> {
+ self.inner.process_name()
}
- /// Gets the window's position, including the window's frame and
- /// shadow borders.
+ /// Gets a rectangle of the window's size and position.
///
- /// This value is lazily retrieved and cached after first retrieval.
- pub fn border_position(&self) -> anyhow::Result<Rect> {
- self
- .border_position
- .get_or_init(Self::updated_border_position, self)
+ /// # Platform-specific
+ ///
+ /// - **Windows**: Includes the window's shadow borders.
+ /// - **macOS**: If the window was previously resized to a value outside
+ /// of the window's allowed min/max width & height (e.g. via calling
+ /// `set_frame`), this can return those invalid values and might not
+ /// reflect the actual window size.
+ pub fn frame(&self) -> crate::Result<Rect> {
+ self.inner.frame()
}
- /// Updates the cached border position.
- pub fn refresh_border_position(&self) -> anyhow::Result<Rect> {
- self
- .border_position
- .update(Self::updated_border_position, self)
+ /// Gets the window's position as (x, y) coordinates.
+ pub fn position(&self) -> crate::Result<(f64, f64)> {
+ self.inner.position()
}
- /// Gets the window's position, including the window's frame and
- /// shadow borders.
- fn updated_border_position(&self) -> anyhow::Result<Rect> {
- let mut rect = RECT::default();
-
- unsafe {
- GetWindowRect(
- HWND(self.handle),
- std::ptr::from_mut(&mut rect).cast(),
- )
- }?;
-
- Ok(Rect::from_ltrb(
- rect.left,
- rect.top,
- rect.right,
- rect.bottom,
- ))
+ /// Gets the window's size as (width, height).
+ pub fn size(&self) -> crate::Result<(f64, f64)> {
+ self.inner.size()
}
- /// Gets the delta between the window's frame and the window's border.
- /// This represents the size of a window's shadow borders.
- pub fn shadow_border_delta(&self) -> anyhow::Result<RectDelta> {
- let border_pos = self.border_position()?;
- let frame_pos = self.frame_position()?;
-
- Ok(RectDelta::new(
- LengthValue::from_px(frame_pos.left - border_pos.left),
- LengthValue::from_px(frame_pos.top - border_pos.top),
- LengthValue::from_px(border_pos.right - frame_pos.right),
- LengthValue::from_px(border_pos.bottom - frame_pos.bottom),
- ))
+ /// Whether the window is still valid.
+ ///
+ /// Returns `true` if the underlying window is still alive.
+ #[must_use]
+ pub fn is_valid(&self) -> bool {
+ self.inner.is_valid()
}
- fn has_window_style(&self, style: WINDOW_STYLE) -> bool {
- let current_style =
- unsafe { GetWindowLongPtrW(HWND(self.handle), GWL_STYLE) };
-
- #[allow(clippy::cast_possible_wrap)]
- let style = style.0 as isize;
- (current_style & style) != 0
+ /// Whether the window is actually visible.
+ pub fn is_visible(&self) -> crate::Result<bool> {
+ self.inner.is_visible()
}
- fn has_window_style_ex(&self, style: WINDOW_EX_STYLE) -> bool {
- let current_style =
- unsafe { GetWindowLongPtrW(HWND(self.handle), GWL_EXSTYLE) };
-
- #[allow(clippy::cast_possible_wrap)]
- let style = style.0 as isize;
- (current_style & style) != 0
- }
-
- pub fn restore_to_position(&self, rect: &Rect) -> anyhow::Result<()> {
- let placement = WINDOWPLACEMENT {
- #[allow(clippy::cast_possible_truncation)]
- length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
- flags: WPF_ASYNCWINDOWPLACEMENT,
- showCmd: SW_RESTORE.0 as u32,
- rcNormalPosition: RECT {
- left: rect.left,
- top: rect.top,
- right: rect.right,
- bottom: rect.bottom,
- },
- ..Default::default()
- };
-
- unsafe {
- SetWindowPlacement(HWND(self.handle), &raw const placement)
- }?;
-
- Ok(())
+ /// Whether the window is minimized.
+ pub fn is_minimized(&self) -> crate::Result<bool> {
+ self.inner.is_minimized()
}
- pub fn maximize(&self) -> anyhow::Result<()> {
- unsafe { ShowWindowAsync(HWND(self.handle), SW_MAXIMIZE).ok() }?;
- Ok(())
+ /// Whether the window is maximized.
+ pub fn is_maximized(&self) -> crate::Result<bool> {
+ self.inner.is_maximized()
}
- pub fn minimize(&self) -> anyhow::Result<()> {
- unsafe { ShowWindowAsync(HWND(self.handle), SW_MINIMIZE).ok() }?;
- Ok(())
+ /// Whether the window can be resized.
+ pub fn is_resizable(&self) -> crate::Result<bool> {
+ self.inner.is_resizable()
}
- pub fn close(&self) -> anyhow::Result<()> {
- unsafe {
- SendNotifyMessageW(HWND(self.handle), WM_CLOSE, None, None)
- }?;
-
- Ok(())
+ /// Whether the window is the OS's desktop window.
+ pub fn is_desktop_window(&self) -> crate::Result<bool> {
+ self.inner.is_desktop_window()
}
- pub fn set_visible(
- &self,
- visible: bool,
- hide_method: &HideMethod,
- ) -> anyhow::Result<()> {
- match hide_method {
- HideMethod::Hide => {
- if visible {
- self.show()
- } else {
- self.hide()
- }
- }
- HideMethod::Cloak => self.set_cloaked(!visible),
- }
+ /// Repositions and resizes the window to the specified rectangle.
+ ///
+ /// # Platform-specific
+ ///
+ /// - **Windows**: Automatically adjusts the `rect` prior to calling [`SetWindowPos`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowpos)
+ /// to include the window's shadow borders. To set the window's
+ /// position directly, use [`NativeWindowWindowsExt::set_window_pos`].
+ pub fn set_frame(&self, rect: &Rect) -> crate::Result<()> {
+ self.inner.set_frame(rect)
}
- pub fn show(&self) -> anyhow::Result<()> {
- unsafe { ShowWindowAsync(HWND(self.handle), SW_SHOWNA) }.ok()?;
- Ok(())
+ /// Resizes the window to the specified size.
+ pub fn resize(&self, width: i32, height: i32) -> crate::Result<()> {
+ self.inner.resize(width, height)
}
- pub fn hide(&self) -> anyhow::Result<()> {
- unsafe { ShowWindowAsync(HWND(self.handle), SW_HIDE) }.ok()?;
- Ok(())
+ /// Repositions the window to the specified position.
+ pub fn reposition(&self, x: i32, y: i32) -> crate::Result<()> {
+ self.inner.reposition(x, y)
}
- pub fn set_cloaked(&self, cloaked: bool) -> anyhow::Result<()> {
- COM_INIT.with(|com_init| {
- com_init.borrow_mut().with_retry(|c| {
- let view_collection = c.application_view_collection()?;
-
- let mut view = None;
- unsafe {
- view_collection.get_view_for_hwnd(self.handle, &raw mut view)
- }
- .ok()?;
-
- let view = view
- .context("Unable to get application view by window handle.")?;
-
- // Ref: https://github.com/Ciantic/AltTabAccessor/issues/1#issuecomment-1426877843
- unsafe { view.set_cloak(1, if cloaked { 2 } else { 0 }) }
- .ok()
- .context("Failed to cloak window.")
- })
- })
+ pub fn minimize(&self) -> crate::Result<()> {
+ self.inner.minimize()
}
- /// Adds or removes the window from the native taskbar.
- ///
- /// Hidden windows (`SW_HIDE`) cannot be forced to be shown in the
- /// taskbar. Cloaked windows are normally always shown in the taskbar,
- /// but can be manually toggled.
- pub fn set_taskbar_visibility(
- &self,
- visible: bool,
- ) -> anyhow::Result<()> {
- COM_INIT.with(|com_init| {
- com_init.borrow_mut().with_retry(|c| {
- let taskbar_list = c.taskbar_list()?;
-
- if visible {
- unsafe { taskbar_list.AddTab(HWND(self.handle))? };
- } else {
- unsafe { taskbar_list.DeleteTab(HWND(self.handle))? };
- }
-
- Ok(())
- })
- })
+ pub fn maximize(&self) -> crate::Result<()> {
+ self.inner.maximize()
}
- pub fn set_position(
- &self,
- state: &WindowState,
- rect: &Rect,
- z_order: &ZOrder,
- is_visible: bool,
- hide_method: &HideMethod,
- has_pending_dpi_adjustment: bool,
- ) -> anyhow::Result<()> {
- // Restore window if it's minimized/maximized and shouldn't be. This is
- // needed to be able to move and resize it.
- match state {
- // Need to restore window if transitioning from maximized fullscreen
- // to non-maximized fullscreen.
- WindowState::Fullscreen(config) => {
- if !config.maximized && self.is_maximized()? {
- // Restoring to position has the same effect as `ShowWindow` with
- // `SW_RESTORE`, but doesn't cause a flicker.
- self.restore_to_position(rect)?;
- }
- }
- // No need to restore window if it'll be minimized. Transitioning
- // from maximized to minimized works without having to restore.
- WindowState::Minimized => {}
- _ => {
- if self.is_minimized()? || self.is_maximized()? {
- self.restore_to_position(rect)?;
- }
- }
- }
-
- let mut swp_flags = SWP_NOACTIVATE
- | SWP_NOCOPYBITS
- | SWP_NOSENDCHANGING
- | SWP_ASYNCWINDOWPOS;
-
- let z_order = match z_order {
- ZOrder::TopMost => HWND_TOPMOST,
- ZOrder::Top => HWND_TOP,
- ZOrder::Normal => HWND_NOTOPMOST,
- ZOrder::AfterWindow(hwnd) => HWND(*hwnd),
- };
-
- match state {
- WindowState::Minimized => {
- if !self.is_minimized()? {
- self.minimize()?;
- }
- }
- WindowState::Fullscreen(config)
- if config.maximized && self.has_window_style(WS_MAXIMIZEBOX) =>
- {
- if !self.is_maximized()? {
- self.maximize()?;
- }
-
- unsafe {
- SetWindowPos(
- HWND(self.handle),
- z_order,
- rect.x(),
- rect.y(),
- rect.width(),
- rect.height(),
- swp_flags,
- )
- }?;
- }
- _ => {
- swp_flags |= SWP_FRAMECHANGED;
-
- unsafe {
- SetWindowPos(
- HWND(self.handle),
- z_order,
- rect.x(),
- rect.y(),
- rect.width(),
- rect.height(),
- swp_flags,
- )
- }?;
-
- // When there's a mismatch between the DPI of the monitor and the
- // window, the window might be sized incorrectly after the first
- // move. If we set the position twice, inconsistencies after the
- // first move are resolved.
- if has_pending_dpi_adjustment {
- unsafe {
- SetWindowPos(
- HWND(self.handle),
- z_order,
- rect.x(),
- rect.y(),
- rect.width(),
- rect.height(),
- swp_flags,
- )
- }?;
- }
- }
- }
-
- // Whether to hide or show the window.
- self.set_visible(is_visible, hide_method)?;
-
- Ok(())
+ /// Sets focus to the window and raises it to the top of the z-order.
+ pub fn focus(&self) -> crate::Result<()> {
+ self.inner.focus()
}
- /// Marks the window as fullscreen.
+ /// Closes the window.
///
- /// Causes the native Windows taskbar to be moved to the bottom of the
- /// z-order when this window is active.
- pub fn mark_fullscreen(&self, fullscreen: bool) -> anyhow::Result<()> {
- COM_INIT.with(|com_init| {
- com_init.borrow_mut().with_retry(|c| {
- let taskbar_list = c.taskbar_list()?;
-
- unsafe {
- taskbar_list.MarkFullscreenWindow(HWND(self.handle), fullscreen)
- }?;
-
- Ok(())
- })
- })
- }
-
- pub fn set_z_order(&self, z_order: &ZOrder) -> anyhow::Result<()> {
- let z_order = match z_order {
- ZOrder::TopMost => HWND_TOPMOST,
- ZOrder::Top => HWND_TOP,
- ZOrder::Normal => HWND_NOTOPMOST,
- ZOrder::AfterWindow(hwnd) => HWND(*hwnd),
- };
-
- unsafe {
- SetWindowPos(
- HWND(self.handle),
- z_order,
- 0,
- 0,
- 0,
- 0,
- SWP_NOACTIVATE
- | SWP_NOCOPYBITS
- | SWP_ASYNCWINDOWPOS
- | SWP_SHOWWINDOW
- | SWP_NOMOVE
- | SWP_NOSIZE,
- )
- }?;
-
- let handle = self.handle;
-
- // Z-order can sometimes still be incorrect after the above call.
- task::spawn(async move {
- tokio::time::sleep(Duration::from_millis(10)).await;
-
- let _ = unsafe {
- SetWindowPos(
- HWND(handle),
- z_order,
- 0,
- 0,
- 0,
- 0,
- SWP_NOACTIVATE
- | SWP_NOCOPYBITS
- | SWP_ASYNCWINDOWPOS
- | SWP_SHOWWINDOW
- | SWP_NOMOVE
- | SWP_NOSIZE,
- )
- };
- });
-
- Ok(())
- }
-
- pub fn cleanup(&self) {
- if let Err(err) = self.show() {
- warn!("Failed to show window: {:?}", err);
- }
-
- _ = self.set_taskbar_visibility(true);
- _ = self.set_border_color(None);
- _ = self.set_transparency(&OpacityValue::from_alpha(u8::MAX));
+ /// # Platform-specific
+ ///
+ /// - **Windows**: This sends a `WM_CLOSE` message to the window.
+ /// - **macOS**: This simulates pressing the close button on the window's
+ /// title bar.
+ pub fn close(&self) -> crate::Result<()> {
+ self.inner.close()
}
}
impl PartialEq for NativeWindow {
fn eq(&self, other: &Self) -> bool {
- self.handle == other.handle
+ self.inner.id() == other.inner.id()
}
}
impl Eq for NativeWindow {}
-
-pub fn available_windows() -> anyhow::Result<Vec<NativeWindow>> {
- available_window_handles()?
- .into_iter()
- .map(|handle| Ok(NativeWindow::new(handle)))
- .collect()
-}
-
-pub fn available_window_handles() -> anyhow::Result<Vec<isize>> {
- let mut handles: Vec<isize> = Vec::new();
-
- unsafe {
- EnumWindows(
- Some(available_window_handles_proc),
- LPARAM(std::ptr::from_mut(&mut handles) as _),
- )
- }?;
-
- Ok(handles)
-}
-
-extern "system" fn available_window_handles_proc(
- handle: HWND,
- data: LPARAM,
-) -> BOOL {
- let handles = data.0 as *mut Vec<isize>;
- unsafe { (*handles).push(handle.0) };
- true.into()
-}
diff --git a/packages/wm-platform/src/platform.rs b/packages/wm-platform/src/platform.rs
deleted file mode 100644
index ebe3e2d1..00000000
--- a/packages/wm-platform/src/platform.rs
+++ /dev/null
@@ -1,521 +0,0 @@
-use std::{
- os::windows::io::AsRawHandle,
- path::{Path, PathBuf},
- thread::JoinHandle,
-};
-
-use anyhow::{bail, Context};
-use auto_launch::AutoLaunch;
-use windows::{
- core::{w, PCWSTR},
- Win32::{
- Foundation::{HANDLE, HWND, LPARAM, POINT, WPARAM},
- System::{
- Environment::ExpandEnvironmentStringsW, Threading::GetThreadId,
- },
- UI::{
- Shell::{
- ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS,
- SHELLEXECUTEINFOW,
- },
- WindowsAndMessaging::{
- CreateWindowExW, DispatchMessageW, GetAncestor, GetCursorPos,
- GetDesktopWindow, GetForegroundWindow, GetMessageW,
- GetShellWindow, MessageBoxW, PeekMessageW, PostThreadMessageW,
- RegisterClassW, SetCursorPos, SystemParametersInfoW,
- TranslateMessage, WindowFromPoint, ANIMATIONINFO, CS_HREDRAW,
- CS_VREDRAW, CW_USEDEFAULT, GA_ROOT, MB_ICONERROR, MB_OK,
- MB_SYSTEMMODAL, MSG, PM_REMOVE, SPIF_SENDCHANGE,
- SPIF_UPDATEINIFILE, SPI_GETANIMATION, SPI_SETANIMATION, SW_HIDE,
- SW_NORMAL, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, WINDOW_EX_STYLE,
- WM_QUIT, WNDCLASSW, WNDPROC, WS_OVERLAPPEDWINDOW,
- },
- },
- },
-};
-use wm_common::{ParsedConfig, Point};
-
-use super::{
- native_monitor, native_window, EventListener, NativeMonitor,
- NativeWindow, SingleInstance,
-};
-
-pub type WindowProcedure = WNDPROC;
-
-pub struct Platform;
-
-impl Platform {
- /// Gets the `NativeWindow` instance of the currently focused window.
- #[must_use]
- pub fn foreground_window() -> NativeWindow {
- let handle = unsafe { GetForegroundWindow() };
- NativeWindow::new(handle.0)
- }
-
- /// Gets the `NativeWindow` instance of the desktop window.
- ///
- /// This is the explorer.exe wallpaper window (i.e. "Progman"). If
- /// explorer.exe isn't running, then default to the desktop window below
- /// the wallpaper window.
- #[must_use]
- pub fn desktop_window() -> NativeWindow {
- let handle = match unsafe { GetShellWindow() } {
- HWND(0) => unsafe { GetDesktopWindow() },
- handle => handle,
- };
-
- NativeWindow::new(handle.0)
- }
-
- /// Gets a vector of available monitors as `NativeMonitor` instances
- /// sorted from left-to-right and top-to-bottom.
- ///
- /// Note that this also ensures that the `NativeMonitor` instances have
- /// valid position values.
- pub fn sorted_monitors() -> anyhow::Result<Vec<NativeMonitor>> {
- let monitors = native_monitor::available_monitors()?;
-
- // Create a tuple of monitors and their rects.
- let mut monitors_with_rect = monitors
- .into_iter()
- .map(|monitor| {
- let rect = monitor.rect()?.clone();
- anyhow::Ok((monitor, rect))
- })
- .try_collect::<Vec<_>>()?;
-
- // Sort monitors from left-to-right, top-to-bottom.
- monitors_with_rect.sort_by(|(_, rect_a), (_, rect_b)| {
- if rect_a.x() == rect_b.x() {
- rect_a.y().cmp(&rect_b.y())
- } else {
- rect_a.x().cmp(&rect_b.x())
- }
- });
-
- // Convert back to a regular vector of monitors.
- Ok(
- monitors_with_rect
- .into_iter()
- .map(|(monitor, _)| monitor)
- .collect(),
- )
- }
-
- #[must_use]
- pub fn nearest_monitor(window: &NativeWindow) -> NativeMonitor {
- native_monitor::nearest_monitor(window.handle)
- }
-
- /// Gets a vector of "manageable" windows as `NativeWindow` instances.
- ///
- /// Manageable windows are visible windows that the WM is most likely
- /// able to manage. Windows are returned in z-order (top to bottom),
- /// although the order is not guaranteed by the underlying API.
- pub fn manageable_windows() -> anyhow::Result<Vec<NativeWindow>> {
- Ok(
- native_window::available_windows()?
- .into_iter()
- .filter(|window| window.is_manageable().unwrap_or(false))
- .collect(),
- )
- }
-
- /// Creates a new `EventListener` for the specified user config.
- pub fn start_event_listener(
- config: &ParsedConfig,
- ) -> anyhow::Result<EventListener> {
- EventListener::start(config)
- }
-
- /// Creates a new `SingleInstance`.
- pub fn new_single_instance() -> anyhow::Result<SingleInstance> {
- SingleInstance::new()
- }
-
- // Gets the root window of the specified window.
- pub fn root_ancestor(
- window: &NativeWindow,
- ) -> anyhow::Result<NativeWindow> {
- let handle = unsafe { GetAncestor(HWND(window.handle), GA_ROOT) };
- Ok(NativeWindow::new(handle.0))
- }
-
- /// Sets the cursor position to the specified coordinates.
- pub fn set_cursor_pos(x: i32, y: i32) -> anyhow::Result<()> {
- unsafe {
- SetCursorPos(x, y)?;
- };
-
- Ok(())
- }
-
- /// Finds the window at the specified point in screen space.
- pub fn window_from_point(point: &Point) -> anyhow::Result<NativeWindow> {
- let point = POINT {
- x: point.x,
- y: point.y,
- };
-
- let handle = unsafe { WindowFromPoint(point) };
- Ok(NativeWindow::new(handle.0))
- }
-
- /// Gets the mouse position in screen space.
- pub fn mouse_position() -> anyhow::Result<Point> {
- let mut point = POINT { x: 0, y: 0 };
- unsafe { GetCursorPos(&raw mut point) }?;
-
- Ok(Point {
- x: point.x,
- y: point.y,
- })
- }
-
- /// Creates a hidden message window.
- ///
- /// Returns a handle to the created window.
- pub fn create_message_window(
- window_procedure: WindowProcedure,
- ) -> anyhow::Result<isize> {
- let wnd_class = WNDCLASSW {
- lpszClassName: w!("MessageWindow"),
- style: CS_HREDRAW | CS_VREDRAW,
- lpfnWndProc: window_procedure,
- ..Default::default()
- };
-
- unsafe { RegisterClassW(&raw const wnd_class) };
-
- let handle = unsafe {
- CreateWindowExW(
- WINDOW_EX_STYLE::default(),
- w!("MessageWindow"),
- w!("MessageWindow"),
- WS_OVERLAPPEDWINDOW,
- CW_USEDEFAULT,
- CW_USEDEFAULT,
- CW_USEDEFAULT,
- CW_USEDEFAULT,
- None,
- None,
- wnd_class.hInstance,
- None,
- )
- };
-
- if handle.0 == 0 {
- bail!("Creation of message window failed.");
- }
-
- Ok(handle.0)
- }
-
- /// Starts a message loop on the current thread.
- ///
- /// This function will block until the message loop is killed. Use
- /// `Platform::kill_message_loop` to terminate the message loop.
- pub fn run_message_loop() {
- let mut msg = MSG::default();
-
- loop {
- if unsafe { GetMessageW(&raw mut msg, None, 0, 0) }.as_bool() {
- unsafe {
- TranslateMessage(&raw const msg);
- DispatchMessageW(&raw const msg);
- }
- } else {
- break;
- }
- }
- }
-
- /// Runs a single cycle of a message loop on the current thread.
- ///
- /// Is non-blocking and returns immediately if there are no messages.
- pub fn run_message_cycle() -> anyhow::Result<()> {
- let mut msg = MSG::default();
-
- let has_message =
- unsafe { PeekMessageW(&raw mut msg, None, 0, 0, PM_REMOVE) }
- .as_bool();
-
- if has_message {
- if msg.message == WM_QUIT {
- bail!("Received WM_QUIT message.")
- }
-
- unsafe {
- TranslateMessage(&raw const msg);
- DispatchMessageW(&raw const msg);
- }
- }
-
- Ok(())
- }
-
- /// Gracefully terminates the message loop on the given thread.
- pub fn kill_message_loop<T>(
- thread: &JoinHandle<T>,
- ) -> anyhow::Result<()> {
- let handle = thread.as_raw_handle();
- let handle = HANDLE(handle as isize);
- let thread_id = unsafe { GetThreadId(handle) };
-
- unsafe {
- PostThreadMessageW(
- thread_id,
- WM_QUIT,
- WPARAM::default(),
- LPARAM::default(),
- )
- }?;
-
- Ok(())
- }
-
- /// Gets whether window transition animations are currently enabled.
- ///
- /// Note that this is a global system setting.
- pub fn window_animations_enabled() -> anyhow::Result<bool> {
- let mut animation_info = ANIMATIONINFO {
- #[allow(clippy::cast_possible_truncation)]
- cbSize: std::mem::size_of::<ANIMATIONINFO>() as u32,
- iMinAnimate: 0,
- };
-
- unsafe {
- SystemParametersInfoW(
- SPI_GETANIMATION,
- animation_info.cbSize,
- Some(std::ptr::from_mut(&mut animation_info).cast()),
- SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
- )
- }?;
-
- Ok(animation_info.iMinAnimate != 0)
- }
-
- /// Enables or disables window transition animations.
- ///
- /// Note that this is a global system setting.
- pub fn set_window_animations_enabled(
- enable: bool,
- ) -> anyhow::Result<()> {
- let mut animation_info = ANIMATIONINFO {
- #[allow(clippy::cast_possible_truncation)]
- cbSize: std::mem::size_of::<ANIMATIONINFO>() as u32,
- iMinAnimate: i32::from(enable),
- };
-
- unsafe {
- SystemParametersInfoW(
- SPI_SETANIMATION,
- animation_info.cbSize,
- Some(std::ptr::from_mut(&mut animation_info).cast()),
- SPIF_UPDATEINIFILE | SPIF_SENDCHANGE,
- )
- }?;
-
- Ok(())
- }
-
- /// Gets the `AutoLaunch` instance for the GlazeWM application.
- fn get_auto_launch() -> anyhow::Result<AutoLaunch> {
- let exe_path = std::env::current_exe()?;
- let quoted_exe_str = format!("\"{}\"", exe_path.to_str().unwrap());
- Ok(AutoLaunch::new("GlazeWM", &quoted_exe_str, &[] as &[&str]))
- }
-
- /// Checks if auto-launch at system startup is enabled.
- pub fn is_auto_launch_enabled() -> anyhow::Result<bool> {
- let auto_launch = Self::get_auto_launch()?;
-
- match auto_launch.is_enabled() {
- Ok(enabled) => Ok(enabled),
- Err(e) => {
- Err(e.into())
- }
- }
- }
-
- /// Enables or disables auto-launch at system startup.
- pub fn set_auto_launch_enabled(enable: bool) -> anyhow::Result<()> {
- let auto_launch = Self::get_auto_launch()?;
-
- if enable {
- auto_launch.enable()?;
- } else {
- auto_launch.disable()?;
- }
-
- Ok(())
- }
-
- /// Opens File Explorer at the specified path.
- pub fn open_file_explorer(path: &PathBuf) -> anyhow::Result<()> {
- let normalized_path = std::fs::canonicalize(path)?;
-
- std::process::Command::new("explorer")
- .arg(normalized_path)
- .spawn()?;
-
- Ok(())
- }
-
- /// Parses a command string into a program name/path and arguments. This
- /// also expands any environment variables found in the command string if
- /// they are wrapped in `%` characters. If the command string is a path,
- /// a file extension is required.
- ///
- /// This is similar to the `SHEvaluateSystemCommandTemplate` function. It
- /// also parses program name/path and arguments, but can't handle `/` as
- /// file path delimiters and it errors for certain programs (e.g.
- /// `code`).
- ///
- /// Returns a tuple containing the program name/path and arguments.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use wm::common::platform::Platform;
- /// let (prog, args) = Platform::parse_command("code .")?;
- /// assert_eq!(prog, "code");
- /// assert_eq!(args, ".");
- ///
- /// let (prog, args) = Platform::parse_command(
- /// r#"C:\Program Files\Git\git-bash --cd=C:\Users\larsb\.glaze-wm"#,
- /// )?;
- /// assert_eq!(prog, r#"C:\Program Files\Git\git-bash"#);
- /// assert_eq!(args, r#"--cd=C:\Users\larsb\.glaze-wm"#);
- /// # Ok::<(), anyhow::Error>(())
- /// ```
- pub fn parse_command(command: &str) -> anyhow::Result<(String, String)> {
- // Expand environment variables in the command string.
- let expanded_command = {
- let wide_command = to_wide(command);
- let size = unsafe {
- ExpandEnvironmentStringsW(PCWSTR(wide_command.as_ptr()), None)
- };
-
- if size == 0 {
- anyhow::bail!(
- "Failed to expand environment strings in command '{}'.",
- command
- );
- }
-
- let mut buffer = vec![0; size as usize];
- let size = unsafe {
- ExpandEnvironmentStringsW(
- PCWSTR(wide_command.as_ptr()),
- Some(&mut buffer),
- )
- };
-
- // The size includes the null terminator, so we need to subtract one.
- String::from_utf16_lossy(&buffer[..(size - 1) as usize])
- };
-
- let command_parts: Vec<&str> =
- expanded_command.split_whitespace().collect();
-
- // If the command starts with double quotes, then the program name/path
- // is wrapped in double quotes (e.g. `"C:\path\to\app.exe" --flag`).
- if command.starts_with('"') {
- // Find the closing double quote.
- let (closing_index, _) =
- command.match_indices('"').nth(2).with_context(|| {
- format!("Command doesn't have an ending `\"`: '{command}'.")
- })?;
-
- return Ok((
- command[1..closing_index].to_string(),
- command[closing_index + 1..].trim().to_string(),
- ));
- }
-
- // The first part is the program name if it doesn't contain a slash or
- // backslash.
- if let Some(first_part) = command_parts.first() {
- if !first_part.contains(&['/', '\\'][..]) {
- let args = command_parts[1..].join(" ");
- return Ok(((*first_part).to_string(), args));
- }
- }
-
- let mut cumulative_path = Vec::new();
-
- // Lastly, iterate over the command until a valid file path is found.
- for (part_index, &part) in command_parts.iter().enumerate() {
- cumulative_path.push(part);
-
- if Path::new(&cumulative_path.join(" ")).is_file() {
- return Ok((
- cumulative_path.join(" "),
- command_parts[part_index + 1..].join(" "),
- ));
- }
- }
-
- anyhow::bail!("Program path is not valid for command '{}'.", command)
- }
-
- /// Runs the specified program with the given arguments.
- pub fn run_command(
- program: &str,
- args: &str,
- hide_window: bool,
- ) -> anyhow::Result<()> {
- let home_dir = home::home_dir()
- .context("Unable to get home directory.")?
- .to_str()
- .context("Invalid home directory.")?
- .to_owned();
-
- // Inlining the wide variables within the `SHELLEXECUTEINFOW` struct
- // causes issues where the pointer is dropped while `ShellExecuteExW`
- // is using it. This is likely a `windows-rs` bug, and we can avoid
- // it by keeping separate variables for the wide strings.
- let program_wide = to_wide(program);
- let args_wide = to_wide(args);
- let home_dir_wide = to_wide(&home_dir);
-
- // Using the built-in `Command::new` function in Rust launches the
- // program as a subprocess. This prevents Windows from cleaning up
- // handles held by our process (e.g. the IPC server port) until the
- // subprocess exits.
- let mut exec_info = SHELLEXECUTEINFOW {
- #[allow(clippy::cast_possible_truncation)]
- cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
- lpFile: PCWSTR(program_wide.as_ptr()),
- lpParameters: PCWSTR(args_wide.as_ptr()),
- lpDirectory: PCWSTR(home_dir_wide.as_ptr()),
- nShow: if hide_window { SW_HIDE } else { SW_NORMAL }.0 as _,
- fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC,
- ..Default::default()
- };
-
- unsafe { ShellExecuteExW(&raw mut exec_info) }?;
- Ok(())
- }
-
- pub fn show_error_dialog(title: &str, message: &str) {
- let title_wide = to_wide(title);
- let message_wide = to_wide(message);
-
- unsafe {
- MessageBoxW(
- None,
- PCWSTR(message_wide.as_ptr()),
- PCWSTR(title_wide.as_ptr()),
- MB_ICONERROR | MB_OK | MB_SYSTEMMODAL,
- );
- }
- }
-}
-
-/// Utility function to convert a string to a null-terminated wide string.
-fn to_wide(string: &str) -> Vec<u16> {
- string.encode_utf16().chain(Some(0)).collect()
-}
diff --git a/packages/wm-platform/src/platform_event.rs b/packages/wm-platform/src/platform_event.rs
new file mode 100644
index 00000000..39b6d88e
--- /dev/null
+++ b/packages/wm-platform/src/platform_event.rs
@@ -0,0 +1,223 @@
+use super::NativeWindow;
+use crate::{
+ platform_impl::WindowEventNotificationInner, Keybinding, MouseEventKind,
+ Point, WindowId,
+};
+
+#[derive(Clone, Debug)]
+pub enum PlatformEvent {
+ Window(WindowEvent),
+ Keybinding(KeybindingEvent),
+ Mouse(MouseEvent),
+ DisplaySettingsChanged,
+}
+
+#[derive(Clone, Debug)]
+pub enum WindowEvent {
+ /// Window gained focus.
+ Focused {
+ window: NativeWindow,
+ notification: WindowEventNotification,
+ },
+
+ /// Window was hidden.
+ Hidden {
+ window: NativeWindow,
+ notification: WindowEventNotification,
+ },
+
+ /// Size or position of window has changed.
+ ///
+ /// `is_interactive_start` and `is_interactive_end` indicate whether the
+ /// move or resize was initiated via manual interaction with the
+ /// window's drag handles.
+ ///
+ /// # Platform-specific
+ ///
+ /// - **Windows**: Corresponds to `EVENT_OBJECT_LOCATIONCHANGE`,
+ /// `EVENT_SYSTEM_MOVESIZESTART`, and `EVENT_SYSTEM_MOVESIZEEND`.
+ /// - **macOS**: Corresponds to `AXWindowMoved` and `AXWindowResized`.
+ /// The `is_interactive_start` and `is_interactive_end` flags are
+ /// always `false`.
+ MovedOrResized {
+ window: NativeWindow,
+ is_interactive_start: bool,
+ is_interactive_end: bool,
+ notification: WindowEventNotification,
+ },
+
+ /// Window was minimized.
+ Minimized {
+ window: NativeWindow,
+ notification: WindowEventNotification,
+ },
+
+ /// Window was restored from minimized state.
+ MinimizeEnded {
+ window: NativeWindow,
+ notification: WindowEventNotification,
+ },
+
+ /// Window became visible.
+ Shown {
+ window: NativeWindow,
+ notification: WindowEventNotification,
+ },
+
+ /// Window title changed.
+ TitleChanged {
+ window: NativeWindow,
+ notification: WindowEventNotification,
+ },
+
+ /// Window was destroyed.
+ Destroyed {
+ window_id: WindowId,
+ notification: WindowEventNotification,
+ },
+}
+
+impl WindowEvent {
+ /// Get the window handle if available (not available for
+ /// `WindowEvent::Destroyed`).
+ #[must_use]
+ pub fn window(&self) -> Option<&NativeWindow> {
+ match self {
+ Self::Focused { window, .. }
+ | Self::Hidden { window, .. }
+ | Self::MovedOrResized { window, .. }
+ | Self::Minimized { window, .. }
+ | Self::MinimizeEnded { window, .. }
+ | Self::Shown { window, .. }
+ | Self::TitleChanged { window, .. } => Some(window),
+ Self::Destroyed { .. } => None,
+ }
+ }
+
+ /// Returns the platform-specific window event notification.
+ #[must_use]
+ pub fn notification(&self) -> &WindowEventNotification {
+ match self {
+ Self::Focused { notification, .. }
+ | Self::Hidden { notification, .. }
+ | Self::MovedOrResized { notification, .. }
+ | Self::Minimized { notification, .. }
+ | Self::MinimizeEnded { notification, .. }
+ | Self::Shown { notification, .. }
+ | Self::TitleChanged { notification, .. }
+ | Self::Destroyed { notification, .. } => notification,
+ }
+ }
+}
+
+/// Platform-specific window event notification.
+///
+/// Some events are "synthetic" and do not have a corresponding
+/// notification (represented by `None`).
+///
+/// Synthetic events can occur when:
+/// * On macOS, `WindowEvent::Shown` is emitted for new visible windows
+/// even if a different notification is received first.
+#[derive(Clone, Debug)]
+pub struct WindowEventNotification(
+ pub Option<WindowEventNotificationInner>,
+);
+
+#[derive(Clone, Debug)]
+pub struct KeybindingEvent(pub Keybinding);
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum MouseButton {
+ Left,
+ Right,
+}
+
+/// Tracks which mouse buttons are currently pressed.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct PressedButtons {
+ left: bool,
+ right: bool,
+}
+
+impl PressedButtons {
+ /// Returns whether the given button is currently pressed.
+ #[must_use]
+ pub fn contains(&self, button: &MouseButton) -> bool {
+ match button {
+ MouseButton::Left => self.left,
+ MouseButton::Right => self.right,
+ }
+ }
+
+ /// Updates button state based on a mouse event.
+ pub(crate) fn update(&mut self, event: MouseEventKind) {
+ match event {
+ MouseEventKind::LeftButtonDown => self.left = true,
+ MouseEventKind::LeftButtonUp => self.left = false,
+ MouseEventKind::RightButtonDown => self.right = true,
+ MouseEventKind::RightButtonUp => self.right = false,
+ MouseEventKind::Move => {}
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub enum MouseEvent {
+ /// Mouse cursor moved.
+ Move {
+ position: Point,
+ pressed_buttons: PressedButtons,
+ /// Window under cursor.
+ ///
+ /// # Platform-specific
+ ///
+ /// - **macOS**: Sourced from the `CGEvent` field. Unreliable; often
+ /// `None`, with the real window ID appearing sporadically.
+ /// - **Windows**: Always `None`.
+ window_below_cursor: Option<WindowId>,
+ },
+
+ /// A mouse button was pressed.
+ ButtonDown {
+ position: Point,
+ button: MouseButton,
+ pressed_buttons: PressedButtons,
+ },
+
+ /// A mouse button was released.
+ ButtonUp {
+ position: Point,
+ button: MouseButton,
+ pressed_buttons: PressedButtons,
+ },
+}
+
+impl MouseEvent {
+ /// Returns the cursor position at the time of the event.
+ ///
+ /// `0,0` is the top-left corner of the primary monitor.
+ #[must_use]
+ pub fn position(&self) -> &Point {
+ match self {
+ Self::Move { position, .. }
+ | Self::ButtonDown { position, .. }
+ | Self::ButtonUp { position, .. } => position,
+ }
+ }
+
+ /// Returns which mouse buttons were pressed at the time of the event.
+ #[must_use]
+ pub fn pressed_buttons(&self) -> &PressedButtons {
+ match self {
+ Self::Move {
+ pressed_buttons, ..
+ }
+ | Self::ButtonDown {
+ pressed_buttons, ..
+ }
+ | Self::ButtonUp {
+ pressed_buttons, ..
+ } => pressed_buttons,
+ }
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/application.rs b/packages/wm-platform/src/platform_impl/macos/application.rs
new file mode 100644
index 00000000..c2847862
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/application.rs
@@ -0,0 +1,185 @@
+use std::sync::Arc;
+
+use objc2::rc::Retained;
+use objc2_app_kit::{
+ NSApplicationActivationPolicy, NSRunningApplication, NSWorkspace,
+};
+use objc2_application_services::AXUIElement;
+use objc2_core_foundation::{CFArray, CFRetained};
+use objc2_foundation::NSString;
+
+use crate::{
+ platform_impl::{ffi, AXUIElementExt, NativeWindow},
+ Dispatcher, ThreadBound, WindowId,
+};
+
+pub type ProcessId = i32;
+
+/// Represents a running macOS application.
+#[derive(Clone, Debug)]
+pub struct Application {
+ pub(crate) pid: ProcessId,
+ pub(crate) dispatcher: Dispatcher,
+ pub(crate) ns_app: Retained<NSRunningApplication>,
+ pub(crate) ax_element: Arc<ThreadBound<CFRetained<AXUIElement>>>,
+}
+
+impl Application {
+ /// Creates an instance of `Application`.
+ pub(crate) fn new(
+ ns_app: Retained<NSRunningApplication>,
+ dispatcher: Dispatcher,
+ ) -> Self {
+ let pid = unsafe { ns_app.processIdentifier() };
+ let ax_element = Arc::new(ThreadBound::new(
+ // Creation of `AXUIElement` for an application does not fail even
+ // if the PID is invalid. Instead, subsequent operations on
+ // the returned `AXUIElement` will error.
+ unsafe { AXUIElement::new_application(pid) },
+ dispatcher.clone(),
+ ));
+
+ Self {
+ pid,
+ dispatcher,
+ ns_app,
+ ax_element,
+ }
+ }
+
+ pub fn focused_window(
+ &self,
+ ) -> crate::Result<Option<crate::NativeWindow>> {
+ self.ax_element.with(|el| {
+ let focused_window =
+ el.get_attribute::<AXUIElement>("AXFocusedWindow");
+
+ focused_window.map(|window_el| {
+ let window_id = WindowId::from_window_element(&window_el);
+ let window_el =
+ ThreadBound::new(window_el, self.dispatcher.clone());
+ Some(NativeWindow::new(window_id, window_el, self.clone()).into())
+ })
+ })?
+ }
+
+ pub fn windows(&self) -> crate::Result<Vec<crate::NativeWindow>> {
+ self.ax_element.with(|el| {
+ let windows = el.get_attribute::<CFArray<AXUIElement>>("AXWindows");
+
+ windows.map(|windows| {
+ windows
+ .iter()
+ .map(|window_el| {
+ let window_id = WindowId::from_window_element(&window_el);
+ let window_el =
+ ThreadBound::new(window_el, self.dispatcher.clone());
+ NativeWindow::new(window_id, window_el, self.clone()).into()
+ })
+ .collect()
+ })
+ })?
+ }
+
+ pub fn psn(&self) -> crate::Result<ffi::ProcessSerialNumber> {
+ let mut psn = ffi::ProcessSerialNumber::default();
+
+ if unsafe { ffi::GetProcessForPID(self.pid, &raw mut psn) } != 0 {
+ return Err(crate::Error::Platform(
+ "Failed to get process serial number.".to_string(),
+ ));
+ }
+
+ Ok(psn)
+ }
+
+ pub fn bundle_id(&self) -> Option<String> {
+ unsafe { self.ns_app.bundleIdentifier() }
+ .map(|ns_string| ns_string.to_string())
+ }
+
+ pub fn process_name(&self) -> Option<String> {
+ unsafe { self.ns_app.localizedName() }
+ .map(|ns_string| ns_string.to_string())
+ }
+
+ /// Whether the application is an XPC service.
+ ///
+ /// Windows from XPC services are non-standard and cannot be managed.
+ /// Though XPC services are not intended to accept UI interaction, some
+ /// of Apple's own services have windows (e.g. `QuickLookUIService`,
+ /// used for Finder previews).
+ pub fn is_xpc(&self) -> crate::Result<bool> {
+ let psn = self.psn()?;
+
+ #[allow(clippy::cast_possible_truncation)]
+ let mut process_info = {
+ let mut info = ffi::ProcessInfo::default();
+ info.info_length = std::mem::size_of::<ffi::ProcessInfo>() as u32;
+ info
+ };
+
+ if unsafe {
+ ffi::GetProcessInformation(&raw const psn, &raw mut process_info)
+ } != 0
+ {
+ return Err(crate::Error::Platform(
+ "Failed to get process information.".to_string(),
+ ));
+ }
+
+ Ok(process_info.r#type.to_be_bytes() == *b"XPC!")
+ }
+
+ pub fn activation_policy(&self) -> NSApplicationActivationPolicy {
+ unsafe { self.ns_app.activationPolicy() }
+ }
+
+ /// Whether the application should be observed.
+ pub(crate) fn should_observe(&self) -> bool {
+ if self.activation_policy()
+ == NSApplicationActivationPolicy::Prohibited
+ {
+ return false;
+ }
+
+ !self.is_xpc().unwrap_or(false)
+ }
+
+ pub(crate) fn is_hidden(&self) -> bool {
+ unsafe { self.ns_app.isHidden() }
+ }
+}
+
+pub(crate) fn all_applications(
+ dispatcher: &Dispatcher,
+) -> crate::Result<Vec<Application>> {
+ dispatcher.dispatch_sync(|| {
+ let running_apps =
+ unsafe { NSWorkspace::sharedWorkspace().runningApplications() };
+
+ running_apps
+ .iter()
+ .map(|app| Application::new(app, dispatcher.clone()))
+ .collect()
+ })
+}
+
+pub(crate) fn application_for_bundle_id(
+ bundle_id: &str,
+ dispatcher: &Dispatcher,
+) -> crate::Result<Option<Application>> {
+ let bundle_id = bundle_id.to_owned();
+ dispatcher.dispatch_sync(|| {
+ let apps = unsafe {
+ NSRunningApplication::runningApplicationsWithBundleIdentifier(
+ &NSString::from_str(&bundle_id),
+ )
+ };
+
+ apps
+ .into_iter()
+ .next()
+ .map(|app| Application::new(app, dispatcher.clone()))
+ })
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/application_observer.rs b/packages/wm-platform/src/platform_impl/macos/application_observer.rs
new file mode 100644
index 00000000..0607c652
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/application_observer.rs
@@ -0,0 +1,386 @@
+use std::{
+ ptr::NonNull,
+ sync::{Arc, Mutex},
+};
+
+use objc2_application_services::{AXError, AXObserver, AXUIElement};
+use objc2_core_foundation::{
+ kCFRunLoopDefaultMode, CFRetained, CFRunLoop, CFRunLoopSource, CFString,
+};
+use tokio::sync::mpsc;
+
+use crate::{
+ platform_impl::{
+ Application, NativeWindow, ProcessId, WindowEventNotificationInner,
+ },
+ NativeWindowExtMacOs, ThreadBound, WindowEvent, WindowId,
+};
+
+/// Notifications to register for the `AXUIElement` of an application.
+const AX_APP_NOTIFICATIONS: &[&str] =
+ &["AXFocusedWindowChanged", "AXWindowCreated"];
+
+/// Notifications to register for the `AXUIElement` of a window.
+const AX_WINDOW_NOTIFICATIONS: &[&str] = &[
+ "AXTitleChanged",
+ "AXUIElementDestroyed",
+ "AXWindowMoved",
+ "AXWindowResized",
+ "AXWindowDeminiaturized",
+ "AXWindowMiniaturized",
+];
+
+/// Context passed to the application event callback.
+#[derive(Debug)]
+struct ApplicationEventContext {
+ application: Application,
+ events_tx: mpsc::UnboundedSender<WindowEvent>,
+ app_windows: Arc<Mutex<Vec<crate::NativeWindow>>>,
+ observer: CFRetained<AXObserver>,
+}
+
+/// Represents an accessibility observer for a specific application.
+#[derive(Debug)]
+pub(crate) struct ApplicationObserver {
+ pub(crate) pid: ProcessId,
+ app_windows: Arc<Mutex<Vec<crate::NativeWindow>>>,
+ events_tx: mpsc::UnboundedSender<WindowEvent>,
+ _observer: CFRetained<AXObserver>,
+ observer_source: CFRetained<CFRunLoopSource>,
+}
+
+// TODO: Remove this.
+unsafe impl Send for ApplicationObserver {}
+
+impl ApplicationObserver {
+ /// Creates a new `ApplicationObserver` for the given application.
+ ///
+ /// If `is_startup` is `true`, the observer will not emit
+ /// `WindowEvent::Shown` for windows already running on startup.
+ pub fn new(
+ app: &Application,
+ events_tx: mpsc::UnboundedSender<WindowEvent>,
+ is_startup: bool,
+ ) -> crate::Result<Self> {
+ let observer = unsafe {
+ let mut observer = std::ptr::null_mut();
+
+ let result = AXObserver::create(
+ app.pid,
+ Some(Self::window_event_callback),
+ // SAFETY: Stack address of `observer` is guaranteed to be
+ // non-null.
+ NonNull::new(&raw mut observer).unwrap(),
+ );
+
+ if result != AXError::Success {
+ return Err(crate::Error::Accessibility(
+ "AXObserverCreate".to_string(),
+ result.0,
+ ));
+ }
+
+ CFRetained::retain(NonNull::new(observer).ok_or_else(|| {
+ crate::Error::InvalidPointer("AXObserver is null.".to_string())
+ })?)
+ };
+
+ let app_windows = Arc::new(Mutex::new(app.windows()?));
+ let context = Box::into_raw(Box::new(ApplicationEventContext {
+ application: app.clone(),
+ events_tx: events_tx.clone(),
+ app_windows: app_windows.clone(),
+ observer: observer.clone(),
+ }));
+
+ let runloop =
+ CFRunLoop::current().ok_or(crate::Error::EventLoopStopped)?;
+
+ let observer_source = unsafe { observer.run_loop_source() };
+ runloop.add_source(Some(&observer_source), unsafe {
+ kCFRunLoopDefaultMode
+ });
+
+ // Register for all window notifications.
+ // TODO: Remove from runloop if registration fails.
+ Self::register_app_notifications(app, &observer, context)?;
+
+ // Emit `WindowEvent::Shown` for all existing windows.
+ for window in app_windows.lock().unwrap().iter() {
+ if let Err(err) =
+ Self::register_window_notifications(window, &observer, context)
+ {
+ tracing::warn!(
+ "Failed to register window notifications for PID {}: {}",
+ app.pid,
+ err
+ );
+ }
+
+ // Don't emit `WindowEvent::Shown` for windows that are already
+ // running on startup.
+ if !is_startup {
+ if let Err(err) = events_tx.send(WindowEvent::Shown {
+ window: window.clone(),
+ notification: crate::WindowEventNotification(None),
+ }) {
+ tracing::warn!(
+ "Failed to send window event for PID {}: {}",
+ app.pid,
+ err
+ );
+ }
+ }
+ }
+
+ Ok(Self {
+ pid: app.pid,
+ app_windows,
+ events_tx,
+ _observer: observer,
+ observer_source,
+ })
+ }
+
+ fn register_app_notifications(
+ app: &Application,
+ observer: &CFRetained<AXObserver>,
+ context: *mut ApplicationEventContext,
+ ) -> crate::Result<()> {
+ for notification in AX_APP_NOTIFICATIONS {
+ unsafe {
+ let notification_cfstr = CFString::from_static_str(notification);
+ let result = observer.add_notification(
+ app.ax_element.get_ref()?,
+ &notification_cfstr,
+ context.cast::<std::ffi::c_void>(),
+ );
+
+ if result != AXError::Success {
+ return Err(crate::Error::Platform(format!(
+ "Failed to add notification {} for PID {}: {:?}",
+ notification, app.pid, result
+ )));
+ }
+ }
+ }
+
+ Ok(())
+ }
+
+ fn register_window_notifications(
+ window: &crate::NativeWindow,
+ observer: &CFRetained<AXObserver>,
+ context: *mut ApplicationEventContext,
+ ) -> crate::Result<()> {
+ for notification in AX_WINDOW_NOTIFICATIONS {
+ unsafe {
+ let notification_cfstr = CFString::from_static_str(notification);
+ let result = observer.add_notification(
+ window.ax_ui_element().get_ref()?,
+ &notification_cfstr,
+ context.cast::<std::ffi::c_void>(),
+ );
+
+ if result != AXError::Success {
+ return Err(crate::Error::Platform(format!(
+ "Failed to add notification {} for window {}: {:?}",
+ notification,
+ window.id().0,
+ result
+ )));
+ }
+ }
+ }
+
+ Ok(())
+ }
+
+ pub(crate) fn emit_all_windows_destroyed(&self) {
+ for window in self.app_windows.lock().unwrap().iter() {
+ if let Err(err) = self.events_tx.send(WindowEvent::Destroyed {
+ window_id: window.id(),
+ notification: crate::WindowEventNotification(None),
+ }) {
+ tracing::warn!(
+ "Failed to send window event for PID {}: {}",
+ self.pid,
+ err
+ );
+ }
+ }
+ }
+
+ pub(crate) fn emit_all_windows_hidden(&self) {
+ for window in self.app_windows.lock().unwrap().iter() {
+ if let Err(err) = self.events_tx.send(WindowEvent::Hidden {
+ window: window.clone(),
+ notification: crate::WindowEventNotification(None),
+ }) {
+ tracing::warn!(
+ "Failed to send window event for PID {}: {}",
+ self.pid,
+ err
+ );
+ }
+ }
+ }
+
+ pub(crate) fn emit_all_windows_shown(&self) {
+ for window in self.app_windows.lock().unwrap().iter() {
+ if let Err(err) = self.events_tx.send(WindowEvent::Shown {
+ window: window.clone(),
+ notification: crate::WindowEventNotification(None),
+ }) {
+ tracing::warn!(
+ "Failed to send window event for PID {}: {}",
+ self.pid,
+ err
+ );
+ }
+ }
+ }
+
+ /// Callback function for accessibility window events.
+ #[allow(clippy::too_many_lines)]
+ unsafe extern "C-unwind" fn window_event_callback(
+ _observer: NonNull<AXObserver>,
+ element: NonNull<AXUIElement>,
+ notification_name: NonNull<CFString>,
+ context: *mut std::ffi::c_void,
+ ) {
+ if context.is_null() {
+ tracing::error!("Window event callback received null context.");
+ return;
+ }
+
+ let context = &mut *context.cast::<ApplicationEventContext>();
+ let ax_element = unsafe { CFRetained::retain(element) };
+ let notification = WindowEventNotificationInner {
+ name: notification_name.as_ref().to_string(),
+ ax_element_ptr: element.as_ptr().cast::<std::ffi::c_void>(),
+ };
+
+ tracing::debug!(
+ "Received window event: {} for PID: {}",
+ notification.name,
+ context.application.pid
+ );
+
+ let found_window = {
+ let app_windows = context.app_windows.lock().unwrap();
+
+ app_windows
+ .iter()
+ .find(|window| {
+ window.ax_ui_element().get_ref().ok() == Some(&ax_element)
+ })
+ .cloned()
+ };
+
+ if notification.name.as_str() == "AXUIElementDestroyed" {
+ if let Some(window) = &found_window {
+ context
+ .app_windows
+ .lock()
+ .unwrap()
+ .retain(|w| w.id() != window.id());
+
+ if let Err(err) = context.events_tx.send(WindowEvent::Destroyed {
+ window_id: window.id(),
+ notification: crate::WindowEventNotification(Some(notification)),
+ }) {
+ tracing::warn!(
+ "Failed to send window event for PID {}: {}",
+ context.application.pid,
+ err
+ );
+ }
+ }
+
+ return;
+ }
+
+ let is_new_window = found_window.is_none();
+ let window = found_window.unwrap_or_else(|| {
+ let window_id = WindowId::from_window_element(&ax_element);
+ let ax_element = ThreadBound::new(
+ ax_element,
+ context.application.dispatcher.clone(),
+ );
+ NativeWindow::new(window_id, ax_element, context.application.clone())
+ .into()
+ });
+
+ if is_new_window {
+ context.app_windows.lock().unwrap().push(window.clone());
+ let _ = Self::register_window_notifications(
+ &window,
+ &context.observer.clone(),
+ context,
+ );
+
+ if let Err(err) = context.events_tx.send(WindowEvent::Shown {
+ window: window.clone(),
+ notification: crate::WindowEventNotification(Some(
+ notification.clone(),
+ )),
+ }) {
+ tracing::warn!(
+ "Failed to send window event for PID {}: {}",
+ context.application.pid,
+ err
+ );
+ }
+ }
+
+ let window_event = match notification.name.as_str() {
+ "AXFocusedWindowChanged" => WindowEvent::Focused {
+ window,
+ notification: crate::WindowEventNotification(Some(notification)),
+ },
+ "AXWindowMoved" | "AXWindowResized" => WindowEvent::MovedOrResized {
+ window,
+ is_interactive_start: false,
+ is_interactive_end: false,
+ notification: crate::WindowEventNotification(Some(notification)),
+ },
+ "AXWindowMiniaturized" => WindowEvent::Minimized {
+ window,
+ notification: crate::WindowEventNotification(Some(notification)),
+ },
+ "AXWindowDeminiaturized" => WindowEvent::MinimizeEnded {
+ window,
+ notification: crate::WindowEventNotification(Some(notification)),
+ },
+ "AXTitleChanged" => WindowEvent::TitleChanged {
+ window,
+ notification: crate::WindowEventNotification(Some(notification)),
+ },
+ _ => {
+ tracing::debug!(
+ "Unhandled window notification: {} for PID: {}",
+ notification.name,
+ context.application.pid
+ );
+ return;
+ }
+ };
+
+ if let Err(err) = context.events_tx.send(window_event) {
+ tracing::warn!(
+ "Failed to send window event for PID {}: {}",
+ context.application.pid,
+ err
+ );
+ }
+ }
+}
+
+impl Drop for ApplicationObserver {
+ fn drop(&mut self) {
+ // Invalidate the runloop source. This is thread-safe and is OK to call
+ // after the run loop is stopped.
+ self.observer_source.invalidate();
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/ax_ui_element.rs b/packages/wm-platform/src/platform_impl/macos/ax_ui_element.rs
new file mode 100644
index 00000000..44b90307
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/ax_ui_element.rs
@@ -0,0 +1,108 @@
+use std::ptr::{self, NonNull};
+
+pub use objc2_application_services::{AXError, AXUIElement};
+use objc2_core_foundation::{CFRetained, CFString, CFType};
+
+use crate::Error;
+
+/// Extension trait for [`AXUIElement`].
+pub trait AXUIElementExt {
+ /// Retrieves the value of an accessibility attribute.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if:
+ /// - The accessibility operation fails (e.g. invalid attribute name).
+ /// - The attribute value cannot be cast to the requested type.
+ fn get_attribute<T: objc2_core_foundation::Type>(
+ &self,
+ attribute: &str,
+ ) -> crate::Result<CFRetained<T>>;
+
+ /// Sets the value of an accessibility attribute.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the accessibility operation fails.
+ fn set_attribute<T: objc2_core_foundation::Type + AsRef<CFType>>(
+ &self,
+ attribute: &str,
+ value: &CFRetained<T>,
+ ) -> crate::Result<()>;
+}
+
+impl AXUIElementExt for AXUIElement {
+ fn get_attribute<T: objc2_core_foundation::Type>(
+ &self,
+ attribute: &str,
+ ) -> crate::Result<CFRetained<T>> {
+ let mut value: *const CFType = ptr::null();
+
+ let result = unsafe {
+ self.copy_attribute_value(
+ &CFString::from_str(attribute),
+ // SAFETY: Stack address of `value` is guaranteed to be
+ // non-null.
+ NonNull::new(&raw mut value).unwrap(),
+ )
+ };
+
+ if result != AXError::Success {
+ return Err(Error::Accessibility(attribute.to_string(), result.0));
+ }
+
+ NonNull::new(value.cast_mut())
+ .map(|ptr| unsafe { CFRetained::from_raw(ptr.cast()) })
+ .ok_or_else(|| {
+ Error::InvalidPointer(
+ "copy_attribute_value returned success but null pointer"
+ .to_string(),
+ )
+ })
+ }
+
+ fn set_attribute<T: objc2_core_foundation::Type + AsRef<CFType>>(
+ &self,
+ attribute: &str,
+ value: &CFRetained<T>,
+ ) -> crate::Result<()> {
+ let cf_attribute = CFString::from_str(attribute);
+ let result =
+ unsafe { self.set_attribute_value(&cf_attribute, value.as_ref()) };
+
+ if result != AXError::Success {
+ return Err(Error::Accessibility(attribute.to_string(), result.0));
+ }
+
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use objc2_core_foundation::CFString;
+
+ use super::*;
+
+ #[test]
+ fn get_attribute_invalid_attribute_is_err() {
+ let pid = i32::try_from(std::process::id()).expect("pid overflow");
+
+ let el = unsafe { AXUIElement::new_application(pid) };
+ let result =
+ el.get_attribute::<CFString>("AXDefinitelyNotARealAttribute");
+
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn set_attribute_invalid_attribute_is_err() {
+ let pid = i32::try_from(std::process::id()).expect("pid overflow");
+
+ let el = unsafe { AXUIElement::new_application(pid) };
+ let value = CFString::from_str("dummy");
+ let result = el.set_attribute("AXDefinitelyNotARealAttribute", &value);
+
+ assert!(result.is_err());
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/ax_value.rs b/packages/wm-platform/src/platform_impl/macos/ax_value.rs
new file mode 100644
index 00000000..3c0f5a4b
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/ax_value.rs
@@ -0,0 +1,122 @@
+use std::{ffi::c_void, mem::MaybeUninit, ptr::NonNull};
+
+use objc2_application_services::{AXValue, AXValueType};
+use objc2_core_foundation::{
+ CFRange, CFRetained, CGPoint, CGRect, CGSize,
+};
+
+/// Trait for types that can be converted to and from `AXValue`.
+pub trait AXValueTypeMarker: Sized + Copy {
+ /// The `AXValueType` constant for this type.
+ const AX_TYPE: AXValueType;
+}
+
+impl AXValueTypeMarker for CGPoint {
+ const AX_TYPE: AXValueType = AXValueType::CGPoint;
+}
+
+impl AXValueTypeMarker for CGSize {
+ const AX_TYPE: AXValueType = AXValueType::CGSize;
+}
+
+impl AXValueTypeMarker for CGRect {
+ const AX_TYPE: AXValueType = AXValueType::CGRect;
+}
+
+impl AXValueTypeMarker for CFRange {
+ const AX_TYPE: AXValueType = AXValueType::CFRange;
+}
+
+/// Extension trait for [`AXValue`].
+pub trait AXValueExt {
+ /// Creates a new `AXValue` from the given value.
+ ///
+ /// This is a wrapper over `AXValue::new` from `objc2`.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the `AXValue` creation fails.
+ fn new_strict<T: AXValueTypeMarker>(
+ val: &T,
+ ) -> crate::Result<CFRetained<AXValue>>;
+
+ /// Extracts the value from this `AXValue`.
+ ///
+ /// This is a wrapper over `AXValue::value` from `objc2`.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if:
+ /// - The `AXValue` type doesn't match the requested type `T`.
+ /// - The accessibility framework fails to extract the value.
+ fn value_strict<T: AXValueTypeMarker>(&self) -> crate::Result<T>;
+}
+
+impl AXValueExt for AXValue {
+ fn new_strict<T: AXValueTypeMarker>(
+ val: &T,
+ ) -> crate::Result<CFRetained<AXValue>> {
+ let ptr = NonNull::new(std::ptr::from_ref::<T>(val) as *mut c_void)
+ .ok_or_else(|| {
+ crate::Error::InvalidPointer("Value pointer is null".to_string())
+ })?;
+
+ unsafe { AXValue::new(T::AX_TYPE, ptr) }.ok_or_else(|| {
+ crate::Error::AXValueCreation(format!(
+ "Failed to create AXValue for type with AX_TYPE {:?}",
+ T::AX_TYPE
+ ))
+ })
+ }
+
+ fn value_strict<T: AXValueTypeMarker>(&self) -> crate::Result<T> {
+ let mut value = MaybeUninit::<T>::uninit();
+ let ptr = NonNull::new(value.as_mut_ptr().cast::<c_void>())
+ .ok_or_else(|| {
+ crate::Error::InvalidPointer(
+ "Value buffer pointer is null".to_string(),
+ )
+ })?;
+
+ let success = unsafe { self.value(T::AX_TYPE, ptr) };
+
+ if success {
+ Ok(unsafe { value.assume_init() })
+ } else {
+ Err(crate::Error::AXValueCreation(format!(
+ "Failed to extract value from AXValue for type with AX_TYPE {:?}",
+ T::AX_TYPE
+ )))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_ax_value_creation_and_extraction() {
+ let point = CGPoint { x: 10.0, y: 20.0 };
+ let ax_value =
+ AXValue::new_strict(&point).expect("Failed to create AXValue.");
+
+ let extracted_point: CGPoint = ax_value
+ .value_strict()
+ .expect("Failed to extract value from AXValue.");
+
+ assert!((point.x - extracted_point.x).abs() < f64::EPSILON);
+ assert!((point.y - extracted_point.y).abs() < f64::EPSILON);
+ }
+
+ #[test]
+ fn test_ax_value_wrong_type_extraction() {
+ let point = CGPoint { x: 10.0, y: 20.0 };
+ let ax_value =
+ AXValue::new_strict(&point).expect("Failed to create AXValue.");
+
+ // Try to extract as `CGSize` instead of `CGPoint`.
+ let result = ax_value.value_strict::<CGSize>();
+ assert!(result.is_err());
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/display.rs b/packages/wm-platform/src/platform_impl/macos/display.rs
new file mode 100644
index 00000000..6c53ea78
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/display.rs
@@ -0,0 +1,484 @@
+use std::sync::Arc;
+
+use objc2::{rc::Retained, MainThreadMarker};
+use objc2_app_kit::NSScreen;
+use objc2_core_foundation::{CFRetained, CFUUID};
+use objc2_core_graphics::{
+ CGDirectDisplayID, CGDisplayBounds, CGDisplayCopyDisplayMode,
+ CGDisplayMirrorsDisplay, CGDisplayMode, CGDisplayRotation, CGError,
+ CGGetActiveDisplayList, CGGetOnlineDisplayList, CGMainDisplayID,
+};
+use objc2_foundation::{ns_string, NSNumber, NSRect};
+
+use crate::{
+ platform_impl::ffi, ConnectionState, Dispatcher, DisplayDeviceId,
+ DisplayId, MirroringState, Point, Rect, ThreadBound,
+};
+
+/// Platform-specific implementation of [`Display`].
+#[derive(Clone, Debug)]
+pub(crate) struct Display {
+ cg_display_id: CGDirectDisplayID,
+ ns_screen: Arc<ThreadBound<Retained<NSScreen>>>,
+}
+
+impl Display {
+ /// Creates an instance of `Display`.
+ pub(crate) fn new(
+ ns_screen: ThreadBound<Retained<NSScreen>>,
+ ) -> crate::Result<Self> {
+ let cg_display_id = ns_screen
+ .with(|screen| {
+ let device_description = screen.deviceDescription();
+
+ device_description
+ .objectForKey(ns_string!("NSScreenNumber"))
+ .and_then(|val| {
+ val.downcast_ref::<NSNumber>().map(NSNumber::as_u32)
+ })
+ })?
+ .ok_or(crate::Error::DisplayNotFound)?;
+
+ Ok(Self {
+ cg_display_id,
+ ns_screen: Arc::new(ns_screen),
+ })
+ }
+
+ /// Implements [`Display::id`].
+ pub(crate) fn id(&self) -> DisplayId {
+ DisplayId(self.cg_display_id)
+ }
+
+ /// Implements [`Display::name`].
+ pub(crate) fn name(&self) -> crate::Result<String> {
+ self.ns_screen.with(|screen| {
+ let name = unsafe { screen.localizedName() };
+ Ok(name.to_string())
+ })?
+ }
+
+ /// Implements [`Display::bounds`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn bounds(&self) -> crate::Result<Rect> {
+ let cg_rect = unsafe { CGDisplayBounds(self.cg_display_id) };
+
+ #[allow(clippy::cast_possible_truncation)]
+ Ok(Rect::from_xy(
+ cg_rect.origin.x as i32,
+ cg_rect.origin.y as i32,
+ cg_rect.size.width as i32,
+ cg_rect.size.height as i32,
+ ))
+ }
+
+ /// Implements [`Display::working_area`].
+ pub(crate) fn working_area(&self) -> crate::Result<Rect> {
+ let primary_display_bounds = {
+ let bounds = unsafe { CGDisplayBounds(CGMainDisplayID()) };
+
+ #[allow(clippy::cast_possible_truncation)]
+ Rect::from_xy(
+ bounds.origin.x as i32,
+ bounds.origin.y as i32,
+ bounds.size.width as i32,
+ bounds.size.height as i32,
+ )
+ };
+
+ self.ns_screen.with(|screen| {
+ // Convert `NSScreen.visibleFrame` into the same coordinate space as
+ // `CGDisplayBounds`.
+ Ok(appkit_rect_to_cg_rect(
+ screen.visibleFrame(),
+ &primary_display_bounds,
+ ))
+ })?
+ }
+
+ /// Implements [`Display::scale_factor`].
+ pub(crate) fn scale_factor(&self) -> crate::Result<f32> {
+ #[allow(clippy::cast_possible_truncation)]
+ self
+ .ns_screen
+ .with(|screen| screen.backingScaleFactor() as f32)
+ }
+
+ /// Implements [`Display::dpi`].
+ pub(crate) fn dpi(&self) -> crate::Result<u32> {
+ let scale_factor = self.scale_factor()?;
+
+ #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
+ Ok((72.0 * scale_factor) as u32)
+ }
+
+ /// Implements [`Display::is_primary`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn is_primary(&self) -> crate::Result<bool> {
+ let main_display_id = unsafe { CGMainDisplayID() };
+ Ok(self.cg_display_id == main_display_id)
+ }
+
+ /// Implements [`Display::devices`].
+ pub(crate) fn devices(
+ &self,
+ ) -> crate::Result<Vec<crate::DisplayDevice>> {
+ let main_device = DisplayDevice::new(
+ self.cg_display_id,
+ cg_display_uuid(self.cg_display_id)?,
+ );
+
+ // TODO: Get devices that are mirroring this display as well.
+ Ok(vec![main_device.into()])
+ }
+
+ /// Implements [`Display::main_device`].
+ pub(crate) fn main_device(&self) -> crate::Result<crate::DisplayDevice> {
+ self
+ .devices()?
+ .into_iter()
+ .find(|device| {
+ matches!(
+ device.mirroring_state(),
+ Ok(None | Some(MirroringState::Source))
+ )
+ })
+ .ok_or(crate::Error::DisplayNotFound)
+ }
+
+ /// Implements [`DisplayExtMacOs::cg_display_id`].
+ pub(crate) fn cg_display_id(&self) -> CGDirectDisplayID {
+ self.cg_display_id
+ }
+
+ /// Implements [`DisplayExtMacOs::ns_screen`].
+ pub(crate) fn ns_screen(&self) -> &ThreadBound<Retained<NSScreen>> {
+ &self.ns_screen
+ }
+}
+
+/// Transforms an AppKit screen rectangle (e.g. `NSScreen.visibleFrame`)
+/// into Core Graphics coordinate space (e.g. `CGDisplayBounds`).
+///
+/// AppKit has (0,0) at the bottom-left corner of the primary display,
+/// whereas Core Graphics has it at the top-left corner. So we can convert
+/// between the two by offsetting the Y-axis by the primary display's
+/// height.
+fn appkit_rect_to_cg_rect(
+ appkit_rect: NSRect,
+ primary_display_bounds: &Rect,
+) -> Rect {
+ let adjusted_y = f64::from(primary_display_bounds.height())
+ - (appkit_rect.origin.y + appkit_rect.size.height);
+
+ #[allow(clippy::cast_possible_truncation)]
+ Rect::from_xy(
+ appkit_rect.origin.x as i32,
+ adjusted_y as i32,
+ appkit_rect.size.width as i32,
+ appkit_rect.size.height as i32,
+ )
+}
+
+impl From<Display> for crate::Display {
+ fn from(display: Display) -> Self {
+ crate::Display { inner: display }
+ }
+}
+
+impl PartialEq for Display {
+ fn eq(&self, other: &Self) -> bool {
+ self.id() == other.id()
+ }
+}
+
+impl Eq for Display {}
+
+/// Platform-specific implementation of [`DisplayDevice`].
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct DisplayDevice {
+ cg_display_id: CGDirectDisplayID,
+ uuid: CFRetained<CFUUID>,
+}
+
+impl DisplayDevice {
+ /// Creates an instance of `DisplayDevice`.
+ #[must_use]
+ pub(crate) fn new(
+ cg_display_id: CGDirectDisplayID,
+ uuid: CFRetained<CFUUID>,
+ ) -> Self {
+ Self {
+ cg_display_id,
+ uuid,
+ }
+ }
+
+ /// Implements [`DisplayDevice::id`].
+ pub(crate) fn id(&self) -> DisplayDeviceId {
+ // SAFETY: Can assume that the `CFUUID` is valid regardless of whether
+ // the underlying display device is still alive.
+ let uuid_string = CFUUID::new_string(None, Some(&self.uuid))
+ .unwrap()
+ .to_string();
+
+ DisplayDeviceId(uuid_string)
+ }
+
+ /// Implements [`DisplayDevice::rotation`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn rotation(&self) -> crate::Result<f32> {
+ #[allow(clippy::cast_possible_truncation)]
+ Ok(unsafe { CGDisplayRotation(self.cg_display_id) } as f32)
+ }
+
+ /// Implements [`DisplayDevice::refresh_rate`].
+ pub(crate) fn refresh_rate(&self) -> crate::Result<f32> {
+ // NOTE: Calling `CGDisplayModeRelease` on cleanup is not needed, since
+ // it's equivalent to `CFRelease` in this case. Ref: https://developer.apple.com/documentation/coregraphics/cgdisplaymoderelease
+ let display_mode =
+ unsafe { CGDisplayCopyDisplayMode(self.cg_display_id) }
+ .ok_or(crate::Error::DisplayModeNotFound)?;
+
+ let refresh_rate =
+ unsafe { CGDisplayMode::refresh_rate(Some(&display_mode)) };
+
+ #[allow(clippy::cast_possible_truncation)]
+ Ok(refresh_rate as f32)
+ }
+
+ /// Implements [`DisplayDevice::is_builtin`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn is_builtin(&self) -> crate::Result<bool> {
+ // TODO: Implement this properly.
+ let main_display_id = unsafe { CGMainDisplayID() };
+ Ok(self.cg_display_id == main_display_id)
+ }
+
+ /// Implements [`DisplayDevice::connection_state`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn connection_state(&self) -> crate::Result<ConnectionState> {
+ let display_mode =
+ unsafe { CGDisplayCopyDisplayMode(self.cg_display_id) };
+
+ // TODO: Implement this properly.
+ if display_mode.is_none() {
+ Ok(ConnectionState::Disconnected)
+ } else {
+ Ok(ConnectionState::Active)
+ }
+ }
+
+ /// Implements [`DisplayDevice::mirroring_state`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn mirroring_state(
+ &self,
+ ) -> crate::Result<Option<MirroringState>> {
+ let mirrored_display =
+ unsafe { CGDisplayMirrorsDisplay(self.cg_display_id) };
+
+ // TODO: Clean this up.
+ if mirrored_display == 0 {
+ // This display is not mirroring another display
+ // Check if another display is mirroring this one by querying active
+ // displays
+ let mut displays: Vec<CGDirectDisplayID> = vec![0; 32];
+ let mut display_count: u32 = 0;
+
+ #[allow(clippy::cast_possible_truncation)]
+ let result = unsafe {
+ CGGetActiveDisplayList(
+ displays.len() as u32,
+ displays.as_mut_ptr(),
+ &raw mut display_count,
+ )
+ };
+
+ if result == CGError::Success {
+ displays.truncate(display_count as usize);
+ for &display_id in &displays {
+ if display_id == self.cg_display_id {
+ continue; // Skip self
+ }
+ let other_mirrored =
+ unsafe { CGDisplayMirrorsDisplay(display_id) };
+ if other_mirrored == self.cg_display_id {
+ // Another display is mirroring this one, so this is the source
+ return Ok(Some(MirroringState::Source));
+ }
+ }
+ }
+ Ok(None)
+ } else {
+ // This display is mirroring another display, so it's a target
+ Ok(Some(MirroringState::Target))
+ }
+ }
+
+ /// Implements [`DisplayDeviceExtMacOs::cg_display_id`].
+ pub(crate) fn cg_display_id(&self) -> CGDirectDisplayID {
+ self.cg_display_id
+ }
+}
+
+impl From<DisplayDevice> for crate::DisplayDevice {
+ fn from(device: DisplayDevice) -> Self {
+ crate::DisplayDevice { inner: device }
+ }
+}
+
+/// Gets the UUID for a display device from its `CGDirectDisplayID`.
+///
+/// This UUID is stable across reboots, whereas `CGDirectDisplayID` is not.
+fn cg_display_uuid(
+ cg_display_id: CGDirectDisplayID,
+) -> crate::Result<CFRetained<CFUUID>> {
+ let ptr =
+ unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(cg_display_id) };
+
+ ptr.map(|ptr| unsafe { CFRetained::from_raw(ptr) }).ok_or(
+ crate::Error::InvalidPointer(
+ "Failed to create UUID for display device".to_string(),
+ ),
+ )
+}
+
+/// Implements [`Dispatcher::displays`].
+pub(crate) fn all_displays(
+ dispatcher: &Dispatcher,
+) -> crate::Result<Vec<crate::Display>> {
+ dispatcher.dispatch_sync(|| {
+ let mtm =
+ MainThreadMarker::new().ok_or(crate::Error::NotMainThread)?;
+
+ let mut displays = Vec::new();
+
+ for screen in NSScreen::screens(mtm) {
+ let ns_screen = ThreadBound::new(screen, dispatcher.clone());
+ displays.push(Display::new(ns_screen)?.into());
+ }
+
+ Ok(displays)
+ })?
+}
+
+/// Implements [`Dispatcher::display_devices`].
+pub(crate) fn all_display_devices(
+ _: &Dispatcher,
+) -> crate::Result<Vec<crate::DisplayDevice>> {
+ let mut cg_display_ids: Vec<CGDirectDisplayID> = vec![0; 32]; // Max 32 displays
+ let mut display_count: u32 = 0;
+
+ #[allow(clippy::cast_possible_truncation)]
+ let result = unsafe {
+ CGGetOnlineDisplayList(
+ cg_display_ids.len() as u32,
+ cg_display_ids.as_mut_ptr(),
+ &raw mut display_count,
+ )
+ };
+
+ if result != CGError::Success {
+ return Err(crate::Error::DisplayEnumerationFailed);
+ }
+
+ cg_display_ids.truncate(display_count as usize);
+
+ cg_display_ids
+ .into_iter()
+ .map(|cg_display_id| {
+ Ok(
+ DisplayDevice::new(cg_display_id, cg_display_uuid(cg_display_id)?)
+ .into(),
+ )
+ })
+ .collect()
+}
+
+/// Implements [`Dispatcher::display_from_point`].
+pub(crate) fn display_from_point(
+ point: &Point,
+ dispatcher: &Dispatcher,
+) -> crate::Result<crate::Display> {
+ let displays = all_displays(dispatcher)?;
+
+ for display in displays {
+ let bounds = display.bounds()?;
+ if bounds.contains_point(point) {
+ return Ok(display);
+ }
+ }
+
+ Err(crate::Error::DisplayNotFound)
+}
+
+/// Implements [`Dispatcher::primary_display`].
+pub(crate) fn primary_display(
+ dispatcher: &Dispatcher,
+) -> crate::Result<crate::Display> {
+ dispatcher.dispatch_sync(|| {
+ let mtm =
+ MainThreadMarker::new().ok_or(crate::Error::NotMainThread)?;
+
+ let ns_screen = ThreadBound::new(
+ NSScreen::mainScreen(mtm).ok_or(crate::Error::DisplayNotFound)?,
+ dispatcher.clone(),
+ );
+
+ Display::new(ns_screen).map(Into::into)
+ })?
+}
+
+/// Implements [`Dispatcher::nearest_display`].
+///
+/// NOTE: This was benchmarked to be 400-600µs on initial retrieval and
+/// 150-300µs on subsequent retrievals. Using `CGGetDisplaysWithRect` and
+/// getting the corresponding `NSScreen` was found to be slightly slower
+/// (700-800µs and then 200-300µs on subsequent retrievals).
+pub(crate) fn nearest_display(
+ native_window: &crate::NativeWindow,
+ dispatcher: &Dispatcher,
+) -> crate::Result<crate::Display> {
+ dispatcher.dispatch_sync(|| {
+ // Get the window's frame in screen coordinates.
+ let window_frame = native_window.frame()?;
+
+ let screens = all_displays(dispatcher)?;
+ let mut best_screen = None;
+ let mut max_intersection_area = 0;
+
+ // TODO: Clean this up.
+ // Iterate through all screens to find the one with the largest
+ // intersection with the window.
+ for screen in screens {
+ let screen_frame = screen.bounds()?;
+
+ // Calculate intersection area.
+ let intersection_x = i32::max(window_frame.x(), screen_frame.x());
+ let intersection_y = i32::max(window_frame.y(), screen_frame.y());
+ let intersection_width = i32::min(
+ window_frame.x() + window_frame.width(),
+ screen_frame.x() + screen_frame.width(),
+ ) - intersection_x;
+ let intersection_height = i32::min(
+ window_frame.y() + window_frame.height(),
+ screen_frame.y() + screen_frame.height(),
+ ) - intersection_y;
+
+ // If there's a valid intersection, calculate its area.
+ if intersection_width > 0 && intersection_height > 0 {
+ let area = intersection_width * intersection_height;
+ if area > max_intersection_area {
+ max_intersection_area = area;
+ best_screen = Some(screen);
+ }
+ }
+ }
+
+ // If we found a screen with intersection, use it. Otherwise, if the
+ // window is off-screen, use the main screen.
+ best_screen
+ .or_else(|| primary_display(dispatcher).ok())
+ .ok_or(crate::Error::DisplayNotFound)
+ })?
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/display_listener.rs b/packages/wm-platform/src/platform_impl/macos/display_listener.rs
new file mode 100644
index 00000000..2b537b5e
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/display_listener.rs
@@ -0,0 +1,84 @@
+use objc2::rc::Retained;
+use tokio::sync::mpsc;
+
+use crate::{
+ platform_impl::{
+ NotificationCenter, NotificationName, NotificationObserver,
+ },
+ Dispatcher, ThreadBound,
+};
+
+/// Platform-specific implementation of [`DisplayListener`].
+pub(crate) struct DisplayListener {
+ /// Notification observer bound to the main thread.
+ observer: Option<ThreadBound<Retained<NotificationObserver>>>,
+}
+
+impl DisplayListener {
+ /// Creates an instance of `DisplayListener`.
+ pub(crate) fn new(
+ event_tx: mpsc::UnboundedSender<()>,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<Self> {
+ let dispatcher_clone = dispatcher.clone();
+ let observer = dispatcher.dispatch_sync(move || {
+ Self::add_observer(event_tx, dispatcher_clone)
+ })?;
+
+ Ok(Self {
+ observer: Some(observer),
+ })
+ }
+
+ /// Implements [`DisplayListener::terminate`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn terminate(&mut self) -> crate::Result<()> {
+ // On macOS 10.11+, observer subscriptions are cleaned up automatically
+ // without calling `removeObserver`.
+ // Ref: https://developer.apple.com/documentation/foundation/notificationcenter/removeobserver(_:name:object:)
+ //
+ // Dropping the `NotificationObserver` also drops its channel sender,
+ // causing the listener thread to exit.
+ self.observer.take();
+ Ok(())
+ }
+
+ /// Registers the notification observer on the main thread.
+ fn add_observer(
+ event_tx: mpsc::UnboundedSender<()>,
+ dispatcher: Dispatcher,
+ ) -> ThreadBound<Retained<NotificationObserver>> {
+ let (observer, mut events_rx) = NotificationObserver::new();
+ let mut default_center = NotificationCenter::default_center();
+
+ // Add observer which will fire when displays are connected and
+ // disconnected, resolution changes, or arrangement changes.
+ unsafe {
+ default_center.add_observer(
+ NotificationName::ApplicationDidChangeScreenParameters,
+ &observer,
+ None,
+ );
+ }
+
+ std::thread::spawn(move || {
+ // Loop exits when the sender is dropped in `Self::terminate`.
+ while events_rx.blocking_recv().is_some() {
+ if let Err(err) = event_tx.send(()) {
+ tracing::warn!("Failed to send display change event: {}", err);
+ break;
+ }
+ }
+
+ tracing::debug!("Display listener thread exited.");
+ });
+
+ ThreadBound::new(observer, dispatcher)
+ }
+}
+
+impl Drop for DisplayListener {
+ fn drop(&mut self) {
+ let _ = self.terminate();
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/event_loop.rs b/packages/wm-platform/src/platform_impl/macos/event_loop.rs
new file mode 100644
index 00000000..0f29ff31
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/event_loop.rs
@@ -0,0 +1,234 @@
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ mpsc, Arc,
+};
+
+use objc2::MainThreadMarker;
+use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy};
+use objc2_core_foundation::{
+ kCFRunLoopDefaultMode, CFRetained, CFRunLoop, CFRunLoopSource,
+ CFRunLoopSourceContext,
+};
+
+use crate::{DispatchFn, Dispatcher};
+
+/// Source for dispatching callbacks onto the event loop thread.
+#[derive(Clone)]
+pub(crate) struct EventLoopSource {
+ dispatch_tx: mpsc::Sender<Box<DispatchFn>>,
+ source: CFRetained<CFRunLoopSource>,
+ run_loop: CFRetained<CFRunLoop>,
+ pub(crate) thread_id: std::thread::ThreadId,
+}
+
+impl EventLoopSource {
+ pub(crate) fn send_dispatch_async<F>(
+ &self,
+ dispatch_fn: F,
+ ) -> crate::Result<()>
+ where
+ F: FnOnce() + Send + 'static,
+ {
+ // TODO: Avoid duplicate check in `dispatch_sync`.
+ if std::thread::current().id() == self.thread_id {
+ dispatch_fn();
+ return Ok(());
+ }
+
+ self
+ .dispatch_tx
+ .send(Box::new(dispatch_fn))
+ .map_err(|_| crate::Error::ChannelSend)?;
+
+ // Signal the run loop source, which schedules the `perform` callback
+ // to be invoked. If signaled multiple times in a short period, this
+ // gets coalesced into a single signal.
+ self.source.signal();
+
+ // Wake up the run loop to process the signal.
+ self.run_loop.wake_up();
+ Ok(())
+ }
+
+ pub(crate) fn send_dispatch_sync<F>(
+ &self,
+ dispatch_fn: F,
+ ) -> crate::Result<()>
+ where
+ F: FnOnce() + Send,
+ {
+ // SAFETY: Usage of this function needs to be in a synchronous
+ // context where the dispatch function will be executed before the
+ // caller's stack frame is dropped.
+ let dispatch_fn_static = unsafe {
+ std::mem::transmute::<
+ Box<dyn FnOnce() + Send>,
+ Box<dyn FnOnce() + Send + 'static>,
+ >(Box::new(dispatch_fn))
+ };
+
+ self.send_dispatch_async(dispatch_fn_static)
+ }
+
+ pub(crate) fn send_stop(&self) -> crate::Result<()> {
+ let (result_tx, result_rx) = std::sync::mpsc::channel();
+
+ self.send_dispatch_sync(|| {
+ let mtm = unsafe { MainThreadMarker::new_unchecked() };
+
+ // Call `stop()` to mark the run loop for termination.
+ let ns_app = NSApplication::sharedApplication(mtm);
+ ns_app.stop(None);
+
+ // `stop()` only takes effect after processing a subsequent UI event.
+ // Post a dummy event so the application actually exits.
+ unsafe { ns_app.abortModal() };
+
+ let _ = result_tx.send(());
+ })?;
+
+ result_rx
+ .recv_timeout(std::time::Duration::from_millis(3000))
+ .map_err(crate::Error::ChannelRecv)
+ }
+}
+
+// SAFETY: `CFRunLoop` and `CFRunLoopSource` are thread-safe types. The
+// `objc2` bindings don't implement `Send + Sync`.
+unsafe impl Send for EventLoopSource {}
+unsafe impl Sync for EventLoopSource {}
+
+/// Platform-specific implementation of [`EventLoop`].
+pub(crate) struct EventLoop {
+ source: EventLoopSource,
+ stopped: Arc<AtomicBool>,
+}
+
+impl EventLoop {
+ /// Implements [`EventLoop::new`].
+ pub fn new() -> crate::Result<(Self, Dispatcher)> {
+ // Add a new run loop source that allows dispatching from any thread.
+ let source = Self::add_dispatch_source()?;
+
+ let stopped = Arc::new(AtomicBool::new(false));
+ let dispatcher =
+ Dispatcher::new(Some(source.clone()), stopped.clone());
+
+ Ok((
+ Self {
+ source: source.clone(),
+ stopped,
+ },
+ dispatcher,
+ ))
+ }
+
+ /// Implements [`EventLoop::run`].
+ #[allow(clippy::unused_self)]
+ pub fn run(self) -> crate::Result<()> {
+ let mtm =
+ MainThreadMarker::new().ok_or(crate::Error::NotMainThread)?;
+
+ tracing::info!("Starting macOS event loop.");
+ NSApplication::sharedApplication(mtm).run();
+
+ tracing::info!("macOS event loop exiting.");
+ Ok(())
+ }
+
+ /// Adds a source (`CFRunLoopSource`) for allowing dispatches to
+ /// the current run loop.
+ ///
+ /// Can only be called on the main thread.
+ pub(crate) fn add_dispatch_source() -> crate::Result<EventLoopSource> {
+ let mtm =
+ MainThreadMarker::new().ok_or(crate::Error::NotMainThread)?;
+
+ // Initialize `NSApplication` on the main thread. This is necessary for
+ // some AppKit components (e.g. system tray) to be functional.
+ // TODO: Skip this if not on the main thread, and instead run a normal
+ // run loop.
+ let ns_app = NSApplication::sharedApplication(mtm);
+ ns_app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
+
+ let (dispatch_tx, dispatch_rx) = mpsc::channel();
+ let dispatch_rx_ptr =
+ Box::into_raw(Box::new(dispatch_rx)).cast::<std::ffi::c_void>();
+
+ // Create `CFRunLoopSource` context.
+ let mut context = CFRunLoopSourceContext {
+ version: 0,
+ info: dispatch_rx_ptr,
+ retain: None,
+ release: Some(Self::runloop_source_released_callback),
+ copyDescription: None,
+ equal: None,
+ hash: None,
+ schedule: None,
+ cancel: None,
+ perform: Some(Self::runloop_signaled_callback),
+ };
+
+ // Create the run loop source.
+ let source =
+ unsafe { CFRunLoopSource::new(None, 0, &raw mut context) }.ok_or(
+ crate::Error::Platform(
+ "Failed to create run loop source.".to_string(),
+ ),
+ )?;
+
+ let run_loop =
+ CFRunLoop::current().ok_or(crate::Error::EventLoopStopped)?;
+
+ run_loop.add_source(Some(&source), unsafe { kCFRunLoopDefaultMode });
+
+ Ok(EventLoopSource {
+ dispatch_tx,
+ source,
+ run_loop,
+ thread_id: std::thread::current().id(),
+ })
+ }
+
+ // This function is called by the `CFRunLoopSource` when signaled.
+ extern "C-unwind" fn runloop_signaled_callback(
+ info: *mut std::ffi::c_void,
+ ) {
+ let callbacks =
+ unsafe { &*(info as *const mpsc::Receiver<Box<DispatchFn>>) };
+
+ // Process any pending dispatched callbacks. Multiple run loop signals
+ // may be coalesced together (calling `perform` only once), so it's
+ // important to drain all pending callbacks.
+ for callback in callbacks.try_iter() {
+ callback();
+ }
+ }
+
+ // This function is called when the `CFRunLoopSource` is released.
+ extern "C-unwind" fn runloop_source_released_callback(
+ info: *const std::ffi::c_void,
+ ) {
+ // SAFETY: This pointer was created with `Box::into_raw` in
+ // `add_dispatch_source`, so it can safely be converted back to a `Box`
+ // and dropped.
+ let _ = unsafe {
+ Box::from_raw(info as *mut mpsc::Receiver<Box<DispatchFn>>)
+ };
+ }
+}
+
+impl Drop for EventLoop {
+ fn drop(&mut self) {
+ tracing::info!("Shutting down event loop.");
+
+ // Stop the run loop if not already stopped.
+ if !self.stopped.load(Ordering::SeqCst) {
+ let _ = self.source.send_stop();
+ }
+
+ // Invalidate the runloop source to trigger its release callback. This
+ // is thread-safe and is OK to call after the run loop is stopped.
+ self.source.source.invalidate();
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/ffi.rs b/packages/wm-platform/src/platform_impl/macos/ffi.rs
new file mode 100644
index 00000000..04ec8851
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/ffi.rs
@@ -0,0 +1,79 @@
+use std::{ffi::c_void, ptr::NonNull};
+
+use objc2_application_services::{AXError, AXUIElement};
+use objc2_core_foundation::CFUUID;
+use objc2_core_graphics::{CGDirectDisplayID, CGError, CGWindowID};
+
+use crate::platform_impl::ProcessId;
+
+/// Carbon process serial number (PSN), used to uniquely identify a
+/// process.
+#[derive(Clone, Debug, Default)]
+#[repr(C)]
+pub struct ProcessSerialNumber {
+ high: u32,
+ low: u32,
+}
+
+/// Carbon process information, populated by `GetProcessInformation`.
+#[derive(Default)]
+#[repr(C, packed(2))]
+pub(crate) struct ProcessInfo {
+ pub(crate) info_length: u32,
+ name: *const u8,
+ psn: ProcessSerialNumber,
+ pub(crate) r#type: u32,
+ signature: u32,
+ mode: u32,
+ location: *const u8,
+ size: u32,
+ free_mem: u32,
+ launcher: ProcessSerialNumber,
+ launch_date: u32,
+ active_time: u32,
+ app_ref: *const u8,
+}
+
+pub const CPS_USER_GENERATED: u32 = 0x200;
+
+#[link(name = "ApplicationServices", kind = "framework")]
+unsafe extern "C" {
+ // Deprecated in macOS 10.9 in late 2014, but still works fine.
+ pub(crate) fn GetProcessForPID(
+ pid: ProcessId,
+ psn: *mut ProcessSerialNumber,
+ ) -> u32;
+
+ // Deprecated in macOS 10.9 in late 2014, but still works fine.
+ pub(crate) fn GetProcessInformation(
+ psn: *const ProcessSerialNumber,
+ process_info: *mut ProcessInfo,
+ ) -> u32;
+
+ // `CGDisplayCreateUUIDFromDisplayID` comes from the `ColorSync`
+ // framework, which is a subframework of `ApplicationServices`.
+ pub(crate) fn CGDisplayCreateUUIDFromDisplayID(
+ display: CGDirectDisplayID,
+ ) -> Option<NonNull<CFUUID>>;
+}
+
+unsafe extern "C" {
+ pub(crate) fn _AXUIElementGetWindow(
+ elem: NonNull<AXUIElement>,
+ window_id: *mut CGWindowID,
+ ) -> AXError;
+}
+
+#[link(name = "SkyLight", kind = "framework")]
+unsafe extern "C" {
+ pub(crate) fn _SLPSSetFrontProcessWithOptions(
+ psn: &ProcessSerialNumber,
+ window_id: i32,
+ mode: u32,
+ ) -> CGError;
+
+ pub(crate) fn SLPSPostEventRecordTo(
+ psn: &ProcessSerialNumber,
+ event: *const c_void,
+ ) -> CGError;
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/keyboard_hook.rs b/packages/wm-platform/src/platform_impl/macos/keyboard_hook.rs
new file mode 100644
index 00000000..ca40bc5e
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/keyboard_hook.rs
@@ -0,0 +1,218 @@
+use std::{os::raw::c_void, ptr::NonNull};
+
+use objc2_core_foundation::{
+ kCFRunLoopCommonModes, CFMachPort, CFRetained, CFRunLoop,
+};
+use objc2_core_graphics::{
+ CGEvent, CGEventField, CGEventFlags, CGEventMask, CGEventTapLocation,
+ CGEventTapOptions, CGEventTapPlacement, CGEventTapProxy, CGEventType,
+};
+
+use crate::{Dispatcher, Error, Key, KeyCode, ThreadBound};
+
+/// A key event received from the keyboard hook.
+#[derive(Clone, Debug)]
+pub struct KeyEvent {
+ /// The key that was pressed or released.
+ pub key: Key,
+
+ /// Key code that generated this event.
+ #[allow(dead_code)]
+ pub key_code: KeyCode,
+
+ /// Whether the event is for a key press or release.
+ pub is_keypress: bool,
+
+ /// Modifier key flags at the time of the event.
+ event_flags: CGEventFlags,
+}
+
+impl KeyEvent {
+ /// Gets whether the specified key is currently pressed.
+ pub fn is_key_down(&self, key: Key) -> bool {
+ match key {
+ Key::Cmd => {
+ self.event_flags & CGEventFlags::MaskCommand
+ != CGEventFlags::empty()
+ }
+ Key::Alt => {
+ self.event_flags & CGEventFlags::MaskAlternate
+ != CGEventFlags::empty()
+ }
+ Key::Ctrl => {
+ self.event_flags & CGEventFlags::MaskControl
+ != CGEventFlags::empty()
+ }
+ Key::Shift => {
+ self.event_flags & CGEventFlags::MaskShift != CGEventFlags::empty()
+ }
+ _ => {
+ // TODO: For non-modifier keys, check using CGEventSourceStateID.
+ false
+ }
+ }
+ }
+}
+
+/// Data shared with the `CGEventTap` callback.
+struct CallbackData {
+ callback: Box<dyn Fn(KeyEvent) -> bool + Send + Sync + 'static>,
+}
+
+/// A system-wide low-level keyboard hook.
+#[derive(Debug)]
+pub struct KeyboardHook {
+ /// Mach port for the created `CGEventTap`.
+ tap_port: Option<ThreadBound<CFRetained<CFMachPort>>>,
+
+ /// Pointer to [`CallbackData`], used by the `CGEventTap` callback.
+ callback_ptr: Option<usize>,
+}
+
+impl KeyboardHook {
+ /// Creates an instance of `KeyboardHook`.
+ ///
+ /// The callback is called for every keyboard event and returns `true` if
+ /// the event should be intercepted.
+ pub fn new<F>(
+ callback: F,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<Self>
+ where
+ F: Fn(KeyEvent) -> bool + Send + Sync + 'static,
+ {
+ let callback_ptr = {
+ let data = Box::new(CallbackData {
+ callback: Box::new(callback),
+ });
+ Box::into_raw(data) as usize
+ };
+
+ let tap_port = dispatcher
+ .dispatch_sync(|| Self::create_event_tap(callback_ptr, dispatcher))
+ .flatten()
+ .inspect_err(|_| {
+ // Clean up the callback data if event tap creation fails.
+ let _ =
+ unsafe { Box::from_raw(callback_ptr as *mut CallbackData) };
+ })?;
+
+ Ok(Self {
+ tap_port: Some(tap_port),
+ callback_ptr: Some(callback_ptr),
+ })
+ }
+
+ /// Terminates the keyboard hook by invalidating the event tap.
+ #[allow(clippy::unnecessary_wraps)]
+ pub fn terminate(&mut self) -> crate::Result<()> {
+ if let Some(tap) = self.tap_port.take() {
+ // Invalidate the event tap to stop it from receiving events. This
+ // also invalidates the run loop source.
+ // See: https://developer.apple.com/documentation/corefoundation/cfmachportinvalidate(_:)
+ let _ = tap.with(|tap| CFMachPort::invalidate(tap));
+ }
+
+ // Clean up the callback data if it exists.
+ if let Some(ptr) = self.callback_ptr.take() {
+ let _ = unsafe { Box::from_raw(ptr as *mut CallbackData) };
+ }
+
+ Ok(())
+ }
+
+ /// Creates a `CGEventTap` object.
+ fn create_event_tap(
+ callback_ptr: usize,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<ThreadBound<CFRetained<CFMachPort>>> {
+ let mask: CGEventMask = (1u64 << u64::from(CGEventType::KeyDown.0))
+ | (1u64 << u64::from(CGEventType::KeyUp.0));
+
+ let tap_port = unsafe {
+ CGEvent::tap_create(
+ CGEventTapLocation::SessionEventTap,
+ CGEventTapPlacement::HeadInsertEventTap,
+ CGEventTapOptions::Default,
+ mask,
+ Some(Self::keyboard_event_callback),
+ callback_ptr as *mut c_void,
+ )
+ .ok_or_else(|| {
+ Error::Platform(
+ "Failed to create `CGEventTap`. Accessibility permissions may be required."
+ .to_string(),
+ )
+ })
+ }?;
+
+ let loop_source =
+ CFMachPort::new_run_loop_source(None, Some(&tap_port), 0)
+ .ok_or_else(|| {
+ Error::Platform("Failed to create loop source".to_string())
+ })?;
+
+ let current_loop = CFRunLoop::current().ok_or_else(|| {
+ Error::Platform("Failed to get current run loop".to_string())
+ })?;
+
+ current_loop
+ .add_source(Some(&loop_source), unsafe { kCFRunLoopCommonModes });
+
+ unsafe { CGEvent::tap_enable(&tap_port, true) };
+
+ Ok(ThreadBound::new(tap_port, dispatcher.clone()))
+ }
+
+ /// Callback function for keyboard events.
+ ///
+ /// For use with `CGEventTap`.
+ extern "C-unwind" fn keyboard_event_callback(
+ _proxy: CGEventTapProxy,
+ event_type: CGEventType,
+ mut event: NonNull<CGEvent>,
+ user_info: *mut c_void,
+ ) -> *mut CGEvent {
+ if user_info.is_null() {
+ tracing::error!("Null pointer passed to keyboard event callback.");
+ return unsafe { event.as_mut() };
+ }
+
+ // Extract the key code of the pressed/released key.
+ let key_code = KeyCode(unsafe {
+ CGEvent::integer_value_field(
+ Some(event.as_ref()),
+ CGEventField::KeyboardEventKeycode,
+ )
+ });
+
+ // Try to convert the key code to a known key.
+ let Ok(key) = Key::try_from(key_code) else {
+ return unsafe { event.as_mut() };
+ };
+
+ let event_flags = unsafe { CGEvent::flags(Some(event.as_ref())) };
+ let key_event = KeyEvent {
+ key,
+ key_code,
+ is_keypress: event_type == CGEventType::KeyDown,
+ event_flags,
+ };
+
+ // Get callback from user data and invoke it.
+ let data = unsafe { &*(user_info as *const CallbackData) };
+ let should_intercept = (data.callback)(key_event);
+
+ if should_intercept {
+ std::ptr::null_mut()
+ } else {
+ unsafe { event.as_mut() }
+ }
+ }
+}
+
+impl Drop for KeyboardHook {
+ fn drop(&mut self) {
+ let _ = self.terminate();
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/mod.rs b/packages/wm-platform/src/platform_impl/macos/mod.rs
new file mode 100644
index 00000000..fcb5fb2d
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/mod.rs
@@ -0,0 +1,28 @@
+mod application;
+mod application_observer;
+mod ax_ui_element;
+mod ax_value;
+mod display;
+mod display_listener;
+mod event_loop;
+pub(crate) mod ffi;
+mod keyboard_hook;
+mod mouse_listener;
+mod native_window;
+mod notification_center;
+mod single_instance;
+mod window_listener;
+
+pub(crate) use application::*;
+pub(crate) use application_observer::*;
+pub(crate) use ax_ui_element::*;
+pub(crate) use ax_value::*;
+pub(crate) use display::*;
+pub(crate) use display_listener::*;
+pub(crate) use event_loop::*;
+pub(crate) use keyboard_hook::*;
+pub(crate) use mouse_listener::*;
+pub(crate) use native_window::*;
+pub(crate) use notification_center::*;
+pub(crate) use single_instance::*;
+pub(crate) use window_listener::*;
diff --git a/packages/wm-platform/src/platform_impl/macos/mouse_listener.rs b/packages/wm-platform/src/platform_impl/macos/mouse_listener.rs
new file mode 100644
index 00000000..4a74617b
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/mouse_listener.rs
@@ -0,0 +1,347 @@
+use std::{
+ os::raw::c_void,
+ ptr::NonNull,
+ time::{Duration, Instant},
+};
+
+use objc2_core_foundation::{
+ kCFRunLoopCommonModes, CFMachPort, CFRetained, CFRunLoop,
+};
+use objc2_core_graphics::{
+ CGEvent, CGEventField, CGEventMask, CGEventTapLocation,
+ CGEventTapOptions, CGEventTapPlacement, CGEventTapProxy, CGEventType,
+};
+use tokio::sync::mpsc;
+
+use crate::{
+ mouse_listener::MouseEventKind,
+ platform_event::{MouseButton, MouseEvent, PressedButtons},
+ Dispatcher, Error, Point, ThreadBound, WindowId,
+};
+
+/// Data shared with the `CGEventTap` callback.
+struct CallbackData {
+ event_tx: mpsc::UnboundedSender<MouseEvent>,
+
+ /// Pressed button state tracked from events.
+ pressed_buttons: PressedButtons,
+
+ /// Timestamp of the last emitted `Move` event for throttling.
+ last_move_emission: Option<Instant>,
+}
+
+impl CallbackData {
+ fn new(event_tx: mpsc::UnboundedSender<MouseEvent>) -> Self {
+ Self {
+ event_tx,
+ pressed_buttons: PressedButtons::default(),
+ last_move_emission: None,
+ }
+ }
+}
+
+/// Platform-specific implementation of [`MouseListener`].
+#[derive(Debug)]
+pub(crate) struct MouseListener {
+ dispatcher: Dispatcher,
+ event_tx: mpsc::UnboundedSender<MouseEvent>,
+
+ /// Mach port for the created `CGEventTap`.
+ tap_port: Option<ThreadBound<CFRetained<CFMachPort>>>,
+
+ /// Pointer to [`CallbackData`], used by the `CGEventTap` callback.
+ callback_data_ptr: Option<usize>,
+}
+
+impl MouseListener {
+ /// Implements [`MouseListener::new`].
+ pub(crate) fn new(
+ enabled_events: &[MouseEventKind],
+ event_tx: mpsc::UnboundedSender<MouseEvent>,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<Self> {
+ let callback_data_ptr = {
+ let data = Box::new(CallbackData::new(event_tx.clone()));
+ Box::into_raw(data) as usize
+ };
+
+ let tap_port = dispatcher
+ .dispatch_sync(|| {
+ Self::create_event_tap(
+ enabled_events,
+ callback_data_ptr,
+ dispatcher,
+ )
+ })
+ .flatten()
+ .inspect_err(|_| {
+ // Clean up the callback data if event tap creation fails.
+ let _ =
+ unsafe { Box::from_raw(callback_data_ptr as *mut CallbackData) };
+ })?;
+
+ Ok(Self {
+ tap_port: Some(tap_port),
+ callback_data_ptr: Some(callback_data_ptr),
+ dispatcher: dispatcher.clone(),
+ event_tx,
+ })
+ }
+
+ /// Implements [`MouseListener::enable`].
+ pub(crate) fn enable(&mut self, enabled: bool) -> crate::Result<()> {
+ if let Some(tap_port) = &self.tap_port {
+ tap_port.with(|tap| unsafe { CGEvent::tap_enable(tap, enabled) })?;
+ }
+
+ Ok(())
+ }
+
+ /// Implements [`MouseListener::set_enabled_events`].
+ pub(crate) fn set_enabled_events(
+ &mut self,
+ enabled_events: &[MouseEventKind],
+ ) -> crate::Result<()> {
+ let _ = self.terminate();
+
+ let callback_data_ptr = {
+ let data = Box::new(CallbackData::new(self.event_tx.clone()));
+ Box::into_raw(data) as usize
+ };
+
+ let tap_port = self
+ .dispatcher
+ .dispatch_sync(|| {
+ Self::create_event_tap(
+ enabled_events,
+ callback_data_ptr,
+ &self.dispatcher,
+ )
+ })
+ .flatten()
+ .inspect_err(|_| {
+ // Clean up the callback data if event tap creation fails.
+ let _ =
+ unsafe { Box::from_raw(callback_data_ptr as *mut CallbackData) };
+ })?;
+
+ self.callback_data_ptr = Some(callback_data_ptr);
+ self.tap_port = Some(tap_port);
+
+ Ok(())
+ }
+
+ /// Implements [`MouseListener::terminate`].
+ pub(crate) fn terminate(&mut self) -> crate::Result<()> {
+ if let Some(tap) = self.tap_port.take() {
+ // Invalidate the tap to stop it from receiving events. This also
+ // invalidates the run loop source.
+ // See: https://developer.apple.com/documentation/corefoundation/cfmachportinvalidate(_:)
+ tap.with(|tap| CFMachPort::invalidate(tap))?;
+ }
+
+ // Clean up the callback data if it exists.
+ if let Some(ptr) = self.callback_data_ptr.take() {
+ let _ = unsafe { Box::from_raw(ptr as *mut CallbackData) };
+ }
+
+ Ok(())
+ }
+
+ /// Creates and registers a `CGEventTap` for mouse events.
+ fn create_event_tap(
+ enabled_events: &[MouseEventKind],
+ callback_data_ptr: usize,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<ThreadBound<CFRetained<CFMachPort>>> {
+ let mask = Self::event_mask_from_enabled(enabled_events);
+
+ let tap_port = unsafe {
+ CGEvent::tap_create(
+ CGEventTapLocation::AnnotatedSessionEventTap,
+ CGEventTapPlacement::HeadInsertEventTap,
+ CGEventTapOptions::Default,
+ mask,
+ Some(Self::mouse_event_callback),
+ callback_data_ptr as *mut c_void,
+ )
+ .ok_or_else(|| {
+ Error::Platform(
+ "Failed to create `CGEventTap`. Accessibility permissions may be required.".to_string(),
+ )
+ })
+ }?;
+
+ let loop_source =
+ CFMachPort::new_run_loop_source(None, Some(&tap_port), 0)
+ .ok_or_else(|| {
+ Error::Platform("Failed to create loop source".to_string())
+ })?;
+
+ let current_loop = CFRunLoop::current().ok_or_else(|| {
+ Error::Platform("Failed to get current run loop".to_string())
+ })?;
+
+ current_loop
+ .add_source(Some(&loop_source), unsafe { kCFRunLoopCommonModes });
+
+ unsafe { CGEvent::tap_enable(&tap_port, true) };
+
+ Ok(ThreadBound::new(tap_port, dispatcher.clone()))
+ }
+
+ /// Gets the `CGEvent` mask for the enabled mouse events.
+ fn event_mask_from_enabled(
+ enabled_events: &[MouseEventKind],
+ ) -> CGEventMask {
+ let mut mask = 0u64;
+
+ for event in enabled_events {
+ match event {
+ MouseEventKind::Move => {
+ // NOTE: `MouseMoved` doesn't get triggered when clicking and
+ // dragging. Therefore, we also listen for `LeftMouseDragged`
+ // and `RightMouseDragged` events.
+ mask |= 1u64 << u64::from(CGEventType::MouseMoved.0);
+ mask |= 1u64 << u64::from(CGEventType::LeftMouseDragged.0);
+ mask |= 1u64 << u64::from(CGEventType::RightMouseDragged.0);
+ }
+ MouseEventKind::LeftButtonDown => {
+ mask |= 1u64 << u64::from(CGEventType::LeftMouseDown.0);
+ }
+ MouseEventKind::RightButtonDown => {
+ mask |= 1u64 << u64::from(CGEventType::RightMouseDown.0);
+ }
+ MouseEventKind::LeftButtonUp => {
+ mask |= 1u64 << u64::from(CGEventType::LeftMouseUp.0);
+ }
+ MouseEventKind::RightButtonUp => {
+ mask |= 1u64 << u64::from(CGEventType::RightMouseUp.0);
+ }
+ }
+ }
+
+ mask
+ }
+
+ /// Callback for the `CGEventTap`.
+ extern "C-unwind" fn mouse_event_callback(
+ _: CGEventTapProxy,
+ cg_event_type: CGEventType,
+ mut cg_event: NonNull<CGEvent>,
+ user_info: *mut c_void,
+ ) -> *mut CGEvent {
+ if user_info.is_null() {
+ tracing::error!("Null pointer passed to mouse event callback.");
+ return unsafe { cg_event.as_mut() };
+ }
+
+ let data = unsafe { &mut *user_info.cast::<CallbackData>() };
+
+ // Map a `CGEventType` to a `MouseEventKind`.
+ let event_kind = match cg_event_type {
+ CGEventType::LeftMouseDown => MouseEventKind::LeftButtonDown,
+ CGEventType::LeftMouseUp => MouseEventKind::LeftButtonUp,
+ CGEventType::RightMouseDown => MouseEventKind::RightButtonDown,
+ CGEventType::RightMouseUp => MouseEventKind::RightButtonUp,
+ _ => MouseEventKind::Move,
+ };
+
+ // Extract the cursor position from the `CGEvent`.
+ let cg_event_ref = unsafe { cg_event.as_ref() };
+ let position = {
+ let cg_point = unsafe { CGEvent::location(Some(cg_event_ref)) };
+
+ #[allow(clippy::cast_possible_truncation)]
+ Point {
+ x: cg_point.x as i32,
+ y: cg_point.y as i32,
+ }
+ };
+
+ // NOTE: Unfortunately quite unreliable. Returns 0 in most cases with
+ // the real window ID interspersed every so often. Often a 100–200ms
+ // delay before the real window ID is returned.
+ let window_below_cursor = {
+ let window_id = unsafe {
+ CGEvent::integer_value_field(
+ Some(cg_event_ref),
+ CGEventField::MouseEventWindowUnderMousePointer,
+ )
+ };
+
+ if window_id == 0 {
+ None
+ } else {
+ #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
+ Some(WindowId(window_id as u32))
+ }
+ };
+
+ data.pressed_buttons.update(event_kind);
+
+ // Throttle mouse move events so that there's a minimum of 50ms between
+ // each emission. State change events (button down/up) always get
+ // emitted.
+ let should_emit = match event_kind {
+ MouseEventKind::Move => {
+ let has_elapsed_throttle =
+ data.last_move_emission.is_none_or(|timestamp| {
+ timestamp.elapsed() >= Duration::from_millis(50)
+ });
+
+ // TODO: This is a hack to let through mouse move events when
+ // they contain a window ID. macOS sporadically includes the
+ // window ID on mouse events.
+ has_elapsed_throttle || window_below_cursor.is_some()
+ }
+ _ => true,
+ };
+
+ let mouse_event = match event_kind {
+ MouseEventKind::LeftButtonDown => MouseEvent::ButtonDown {
+ position,
+ button: MouseButton::Left,
+ pressed_buttons: data.pressed_buttons,
+ },
+ MouseEventKind::LeftButtonUp => MouseEvent::ButtonUp {
+ position,
+ button: MouseButton::Left,
+ pressed_buttons: data.pressed_buttons,
+ },
+ MouseEventKind::RightButtonDown => MouseEvent::ButtonDown {
+ position,
+ button: MouseButton::Right,
+ pressed_buttons: data.pressed_buttons,
+ },
+ MouseEventKind::RightButtonUp => MouseEvent::ButtonUp {
+ position,
+ button: MouseButton::Right,
+ pressed_buttons: data.pressed_buttons,
+ },
+ MouseEventKind::Move => MouseEvent::Move {
+ position,
+ pressed_buttons: data.pressed_buttons,
+ window_below_cursor,
+ },
+ };
+
+ if should_emit {
+ let _ = data.event_tx.send(mouse_event);
+
+ if event_kind == MouseEventKind::Move {
+ data.last_move_emission = Some(Instant::now());
+ }
+ }
+
+ unsafe { cg_event.as_mut() }
+ }
+}
+
+impl Drop for MouseListener {
+ fn drop(&mut self) {
+ if let Err(err) = self.terminate() {
+ tracing::warn!("Failed to terminate mouse listener: {}", err);
+ }
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/native_window.rs b/packages/wm-platform/src/platform_impl/macos/native_window.rs
new file mode 100644
index 00000000..62536971
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/native_window.rs
@@ -0,0 +1,482 @@
+use std::sync::Arc;
+
+use objc2::MainThreadMarker;
+use objc2_app_kit::{
+ NSApplicationActivationOptions, NSWindow, NSWorkspace,
+};
+use objc2_application_services::{AXError, AXValue};
+use objc2_core_foundation::{
+ CFBoolean, CFRetained, CFString, CGPoint, CGSize,
+};
+use objc2_core_graphics::CGError;
+
+use crate::{
+ platform_impl::{
+ self, ffi, AXUIElement, AXUIElementExt, AXValueExt, Application,
+ },
+ Dispatcher, Point, Rect, ThreadBound, WindowId,
+};
+
+/// Platform-specific implementation of [`NativeWindow`].
+#[derive(Clone, Debug)]
+pub(crate) struct NativeWindow {
+ pub(crate) id: WindowId,
+ pub(crate) element: Arc<ThreadBound<CFRetained<AXUIElement>>>,
+ pub(crate) application: Application,
+}
+
+impl NativeWindow {
+ /// Creates an instance of `NativeWindow`.
+ #[must_use]
+ pub(crate) fn new(
+ id: WindowId,
+ element: ThreadBound<CFRetained<AXUIElement>>,
+ application: Application,
+ ) -> Self {
+ Self {
+ element: Arc::new(element),
+ id,
+ application,
+ }
+ }
+
+ /// Implements [`NativeWindow::id`].
+ pub(crate) fn id(&self) -> WindowId {
+ self.id
+ }
+
+ /// Implements [`NativeWindow::title`].
+ pub(crate) fn title(&self) -> crate::Result<String> {
+ self.element.with(|el| {
+ el.get_attribute::<CFString>("AXTitle")
+ .map(|cf_string| cf_string.to_string())
+ })?
+ }
+
+ /// Implements [`NativeWindow::process_name`].
+ pub(crate) fn process_name(&self) -> crate::Result<String> {
+ self
+ .application
+ .process_name()
+ .ok_or(crate::Error::Platform(
+ "Failed to get application process name.".to_string(),
+ ))
+ }
+
+ /// Implements [`NativeWindow::frame`].
+ pub(crate) fn frame(&self) -> crate::Result<Rect> {
+ // TODO: Consider refactoring this to use a single dispatch.
+ // TODO: Would `AXFrame` work instead?
+ let size = self.size()?;
+ let position = self.position()?;
+ #[allow(clippy::cast_possible_truncation)]
+ Ok(Rect::from_xy(
+ position.0 as i32,
+ position.1 as i32,
+ size.0 as i32,
+ size.1 as i32,
+ ))
+ }
+
+ /// Implements [`NativeWindow::position`].
+ pub(crate) fn position(&self) -> crate::Result<(f64, f64)> {
+ self.element.with(move |el| {
+ el.get_attribute::<AXValue>("AXPosition")
+ .and_then(|ax_value| ax_value.value_strict::<CGPoint>())
+ .map(|point| (point.x, point.y))
+ })?
+ }
+
+ /// Implements [`NativeWindow::size`].
+ pub(crate) fn size(&self) -> crate::Result<(f64, f64)> {
+ self.element.with(move |el| {
+ el.get_attribute::<AXValue>("AXSize")
+ .and_then(|ax_value| ax_value.value_strict::<CGSize>())
+ .map(|size| (size.width, size.height))
+ })?
+ }
+
+ /// Implements [`NativeWindow::is_valid`].
+ pub(crate) fn is_valid(&self) -> bool {
+ // Query `AXRole`, which is present on all valid `AXUIElement`s.
+ self
+ .element
+ .with(|el| match el.get_attribute::<CFString>("AXRole") {
+ Err(crate::Error::Accessibility(_, code)) => {
+ code != AXError::InvalidUIElement.0
+ }
+ _ => true,
+ })
+ .unwrap_or(false)
+ }
+
+ /// Implements [`NativeWindow::is_visible`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn is_visible(&self) -> crate::Result<bool> {
+ Ok(!self.application.is_hidden())
+ }
+
+ /// Implements [`NativeWindow::is_minimized`].
+ pub(crate) fn is_minimized(&self) -> crate::Result<bool> {
+ self.element.with(|el| {
+ el.get_attribute::<CFBoolean>("AXMinimized")
+ .map(|cf_bool| cf_bool.value())
+ })?
+ }
+
+ /// Implements [`NativeWindow::is_maximized`].
+ pub(crate) fn is_maximized(&self) -> crate::Result<bool> {
+ self.element.with(|el| {
+ el.get_attribute::<CFBoolean>("AXFullScreen")
+ .map(|cf_bool| cf_bool.value())
+ })?
+ }
+
+ /// Implements [`NativeWindow::is_resizable`].
+ #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
+ pub(crate) fn is_resizable(&self) -> crate::Result<bool> {
+ // TODO: Not sure if this is even available via the AX API.
+ Ok(true)
+ }
+
+ /// Implements [`NativeWindow::is_desktop_window`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn is_desktop_window(&self) -> crate::Result<bool> {
+ Ok(
+ self.application.bundle_id() == Some("com.apple.finder".to_string()),
+ )
+ }
+
+ /// Implements [`NativeWindow::set_frame`].
+ pub(crate) fn set_frame(&self, rect: &Rect) -> crate::Result<()> {
+ // TODO: Consider adding a separate `set_frame_async` method which
+ // spawns a thread. Calling blocking AXUIElement methods from different
+ // threads supposedly works fine.
+ // TODO: Refactor the repeated `set_attribute` calls.
+ let rect = rect.clone();
+ self.with_enhanced_ui_disabled(move |el| -> crate::Result<()> {
+ let ax_size = CGSize::new(rect.width().into(), rect.height().into());
+ let ax_value = AXValue::new_strict(&ax_size)?;
+ el.set_attribute("AXSize", &ax_value)?;
+ let ax_point = CGPoint::new(rect.x().into(), rect.y().into());
+ let ax_value = AXValue::new_strict(&ax_point)?;
+ el.set_attribute("AXPosition", &ax_value)?;
+ let ax_size = CGSize::new(rect.width().into(), rect.height().into());
+ let ax_value = AXValue::new_strict(&ax_size)?;
+ el.set_attribute("AXSize", &ax_value)
+ })
+ }
+
+ /// Implements [`NativeWindow::resize`].
+ pub(crate) fn resize(
+ &self,
+ width: i32,
+ height: i32,
+ ) -> crate::Result<()> {
+ self.with_enhanced_ui_disabled(move |el| -> crate::Result<()> {
+ let ax_size = CGSize::new(width.into(), height.into());
+ let ax_value = AXValue::new_strict(&ax_size)?;
+ el.set_attribute("AXSize", &ax_value)
+ })
+ }
+
+ /// Implements [`NativeWindow::reposition`].
+ pub(crate) fn reposition(&self, x: i32, y: i32) -> crate::Result<()> {
+ self.with_enhanced_ui_disabled(move |el| -> crate::Result<()> {
+ let ax_point = CGPoint::new(x.into(), y.into());
+ let ax_value = AXValue::new_strict(&ax_point)?;
+ el.set_attribute("AXPosition", &ax_value)
+ })
+ }
+
+ /// Implements [`NativeWindow::minimize`].
+ pub(crate) fn minimize(&self) -> crate::Result<()> {
+ self.element.with(move |el| -> crate::Result<()> {
+ let ax_bool = CFBoolean::new(true);
+ el.set_attribute::<CFBoolean>("AXMinimized", &ax_bool.into())
+ })?
+ }
+
+ /// Implements [`NativeWindow::maximize`].
+ pub(crate) fn maximize(&self) -> crate::Result<()> {
+ self.element.with(move |el| -> crate::Result<()> {
+ let ax_bool = CFBoolean::new(true);
+ el.set_attribute::<CFBoolean>("AXFullScreen", &ax_bool.into())
+ })?
+ }
+
+ /// Implements [`NativeWindow::focus`].
+ pub(crate) fn focus(&self) -> crate::Result<()> {
+ let psn = self.application.psn()?;
+ self.set_front_process(&psn)?;
+ self.set_key_window(&psn)?;
+ self.raise()
+ }
+
+ /// Implements [`NativeWindow::close`].
+ pub(crate) fn close(&self) -> crate::Result<()> {
+ self.element.with(|el| -> crate::Result<()> {
+ let close_button =
+ el.get_attribute::<AXUIElement>("AXCloseButton")?;
+
+ // Simulate pressing the window's close button.
+ let result = unsafe {
+ close_button.perform_action(&CFString::from_str("AXPress"))
+ };
+
+ if result != AXError::Success {
+ return Err(crate::Error::Accessibility(
+ "AXPress".to_string(),
+ result.0,
+ ));
+ }
+
+ Ok(())
+ })?
+ }
+
+ /// Executes a callback with the `AXEnhancedUserInterface` attribute
+ /// temporarily disabled on the application `AXUIElement`.
+ ///
+ /// This is to prevent inconsistent window resizing and repositioning
+ /// for certain applications (e.g. Firefox).
+ ///
+ /// References:
+ /// - <https://github.com/koekeishiya/yabai/commit/3fe4c77b001e1a4f613c26f01ea68c0f09327f3a>
+ /// - <https://github.com/rxhanson/Rectangle/pull/285>
+ fn with_enhanced_ui_disabled<F, R>(
+ &self,
+ callback: F,
+ ) -> crate::Result<R>
+ where
+ F: FnOnce(&CFRetained<AXUIElement>) -> crate::Result<R> + Send,
+ R: Send,
+ {
+ self.application.ax_element.with(|app_el| {
+ // Get whether enhanced UI is currently enabled.
+ let was_enabled = app_el
+ .get_attribute::<CFBoolean>("AXEnhancedUserInterface")
+ .map(|cf_bool| cf_bool.value())
+ .unwrap_or(false);
+
+ // Disable enhanced UI if it was enabled.
+ if was_enabled {
+ let ax_bool = CFBoolean::new(false);
+ let _ = app_el.set_attribute::<CFBoolean>(
+ "AXEnhancedUserInterface",
+ &ax_bool.into(),
+ );
+ }
+
+ // Execute the callback with the window element.
+ let result = self.element.with(callback);
+
+ // Restore enhanced UI if it was originally enabled.
+ if was_enabled {
+ let ax_bool = CFBoolean::new(true);
+ let _ = app_el.set_attribute::<CFBoolean>(
+ "AXEnhancedUserInterface",
+ &ax_bool.into(),
+ );
+ }
+
+ result
+ })??
+ }
+
+ fn raise(&self) -> crate::Result<()> {
+ self.element.with(move |el| -> crate::Result<()> {
+ // This has a couple of caveats:
+ // - Some windows do not get raised without first calling
+ // `_SLPSSetFrontProcessWithOptions`.
+ // - This changes focus if raising a window of the frontmost (active)
+ // application. For example, if 2 Chrome windows are open and one
+ // is focused, raising the other will change focus to the other
+ // window.
+ //
+ // Because of these caveats, this method is not exposed as a public
+ // API. It's also the reason why the GlazeWM feature of bringing all
+ // tiling/floating windows to the front on focus change is not
+ // implemented for macOS.
+ let result =
+ unsafe { el.perform_action(&CFString::from_str("AXRaise")) };
+
+ if result != AXError::Success {
+ return Err(crate::Error::Accessibility(
+ "AXRaise".to_string(),
+ result.0,
+ ));
+ }
+
+ Ok(())
+ })?
+ }
+
+ fn set_front_process(
+ &self,
+ psn: &ffi::ProcessSerialNumber,
+ ) -> crate::Result<()> {
+ let result = unsafe {
+ #[allow(clippy::cast_possible_wrap)]
+ ffi::_SLPSSetFrontProcessWithOptions(
+ psn,
+ self.id.0 as i32,
+ ffi::CPS_USER_GENERATED,
+ )
+ };
+
+ if result != CGError::Success {
+ return Err(crate::Error::Platform(
+ "Failed to set front process.".to_string(),
+ ));
+ }
+
+ Ok(())
+ }
+
+ fn set_key_window(
+ &self,
+ psn: &ffi::ProcessSerialNumber,
+ ) -> crate::Result<()> {
+ // Ref: https://github.com/Hammerspoon/hammerspoon/issues/370#issuecomment-545545468
+ let window_id = self.id.0.to_ne_bytes();
+ let mut event1 = [0u8; 0xf8];
+ event1[0x04] = 0xf8;
+ event1[0x08] = 0x01;
+ event1[0x3a] = 0x10;
+ event1[0x3c..(0x3c + window_id.len())].copy_from_slice(&window_id);
+ event1[0x20..(0x20 + 0x10)].fill(0xff);
+
+ let mut event2 = event1;
+ event2[0x08] = 0x02;
+
+ for event in [event1, event2] {
+ let result =
+ unsafe { ffi::SLPSPostEventRecordTo(psn, event.as_ptr().cast()) };
+
+ if result != CGError::Success {
+ return Err(crate::Error::Platform(
+ "Failed to set key window.".to_string(),
+ ));
+ }
+ }
+
+ Ok(())
+ }
+}
+
+impl From<NativeWindow> for crate::NativeWindow {
+ fn from(window: NativeWindow) -> Self {
+ crate::NativeWindow { inner: window }
+ }
+}
+
+/// Implements [`Dispatcher::visible_windows`].
+pub(crate) fn visible_windows(
+ dispatcher: &Dispatcher,
+) -> crate::Result<Vec<crate::NativeWindow>> {
+ Ok(
+ platform_impl::all_applications(dispatcher)?
+ .iter()
+ .filter_map(|app| app.windows().ok())
+ .flat_map(std::iter::IntoIterator::into_iter)
+ .collect(),
+ )
+}
+
+/// Implements [`Dispatcher::window_by_id`].
+pub(crate) fn window_by_id(
+ id: WindowId,
+ dispatcher: &Dispatcher,
+) -> crate::Result<Option<crate::NativeWindow>> {
+ // TODO: The performance of this is terrible. A better solution would be
+ // to have a cache of window ID <-> `NativeWindow` instances.
+ for app in platform_impl::all_applications(dispatcher)? {
+ if let Ok(windows) = app.windows() {
+ if let Some(win) = windows.into_iter().find(|w| w.id() == id) {
+ return Ok(Some(win));
+ }
+ }
+ }
+
+ Ok(None)
+}
+
+/// Implements [`Dispatcher::window_from_point`].
+pub(crate) fn window_from_point(
+ point: &Point,
+ dispatcher: &Dispatcher,
+) -> crate::Result<Option<crate::NativeWindow>> {
+ // Get the top-most window ID at the given point.
+ let window_id = dispatcher.dispatch_sync(|| {
+ let cg_point = CGPoint {
+ x: f64::from(point.x),
+ y: f64::from(point.y),
+ };
+
+ let window_id = unsafe {
+ NSWindow::windowNumberAtPoint_belowWindowWithWindowNumber(
+ cg_point,
+ // 0 for all windows.
+ 0,
+ MainThreadMarker::new_unchecked(),
+ )
+ };
+
+ #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
+ WindowId(window_id as u32)
+ })?;
+
+ // No window found at the given point.
+ if window_id.0 == 0 {
+ return Ok(None);
+ }
+
+ window_by_id(window_id, dispatcher)
+ .map_err(|_| crate::Error::WindowNotFound)
+}
+
+/// Implements [`Dispatcher::focused_window`].
+pub(crate) fn focused_window(
+ dispatcher: &Dispatcher,
+) -> crate::Result<crate::NativeWindow> {
+ dispatcher
+ .dispatch_sync(|| unsafe {
+ // Get the frontmost (active) application.
+ let frontmost_app = NSWorkspace::sharedWorkspace()
+ .frontmostApplication()
+ .map(|app| Application::new(app, dispatcher.clone()));
+
+ // Get the focused window of the frontmost application.
+ frontmost_app.and_then(|app| app.focused_window().ok().flatten())
+ })?
+ .ok_or(crate::Error::WindowNotFound)
+}
+
+/// Implements [`Dispatcher::reset_focus`].
+// TODO: Move this to a better-suited module.
+pub(crate) fn reset_focus(dispatcher: &Dispatcher) -> crate::Result<()> {
+ let Some(application) = platform_impl::application_for_bundle_id(
+ "com.apple.finder",
+ dispatcher,
+ )?
+ else {
+ return Err(crate::Error::Platform(
+ "Failed to get desktop application.".to_string(),
+ ));
+ };
+
+ let success = unsafe {
+ application.ns_app.activateWithOptions(
+ NSApplicationActivationOptions::ActivateAllWindows,
+ )
+ };
+
+ if !success {
+ return Err(crate::Error::Platform(
+ "Failed to activate desktop application.".to_string(),
+ ));
+ }
+
+ Ok(())
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/notification_center.rs b/packages/wm-platform/src/platform_impl/macos/notification_center.rs
new file mode 100644
index 00000000..b54ad62a
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/notification_center.rs
@@ -0,0 +1,254 @@
+use objc2::{
+ define_class, msg_send, rc::Retained, runtime::AnyObject, sel,
+ AnyThread, DefinedClass,
+};
+use objc2_app_kit::{
+ NSApplicationDidChangeScreenParametersNotification,
+ NSRunningApplication, NSWorkspace,
+ NSWorkspaceActiveSpaceDidChangeNotification,
+ NSWorkspaceDidActivateApplicationNotification,
+ NSWorkspaceDidHideApplicationNotification,
+ NSWorkspaceDidLaunchApplicationNotification,
+ NSWorkspaceDidTerminateApplicationNotification,
+ NSWorkspaceDidUnhideApplicationNotification,
+};
+use objc2_foundation::{
+ ns_string, NSNotification, NSNotificationCenter, NSNotificationName,
+ NSObject, NSString,
+};
+use tokio::sync::mpsc;
+
+/// Notification names for observing macOS workspace and screen events.
+#[derive(Debug)]
+pub(crate) enum NotificationName {
+ WorkspaceActiveSpaceDidChange,
+ WorkspaceDidActivateApplication,
+ WorkspaceDidLaunchApplication,
+ WorkspaceDidTerminateApplication,
+ WorkspaceDidHideApplication,
+ WorkspaceDidUnhideApplication,
+ ApplicationDidChangeScreenParameters,
+}
+
+impl From<&NSNotificationName> for NotificationName {
+ fn from(name: &NSNotificationName) -> Self {
+ if name == unsafe { NSWorkspaceDidLaunchApplicationNotification } {
+ Self::WorkspaceDidLaunchApplication
+ } else if name
+ == unsafe { NSWorkspaceDidActivateApplicationNotification }
+ {
+ Self::WorkspaceDidActivateApplication
+ } else if name
+ == unsafe { NSWorkspaceDidTerminateApplicationNotification }
+ {
+ Self::WorkspaceDidTerminateApplication
+ } else if name
+ == unsafe { NSWorkspaceActiveSpaceDidChangeNotification }
+ {
+ Self::WorkspaceActiveSpaceDidChange
+ } else if name == unsafe { NSWorkspaceDidHideApplicationNotification }
+ {
+ Self::WorkspaceDidHideApplication
+ } else if name
+ == unsafe { NSWorkspaceDidUnhideApplicationNotification }
+ {
+ Self::WorkspaceDidUnhideApplication
+ } else if name
+ == unsafe { NSApplicationDidChangeScreenParametersNotification }
+ {
+ Self::ApplicationDidChangeScreenParameters
+ } else {
+ panic!("Unknown notification name: {name}");
+ }
+ }
+}
+
+impl From<NotificationName> for &NSString {
+ fn from(name: NotificationName) -> Self {
+ match name {
+ NotificationName::WorkspaceActiveSpaceDidChange => unsafe {
+ NSWorkspaceActiveSpaceDidChangeNotification
+ },
+ NotificationName::WorkspaceDidActivateApplication => unsafe {
+ NSWorkspaceDidActivateApplicationNotification
+ },
+ NotificationName::WorkspaceDidLaunchApplication => unsafe {
+ NSWorkspaceDidLaunchApplicationNotification
+ },
+ NotificationName::WorkspaceDidTerminateApplication => unsafe {
+ NSWorkspaceDidTerminateApplicationNotification
+ },
+ NotificationName::WorkspaceDidHideApplication => unsafe {
+ NSWorkspaceDidHideApplicationNotification
+ },
+ NotificationName::WorkspaceDidUnhideApplication => unsafe {
+ NSWorkspaceDidUnhideApplicationNotification
+ },
+ NotificationName::ApplicationDidChangeScreenParameters => unsafe {
+ NSApplicationDidChangeScreenParametersNotification
+ },
+ }
+ }
+}
+
+/// Events received from macOS notification center observers.
+#[derive(Debug)]
+pub(crate) enum NotificationEvent {
+ WorkspaceActiveSpaceDidChange,
+ WorkspaceDidActivateApplication(Retained<NSRunningApplication>),
+ WorkspaceDidLaunchApplication(Retained<NSRunningApplication>),
+ WorkspaceDidTerminateApplication(Retained<NSRunningApplication>),
+ WorkspaceDidHideApplication(Retained<NSRunningApplication>),
+ WorkspaceDidUnhideApplication(Retained<NSRunningApplication>),
+ ApplicationDidChangeScreenParameters,
+}
+
+/// Instance variables for `NotificationObserver`.
+#[repr(C)]
+pub(crate) struct NotificationObserverIvars {
+ events_tx: mpsc::UnboundedSender<NotificationEvent>,
+}
+
+define_class! {
+ // SAFETY:
+ // - The superclass `NSObject` does not have any subclassing requirements.
+ // - `NotificationObserver` does not implement `Drop`.
+ #[unsafe(super(NSObject))]
+ #[ivars = Box<NotificationObserverIvars>]
+ pub(crate) struct NotificationObserver;
+
+ // SAFETY: Each of these method signatures must match their invocations.
+ impl NotificationObserver {
+ #[unsafe(method(onEvent:))]
+ fn on_event(&self, notif: &NSNotification) {
+ self.handle_event(notif);
+ }
+ }
+}
+
+impl NotificationObserver {
+ pub fn new(
+ ) -> (Retained<Self>, mpsc::UnboundedReceiver<NotificationEvent>) {
+ let (events_tx, events_rx) = mpsc::unbounded_channel();
+
+ let instance = Self::alloc()
+ .set_ivars(Box::new(NotificationObserverIvars { events_tx }));
+
+ // SAFETY: The signature of `NSObject`'s `init` method is correct.
+ (unsafe { msg_send![super(instance), init] }, events_rx)
+ }
+
+ fn handle_event(&self, notif: &NSNotification) {
+ tracing::debug!("Received notification: {notif:#?}");
+
+ match NotificationName::from(unsafe { &*notif.name() }) {
+ NotificationName::WorkspaceActiveSpaceDidChange => {
+ self.emit_event(NotificationEvent::WorkspaceActiveSpaceDidChange);
+ }
+ NotificationName::WorkspaceDidActivateApplication => {
+ if let Some(app) = unsafe { app_from_notification(notif) } {
+ self.emit_event(
+ NotificationEvent::WorkspaceDidActivateApplication(app),
+ );
+ } else {
+ tracing::warn!(
+ "Failed to extract application from activate notification"
+ );
+ }
+ }
+ NotificationName::WorkspaceDidLaunchApplication => {
+ if let Some(app) = unsafe { app_from_notification(notif) } {
+ self.emit_event(
+ NotificationEvent::WorkspaceDidLaunchApplication(app),
+ );
+ } else {
+ tracing::warn!(
+ "Failed to extract application from launch notification"
+ );
+ }
+ }
+ NotificationName::WorkspaceDidTerminateApplication => {
+ if let Some(app) = unsafe { app_from_notification(notif) } {
+ self.emit_event(
+ NotificationEvent::WorkspaceDidTerminateApplication(app),
+ );
+ } else {
+ tracing::warn!(
+ "Failed to extract application from terminate notification"
+ );
+ }
+ }
+ NotificationName::WorkspaceDidHideApplication => {
+ if let Some(app) = unsafe { app_from_notification(notif) } {
+ self.emit_event(NotificationEvent::WorkspaceDidHideApplication(
+ app,
+ ));
+ }
+ }
+ NotificationName::WorkspaceDidUnhideApplication => {
+ if let Some(app) = unsafe { app_from_notification(notif) } {
+ self.emit_event(
+ NotificationEvent::WorkspaceDidUnhideApplication(app),
+ );
+ }
+ }
+ NotificationName::ApplicationDidChangeScreenParameters => {
+ self.emit_event(
+ NotificationEvent::ApplicationDidChangeScreenParameters,
+ );
+ }
+ }
+ }
+
+ fn emit_event(&self, event: NotificationEvent) {
+ if let Err(err) = self.ivars().events_tx.send(event) {
+ tracing::warn!("Failed to send event: {err}");
+ }
+ }
+}
+
+/// Wrapper around `NSNotificationCenter` for registering event observers.
+#[derive(Debug)]
+pub(crate) struct NotificationCenter {
+ inner: Retained<NSNotificationCenter>,
+}
+
+impl NotificationCenter {
+ pub fn workspace_center() -> Self {
+ let center =
+ unsafe { NSWorkspace::sharedWorkspace().notificationCenter() };
+
+ Self { inner: center }
+ }
+
+ pub fn default_center() -> Self {
+ let center = unsafe { NSNotificationCenter::defaultCenter() };
+
+ Self { inner: center }
+ }
+
+ pub unsafe fn add_observer(
+ &mut self,
+ notification_name: NotificationName,
+ observer: &NotificationObserver,
+ object: Option<&AnyObject>,
+ ) {
+ tracing::info!("Adding observer for {notification_name:?}.");
+
+ self.inner.addObserver_selector_name_object(
+ observer,
+ sel!(onEvent:),
+ Some(notification_name.into()),
+ object,
+ );
+ }
+}
+
+pub unsafe fn app_from_notification(
+ notification: &NSNotification,
+) -> Option<Retained<NSRunningApplication>> {
+ notification
+ .userInfo()?
+ .objectForKey(ns_string!("NSWorkspaceApplicationKey"))
+ .map(|app| Retained::<AnyObject>::cast_unchecked(app))
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/single_instance.rs b/packages/wm-platform/src/platform_impl/macos/single_instance.rs
new file mode 100644
index 00000000..834457a4
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/single_instance.rs
@@ -0,0 +1,64 @@
+use std::{
+ fs::{self, File, TryLockError},
+ path::PathBuf,
+};
+
+/// Platform-specific implementation of [`SingleInstance`].
+pub(crate) struct SingleInstance {
+ /// File that holds the lock.
+ ///
+ /// The lock is automatically released when the [`File`] is dropped.
+ _file: File,
+}
+
+impl SingleInstance {
+ /// Implements [`SingleInstance::new`].
+ pub(crate) fn new() -> crate::Result<Self> {
+ let path = Self::lock_file_path()?;
+
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent).map_err(crate::Error::Io)?;
+ }
+
+ let file = File::create(&path).map_err(crate::Error::Io)?;
+
+ // Acquire exclusive file lock.
+ file.try_lock().map_err(|err| match err {
+ TryLockError::WouldBlock => crate::Error::Platform(
+ "Another instance of the application is already running."
+ .to_string(),
+ ),
+ TryLockError::Error(io_err) => crate::Error::Io(io_err),
+ })?;
+
+ Ok(Self { _file: file })
+ }
+
+ /// Implements [`SingleInstance::is_running`].
+ #[must_use]
+ pub(crate) fn is_running() -> bool {
+ let Ok(file) = Self::lock_file_path()
+ .and_then(|path| File::open(&path).map_err(crate::Error::Io))
+ else {
+ return false;
+ };
+
+ // If `try_lock` fails with `WouldBlock`, the lock is held by another
+ // process.
+ file
+ .try_lock()
+ .is_err_and(|err| matches!(err, TryLockError::WouldBlock))
+ }
+
+ /// Returns the path to the lock file:
+ /// `~/Library/Application Support/glazewm/.lock`.
+ fn lock_file_path() -> crate::Result<PathBuf> {
+ let home = home::home_dir().ok_or_else(|| {
+ crate::Error::Platform(
+ "Unable to determine home directory.".to_string(),
+ )
+ })?;
+
+ Ok(home.join("Library/Application Support/glazewm/.lock"))
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/macos/window_listener.rs b/packages/wm-platform/src/platform_impl/macos/window_listener.rs
new file mode 100644
index 00000000..9697d49b
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/macos/window_listener.rs
@@ -0,0 +1,239 @@
+use std::collections::HashMap;
+
+use objc2::rc::Retained;
+use objc2_app_kit::NSWorkspace;
+use tokio::sync::mpsc;
+
+use crate::{
+ platform_impl::{
+ self, Application, ApplicationObserver, NotificationCenter,
+ NotificationEvent, NotificationName, NotificationObserver, ProcessId,
+ },
+ Dispatcher, ThreadBound, WindowEvent,
+};
+
+/// Platform-specific implementation of [`WindowEventNotification`].
+#[derive(Clone, Debug)]
+pub struct WindowEventNotificationInner {
+ /// Name of the notification (e.g. `AXWindowMoved`).
+ pub name: String,
+
+ /// Pointer to the `AXUIElement` that triggered the notification.
+ pub ax_element_ptr: *mut std::ffi::c_void,
+}
+
+unsafe impl Send for WindowEventNotificationInner {}
+
+/// Platform-specific implementation of [`WindowListener`].
+#[derive(Debug)]
+pub(crate) struct WindowListener {
+ /// Workspace notification observer, bound to the main thread.
+ observer: Option<ThreadBound<Retained<NotificationObserver>>>,
+}
+
+impl WindowListener {
+ /// Implements [`WindowListener::new`].
+ pub(crate) fn new(
+ events_tx: mpsc::UnboundedSender<WindowEvent>,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<Self> {
+ let observer = dispatcher
+ .dispatch_sync(|| Self::init(events_tx, dispatcher.clone()))??;
+
+ Ok(Self {
+ observer: Some(observer),
+ })
+ }
+
+ /// Implements [`WindowListener::terminate`].
+ pub(crate) fn terminate(&mut self) {
+ // On macOS 10.11+, observer subscriptions are cleaned up automatically
+ // without calling `removeObserver`.
+ // Ref: https://developer.apple.com/documentation/foundation/notificationcenter/removeobserver(_:name:object:)
+ //
+ // Dropping the `NotificationObserver` also drops its channel sender,
+ // causing the listener thread to exit.
+ self.observer.take();
+ }
+
+ fn init(
+ events_tx: mpsc::UnboundedSender<WindowEvent>,
+ dispatcher: Dispatcher,
+ ) -> crate::Result<ThreadBound<Retained<NotificationObserver>>> {
+ let (observer, events_rx) = NotificationObserver::new();
+
+ let workspace = unsafe { NSWorkspace::sharedWorkspace() };
+ let mut workspace_center = NotificationCenter::workspace_center();
+
+ for notification in [
+ NotificationName::WorkspaceActiveSpaceDidChange,
+ NotificationName::WorkspaceDidLaunchApplication,
+ NotificationName::WorkspaceDidActivateApplication,
+ NotificationName::WorkspaceDidTerminateApplication,
+ NotificationName::WorkspaceDidHideApplication,
+ NotificationName::WorkspaceDidUnhideApplication,
+ ] {
+ unsafe {
+ workspace_center.add_observer(
+ notification,
+ &observer,
+ Some(&workspace),
+ );
+ }
+ }
+
+ let running_apps = platform_impl::all_applications(&dispatcher)?;
+
+ // Create observers for all running applications.
+ let app_observers = running_apps
+ .into_iter()
+ .filter_map(|app| {
+ Self::create_app_observer(&app, events_tx.clone()).ok()
+ })
+ .collect::<Vec<_>>();
+
+ tracing::info!(
+ "Registered observers for {} existing applications.",
+ app_observers.len()
+ );
+
+ let dispatcher_clone = dispatcher.clone();
+ std::thread::spawn(move || {
+ Self::listen_workspace_events(
+ app_observers,
+ events_rx,
+ &events_tx,
+ &dispatcher_clone,
+ );
+ });
+
+ Ok(ThreadBound::new(observer, dispatcher))
+ }
+
+ fn listen_workspace_events(
+ app_observers: Vec<ApplicationObserver>,
+ mut events_rx: mpsc::UnboundedReceiver<NotificationEvent>,
+ events_tx: &mpsc::UnboundedSender<WindowEvent>,
+ dispatcher: &Dispatcher,
+ ) {
+ // Track window observers for each application by PID.
+ let mut app_observers: HashMap<ProcessId, ApplicationObserver> =
+ app_observers
+ .into_iter()
+ .map(|observer| (observer.pid, observer))
+ .collect();
+
+ // Loop exits when the sender is dropped in `Self::terminate`.
+ while let Some(event) = events_rx.blocking_recv() {
+ tracing::debug!("Received workspace event: {event:?}");
+
+ match event {
+ NotificationEvent::WorkspaceDidLaunchApplication(running_app) => {
+ let events_tx = events_tx.clone();
+
+ let Ok(Ok(app_observer)) = dispatcher.dispatch_sync(|| {
+ let app = Application::new(running_app, dispatcher.clone());
+ if !app.should_observe() {
+ return Err(crate::Error::Platform(format!(
+ "Skipped observer registration for PID {} (should ignore).",
+ app.pid,
+ )));
+ }
+
+ ApplicationObserver::new(&app, events_tx.clone(), false)
+ }) else {
+ continue;
+ };
+
+ if app_observers.contains_key(&app_observer.pid) {
+ tracing::debug!(
+ "Observer already exists for PID {}.",
+ app_observer.pid
+ );
+ continue;
+ }
+
+ app_observers.insert(app_observer.pid, app_observer);
+ }
+ NotificationEvent::WorkspaceDidTerminateApplication(
+ running_app,
+ ) => {
+ let pid = unsafe { running_app.processIdentifier() };
+
+ if let Some(observer) = app_observers.remove(&pid) {
+ tracing::info!(
+ "Removed window observer for terminated PID: {}",
+ pid
+ );
+
+ observer.emit_all_windows_destroyed();
+ }
+ }
+ NotificationEvent::WorkspaceDidActivateApplication(
+ running_app,
+ ) => {
+ let Ok(Ok(Some(focused_window))) =
+ dispatcher.dispatch_sync(|| {
+ let app = Application::new(running_app, dispatcher.clone());
+ app.focused_window()
+ })
+ else {
+ continue;
+ };
+
+ let _ = events_tx.send(WindowEvent::Focused {
+ window: focused_window,
+ notification: crate::WindowEventNotification(None),
+ });
+ }
+ NotificationEvent::WorkspaceDidHideApplication(running_app) => {
+ if let Some(app_observer) =
+ app_observers.get(unsafe { &running_app.processIdentifier() })
+ {
+ app_observer.emit_all_windows_hidden();
+ }
+ }
+ NotificationEvent::WorkspaceDidUnhideApplication(running_app) => {
+ if let Some(app_observer) =
+ app_observers.get(unsafe { &running_app.processIdentifier() })
+ {
+ app_observer.emit_all_windows_shown();
+ }
+ }
+ _ => {}
+ }
+ }
+
+ tracing::debug!("Window listener thread exited.");
+ }
+
+ fn create_app_observer(
+ app: &Application,
+ events_tx: mpsc::UnboundedSender<WindowEvent>,
+ ) -> crate::Result<ApplicationObserver> {
+ if !app.should_observe() {
+ return Err(crate::Error::Platform(format!(
+ "Skipped observer registration for PID {} (should ignore).",
+ app.pid,
+ )));
+ }
+
+ let app_observer_res = ApplicationObserver::new(app, events_tx, true);
+
+ if let Err(err) = &app_observer_res {
+ tracing::debug!(
+ "Skipped observer registration for PID {}: {}",
+ app.pid,
+ err
+ );
+ }
+
+ app_observer_res
+ }
+}
+
+impl Drop for WindowListener {
+ fn drop(&mut self) {
+ self.terminate();
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/mod.rs b/packages/wm-platform/src/platform_impl/mod.rs
new file mode 100644
index 00000000..1a225c80
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/mod.rs
@@ -0,0 +1,11 @@
+#[cfg(target_os = "windows")]
+#[path = "windows/mod.rs"]
+mod platform;
+#[cfg(target_os = "macos")]
+#[path = "macos/mod.rs"]
+mod platform;
+
+pub(crate) use platform::*;
+
+#[cfg(all(not(target_os = "windows"), not(target_os = "macos"),))]
+compile_error!("The platform you're compiling for is not supported.");
diff --git a/packages/wm-platform/src/com.rs b/packages/wm-platform/src/platform_impl/windows/com.rs
similarity index 81%
rename from packages/wm-platform/src/com.rs
rename to packages/wm-platform/src/platform_impl/windows/com.rs
index 9fb6de34..c83619f0 100644
--- a/packages/wm-platform/src/com.rs
+++ b/packages/wm-platform/src/platform_impl/windows/com.rs
@@ -1,6 +1,5 @@
use std::cell::RefCell;
-use anyhow::Context;
use windows::{
core::{ComInterface, IUnknown, IUnknown_Vtbl, GUID, HRESULT},
Win32::{
@@ -14,7 +13,7 @@ use windows::{
/// COM class identifier (CLSID) for the Windows Shell that implements the
/// `IServiceProvider` interface.
-pub const CLSID_IMMERSIVE_SHELL: GUID =
+const CLSID_IMMERSIVE_SHELL: GUID =
GUID::from_u128(0xC2F03A33_21F5_47FA_B4BB_156362A2F239);
thread_local! {
@@ -23,10 +22,10 @@ thread_local! {
/// the setup and cleanup automatically.
///
/// Wrapped in `RefCell` to allow mutation via `COM_INIT.borrow_mut()`.
- pub static COM_INIT: RefCell<ComInit> = RefCell::new(ComInit::new());
+ pub(crate) static COM_INIT: RefCell<ComInit> = RefCell::new(ComInit::new());
}
-pub struct ComInit {
+pub(crate) struct ComInit {
service_provider: Option<IServiceProvider>,
application_view_collection: Option<IApplicationViewCollection>,
taskbar_list: Option<ITaskbarList2>,
@@ -41,7 +40,7 @@ impl ComInit {
/// Panics if COM initialization fails. This is typically only possible
/// if COM is already initialized with an incompatible threading model.
#[must_use]
- pub fn new() -> Self {
+ pub(crate) fn new() -> Self {
unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }
.expect("Unable to initialize COM.");
@@ -66,36 +65,32 @@ impl ComInit {
}
}
- /// Returns an instance of `IServiceProvider`.
- pub fn service_provider(&self) -> anyhow::Result<&IServiceProvider> {
- self
- .service_provider
- .as_ref()
- .context("Unable to create `IServiceProvider` instance.")
- }
-
/// Returns an instance of `IApplicationViewCollection`.
- pub fn application_view_collection(
+ pub(crate) fn application_view_collection(
&self,
- ) -> anyhow::Result<&IApplicationViewCollection> {
- self.application_view_collection.as_ref().context(
- "Failed to query for `IApplicationViewCollection` instance.",
- )
+ ) -> crate::Result<&IApplicationViewCollection> {
+ self.application_view_collection.as_ref().ok_or_else(|| {
+ crate::Error::Platform(
+ "Failed to query for `IApplicationViewCollection` instance."
+ .to_string(),
+ )
+ })
}
/// Returns an instance of `ITaskbarList2`.
- pub fn taskbar_list(&self) -> anyhow::Result<&ITaskbarList2> {
- self
- .taskbar_list
- .as_ref()
- .context("Unable to create `ITaskbarList2` instance.")
+ pub(crate) fn taskbar_list(&self) -> crate::Result<&ITaskbarList2> {
+ self.taskbar_list.as_ref().ok_or_else(|| {
+ crate::Error::Platform(
+ "Unable to create `ITaskbarList2` instance.".to_string(),
+ )
+ })
}
/// Refreshes cached COM interfaces.
///
/// Called automatically by `with_retry` when COM operations fail due to
- /// stale interface pointers (e.g., after Explorer restarts).
- pub fn refresh(&mut self) {
+ /// stale interface pointers (e.g. after Explorer restarts).
+ pub(crate) fn refresh(&mut self) {
// Re-create the service provider.
self.service_provider = unsafe {
CoCreateInstance(&CLSID_IMMERSIVE_SHELL, None, CLSCTX_ALL)
@@ -118,9 +113,9 @@ impl ComInit {
/// Executes a COM operation, refreshing interfaces on failure and
/// retrying once. Use this for operations that may fail due to stale
/// COM interfaces.
- pub fn with_retry<T, F>(&mut self, op: F) -> anyhow::Result<T>
+ pub fn with_retry<T, F>(&mut self, op: F) -> crate::Result<T>
where
- F: Fn(&Self) -> anyhow::Result<T>,
+ F: Fn(&Self) -> crate::Result<T>,
{
if let Ok(result) = op(self) {
Ok(result)
diff --git a/packages/wm-platform/src/platform_impl/windows/display.rs b/packages/wm-platform/src/platform_impl/windows/display.rs
new file mode 100644
index 00000000..3c9e70b4
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/windows/display.rs
@@ -0,0 +1,432 @@
+use windows::{
+ core::PCWSTR,
+ Win32::{
+ Foundation::{BOOL, LPARAM, POINT, RECT},
+ Graphics::Gdi::{
+ EnumDisplayDevicesW, EnumDisplayMonitors, EnumDisplaySettingsW,
+ GetMonitorInfoW, MonitorFromPoint, MonitorFromWindow, DEVMODEW,
+ DISPLAY_DEVICEW, DISPLAY_DEVICE_ACTIVE, ENUM_CURRENT_SETTINGS, HDC,
+ HMONITOR, MONITORINFO, MONITORINFOEXW, MONITOR_DEFAULTTONEAREST,
+ MONITOR_DEFAULTTOPRIMARY,
+ },
+ UI::{
+ HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI},
+ WindowsAndMessaging::EDD_GET_DEVICE_INTERFACE_NAME,
+ },
+ },
+};
+
+use crate::{
+ display::{
+ ConnectionState, DisplayDeviceId, DisplayId, MirroringState,
+ OutputTechnology,
+ },
+ Dispatcher, NativeWindow, Point, Rect,
+};
+
+/// Platform-specific implementation of [`Display`].
+#[derive(Clone, Debug)]
+pub(crate) struct Display {
+ pub(crate) monitor_handle: isize,
+}
+
+impl Display {
+ /// Creates an instance of `Display`.
+ #[must_use]
+ pub(crate) fn new(monitor_handle: isize) -> Self {
+ Self { monitor_handle }
+ }
+
+ /// Implements [`Display::id`].
+ pub(crate) fn id(&self) -> DisplayId {
+ DisplayId(self.monitor_handle)
+ }
+
+ /// Implements [`Display::name`].
+ pub(crate) fn name(&self) -> crate::Result<String> {
+ Ok(
+ String::from_utf16_lossy(&self.monitor_info_ex()?.szDevice)
+ .trim_end_matches('\0')
+ .to_string(),
+ )
+ }
+
+ /// Implements [`Display::bounds`].
+ pub(crate) fn bounds(&self) -> crate::Result<Rect> {
+ let rc = self.monitor_info_ex()?.monitorInfo.rcMonitor;
+ Ok(Rect::from_ltrb(rc.left, rc.top, rc.right, rc.bottom))
+ }
+
+ /// Implements [`Display::working_area`].
+ pub(crate) fn working_area(&self) -> crate::Result<Rect> {
+ let rc = self.monitor_info_ex()?.monitorInfo.rcWork;
+ Ok(Rect::from_ltrb(rc.left, rc.top, rc.right, rc.bottom))
+ }
+
+ /// Implements [`Display::scale_factor`].
+ pub(crate) fn scale_factor(&self) -> crate::Result<f32> {
+ let dpi = self.dpi()?;
+ #[allow(clippy::cast_precision_loss)]
+ Ok(dpi as f32 / 96.0)
+ }
+
+ /// Implements [`Display::dpi`].
+ pub(crate) fn dpi(&self) -> crate::Result<u32> {
+ let mut dpi_x = u32::default();
+ let mut dpi_y = u32::default();
+
+ unsafe {
+ GetDpiForMonitor(
+ HMONITOR(self.monitor_handle),
+ MDT_EFFECTIVE_DPI,
+ &raw mut dpi_x,
+ &raw mut dpi_y,
+ )
+ }?;
+
+ // Arbitrarily choose the Y DPI.
+ Ok(dpi_y)
+ }
+
+ /// Implements [`Display::is_primary`].
+ pub(crate) fn is_primary(&self) -> crate::Result<bool> {
+ // Check for `MONITORINFOF_PRIMARY` flag (`0x1`).
+ Ok(self.monitor_info_ex()?.monitorInfo.dwFlags & 0x1 != 0)
+ }
+
+ /// Implements [`Display::devices`].
+ pub(crate) fn devices(
+ &self,
+ ) -> crate::Result<Vec<crate::DisplayDevice>> {
+ let monitor_info = self.monitor_info_ex()?;
+
+ let adapter_name = String::from_utf16_lossy(&monitor_info.szDevice)
+ .trim_end_matches('\0')
+ .to_string();
+
+ // Get the display devices associated with the display's adapter.
+ let devices = (0u32..)
+ .map_while(|index| {
+ #[allow(clippy::cast_possible_truncation)]
+ let mut device = DISPLAY_DEVICEW {
+ cb: std::mem::size_of::<DISPLAY_DEVICEW>() as u32,
+ ..Default::default()
+ };
+
+ // When passing the `EDD_GET_DEVICE_INTERFACE_NAME` flag, the
+ // returned `DISPLAY_DEVICEW` will contain the device path in the
+ // `DeviceID` field.
+ unsafe {
+ EnumDisplayDevicesW(
+ PCWSTR(monitor_info.szDevice.as_ptr()),
+ index,
+ &raw mut device,
+ EDD_GET_DEVICE_INTERFACE_NAME,
+ )
+ }
+ .as_bool()
+ .then_some(device)
+ })
+ // Filter out any devices that are not active.
+ .filter(|device| device.StateFlags & DISPLAY_DEVICE_ACTIVE != 0)
+ .map(|device| {
+ DisplayDevice::new(adapter_name.clone(), &device.DeviceID).into()
+ })
+ .collect();
+
+ Ok(devices)
+ }
+
+ /// Implements [`Display::main_device`].
+ pub(crate) fn main_device(&self) -> crate::Result<crate::DisplayDevice> {
+ self
+ .devices()?
+ .into_iter()
+ .find(|device| {
+ matches!(
+ device.mirroring_state(),
+ Ok(None | Some(MirroringState::Source))
+ )
+ })
+ .ok_or(crate::Error::DisplayDeviceNotFound)
+ }
+
+ /// Implements [`DisplayExtWindows::hmonitor`].
+ pub(crate) fn hmonitor(&self) -> HMONITOR {
+ HMONITOR(self.monitor_handle)
+ }
+
+ /// Ref: <https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmonitorinfow>
+ fn monitor_info_ex(&self) -> crate::Result<MONITORINFOEXW> {
+ let mut monitor_info = MONITORINFOEXW {
+ monitorInfo: MONITORINFO {
+ #[allow(clippy::cast_possible_truncation)]
+ cbSize: std::mem::size_of::<MONITORINFOEXW>() as u32,
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ unsafe {
+ GetMonitorInfoW(
+ HMONITOR(self.monitor_handle),
+ std::ptr::from_mut(&mut monitor_info).cast(),
+ )
+ }
+ .ok()?;
+
+ Ok(monitor_info)
+ }
+}
+
+impl From<Display> for crate::Display {
+ fn from(display: Display) -> Self {
+ crate::Display { inner: display }
+ }
+}
+
+impl PartialEq for Display {
+ fn eq(&self, other: &Self) -> bool {
+ self.monitor_handle == other.monitor_handle
+ }
+}
+
+impl Eq for Display {}
+
+/// Platform-specific implementation of [`DisplayDevice`].
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct DisplayDevice {
+ /// Display adapter name (e.g. `\\.\DISPLAY1`).
+ adapter_name: String,
+
+ /// Device interface path (e.g.
+ /// `\\?\DISPLAY#DEL40A3#5&1234abcd&0&UID256#
+ /// {e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}`).
+ pub(crate) device_path: Option<String>,
+}
+
+impl DisplayDevice {
+ /// Creates an instance of `DisplayDevice`.
+ #[must_use]
+ pub(crate) fn new(adapter_name: String, device_path: &[u16]) -> Self {
+ // NOTE: This may be an empty string for virtual display devices.
+ let device_path = String::from_utf16_lossy(device_path)
+ .trim_end_matches('\0')
+ .to_string();
+
+ // Check that the device path is valid. If not, set it to `None`.
+ let device_path =
+ (device_path.split('#').count() >= 4).then_some(device_path);
+
+ Self {
+ adapter_name,
+ device_path,
+ }
+ }
+
+ /// Implements [`DisplayDevice::id`].
+ pub(crate) fn id(&self) -> DisplayDeviceId {
+ // TODO: Display adapter name might not be unique.
+ DisplayDeviceId(
+ self
+ .hardware_id()
+ .unwrap_or_else(|| self.adapter_name.clone()),
+ )
+ }
+
+ /// Implements [`DisplayDevice::rotation`].
+ pub(crate) fn rotation(&self) -> crate::Result<f32> {
+ let orientation = unsafe {
+ self
+ .current_device_mode()?
+ .Anonymous1
+ .Anonymous2
+ .dmDisplayOrientation
+ };
+
+ Ok(match orientation.0 {
+ 1 => 90.0,
+ 2 => 180.0,
+ 3 => 270.0,
+ _ => 0.0,
+ })
+ }
+
+ /// Implements [`DisplayDevice::refresh_rate`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn refresh_rate(&self) -> crate::Result<f32> {
+ #[allow(clippy::cast_precision_loss)]
+ Ok(self.current_device_mode()?.dmDisplayFrequency as f32)
+ }
+
+ /// Implements [`DisplayDevice::is_builtin`].
+ #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
+ pub(crate) fn is_builtin(&self) -> crate::Result<bool> {
+ // TODO: Use `DisplayConfigGetDeviceInfo` to determine whether the
+ // output technology is internal.
+ Ok(false)
+ }
+
+ /// Implements [`DisplayDevice::connection_state`].
+ #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
+ pub(crate) fn connection_state(&self) -> crate::Result<ConnectionState> {
+ // TODO: Detect disconnected state.
+ Ok(ConnectionState::Active)
+ }
+
+ /// Implements [`DisplayDevice::mirroring_state`].
+ #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
+ pub(crate) fn mirroring_state(
+ &self,
+ ) -> crate::Result<Option<MirroringState>> {
+ // TODO: Implement mirroring detection using
+ // `DisplayConfigGetDeviceInfo`.
+ Ok(None)
+ }
+
+ /// Implements [`DisplayDeviceExtWindows::hardware_id`].
+ pub(crate) fn hardware_id(&self) -> Option<String> {
+ self
+ .device_path
+ .as_deref()?
+ .split('#')
+ .nth(1)
+ .map(ToString::to_string)
+ }
+
+ /// Implements [`DisplayDeviceExtWindows::output_technology`].
+ #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
+ pub(crate) fn output_technology(
+ &self,
+ ) -> crate::Result<Option<OutputTechnology>> {
+ // TODO: Use `DisplayConfigGetDeviceInfo` to get the output technology.
+ Ok(Some(OutputTechnology::Unknown))
+ }
+
+ /// Gets the current device mode.
+ fn current_device_mode(&self) -> crate::Result<DEVMODEW> {
+ #[allow(clippy::cast_possible_truncation)]
+ let mut device_mode = DEVMODEW {
+ dmSize: std::mem::size_of::<DEVMODEW>() as u16,
+ ..Default::default()
+ };
+
+ let wide_adapter_name = self
+ .adapter_name
+ .encode_utf16()
+ .chain(std::iter::once(0))
+ .collect::<Vec<_>>();
+
+ unsafe {
+ EnumDisplaySettingsW(
+ PCWSTR(wide_adapter_name.as_ptr()),
+ ENUM_CURRENT_SETTINGS,
+ &raw mut device_mode,
+ )
+ }
+ .ok()?;
+
+ Ok(device_mode)
+ }
+}
+
+impl From<DisplayDevice> for crate::DisplayDevice {
+ fn from(device: DisplayDevice) -> Self {
+ crate::DisplayDevice { inner: device }
+ }
+}
+
+/// Implements [`Dispatcher::displays`].
+pub(crate) fn all_displays(
+ _: &Dispatcher,
+) -> crate::Result<Vec<crate::Display>> {
+ let mut monitor_handles: Vec<isize> = Vec::new();
+
+ // Callback for `EnumDisplayMonitors` to collect monitor handles.
+ #[allow(clippy::items_after_statements)]
+ extern "system" fn monitor_enum_proc(
+ handle: HMONITOR,
+ _hdc: HDC,
+ _clip: *mut RECT,
+ data: LPARAM,
+ ) -> BOOL {
+ let handles = data.0 as *mut Vec<isize>;
+
+ // SAFETY: `data` is a valid pointer to the `monitor_handles` vec,
+ // which outlives this callback.
+ unsafe { (*handles).push(handle.0) };
+ true.into()
+ }
+
+ unsafe {
+ EnumDisplayMonitors(
+ HDC::default(),
+ None,
+ Some(monitor_enum_proc),
+ LPARAM(std::ptr::from_mut(&mut monitor_handles) as _),
+ )
+ }
+ .ok()?;
+
+ Ok(
+ monitor_handles
+ .into_iter()
+ .map(|handle| Display::new(handle).into())
+ .collect(),
+ )
+}
+
+/// Implements [`Dispatcher::display_devices`].
+pub(crate) fn all_display_devices(
+ dispatcher: &Dispatcher,
+) -> crate::Result<Vec<crate::DisplayDevice>> {
+ all_displays(dispatcher)?
+ .into_iter()
+ .map(|display| display.devices())
+ .collect::<crate::Result<Vec<_>>>()
+ .map(|vecs| vecs.into_iter().flatten().collect())
+}
+
+/// Implements [`Dispatcher::display_from_point`].
+#[allow(clippy::unnecessary_wraps)]
+pub(crate) fn display_from_point(
+ point: &Point,
+ _: &Dispatcher,
+) -> crate::Result<crate::Display> {
+ let handle = unsafe {
+ MonitorFromPoint(
+ POINT {
+ x: point.x,
+ y: point.y,
+ },
+ MONITOR_DEFAULTTOPRIMARY,
+ )
+ };
+
+ Ok(Display::new(handle.0).into())
+}
+
+/// Implements [`Dispatcher::primary_display`].
+#[allow(clippy::unnecessary_wraps)]
+pub(crate) fn primary_display(
+ _: &Dispatcher,
+) -> crate::Result<crate::Display> {
+ let handle = unsafe {
+ MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY)
+ };
+
+ Ok(Display::new(handle.0).into())
+}
+
+/// Implements [`Dispatcher::nearest_display`].
+#[allow(clippy::unnecessary_wraps)]
+pub(crate) fn nearest_display(
+ native_window: &NativeWindow,
+ _: &Dispatcher,
+) -> crate::Result<crate::Display> {
+ let handle = unsafe {
+ MonitorFromWindow(native_window.inner.hwnd(), MONITOR_DEFAULTTONEAREST)
+ };
+
+ Ok(Display::new(handle.0).into())
+}
diff --git a/packages/wm-platform/src/platform_impl/windows/display_listener.rs b/packages/wm-platform/src/platform_impl/windows/display_listener.rs
new file mode 100644
index 00000000..64a7b987
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/windows/display_listener.rs
@@ -0,0 +1,110 @@
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+};
+
+use tokio::sync::mpsc;
+use tracing::warn;
+use windows::Win32::UI::WindowsAndMessaging::{
+ DBT_DEVNODES_CHANGED, PBT_APMRESUMEAUTOMATIC, PBT_APMRESUMESUSPEND,
+ PBT_APMSUSPEND, SPI_SETWORKAREA, WM_DEVICECHANGE, WM_DISPLAYCHANGE,
+ WM_POWERBROADCAST, WM_SETTINGCHANGE,
+};
+
+use crate::{Dispatcher, DispatcherExtWindows};
+
+/// Platform-specific implementation of [`DisplayListener`].
+pub(crate) struct DisplayListener {
+ callback_id: Option<usize>,
+ dispatcher: Dispatcher,
+}
+
+impl DisplayListener {
+ /// Implements [`DisplayListener::new`].
+ pub(crate) fn new(
+ event_tx: mpsc::UnboundedSender<()>,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<Self> {
+ let is_system_suspended = Arc::new(AtomicBool::new(false));
+
+ let callback_id = dispatcher.register_wndproc_callback(Box::new(
+ move |_hwnd, message, wparam, _lparam| {
+ match message {
+ WM_POWERBROADCAST => {
+ #[allow(clippy::cast_possible_truncation)]
+ match wparam as u32 {
+ // System is resuming from sleep/hibernation.
+ PBT_APMRESUMEAUTOMATIC | PBT_APMRESUMESUSPEND => {
+ is_system_suspended.store(false, Ordering::Relaxed);
+ }
+ // System is entering sleep/hibernation.
+ PBT_APMSUSPEND => {
+ is_system_suspended.store(true, Ordering::Relaxed);
+ }
+ _ => {}
+ }
+
+ Some(0)
+ }
+ WM_DISPLAYCHANGE | WM_SETTINGCHANGE | WM_DEVICECHANGE => {
+ let should_emit = {
+ // Ignore display change messages if the system hasn't fully
+ // resumed from sleep.
+ if is_system_suspended.load(Ordering::Relaxed) {
+ false
+ } else {
+ #[allow(clippy::cast_possible_truncation)]
+ match message {
+ // Received when displays are connected and disconnected,
+ // resolution changes, or arrangement changes.
+ WM_DISPLAYCHANGE => true,
+ // Received when the working area has changed. Fires when
+ // the Windows taskbar is changed or an appbar is
+ // registered or changed. 3rd-party apps like
+ // ButteryTaskbar can trigger this message by calling
+ // `SystemParametersInfo(SPI_SETWORKAREA, ...)`.
+ WM_SETTINGCHANGE => wparam as u32 == SPI_SETWORKAREA.0,
+ // Received when any device is connected or disconnected
+ // (including non-display devices).
+ // TODO: Check if this is actually needed. Previous C#
+ // implementation did not use this.
+ WM_DEVICECHANGE => wparam as u32 == DBT_DEVNODES_CHANGED,
+ _ => unreachable!(),
+ }
+ }
+ };
+
+ if should_emit {
+ let _ = event_tx.send(());
+ }
+
+ Some(0)
+ }
+ _ => None,
+ }
+ },
+ ))?;
+
+ Ok(Self {
+ callback_id: Some(callback_id),
+ dispatcher: dispatcher.clone(),
+ })
+ }
+
+ /// Implements [`DisplayListener::terminate`].
+ pub(crate) fn terminate(&mut self) -> crate::Result<()> {
+ if let Some(id) = self.callback_id.take() {
+ self.dispatcher.deregister_wndproc_callback(id)?;
+ }
+
+ Ok(())
+ }
+}
+
+impl Drop for DisplayListener {
+ fn drop(&mut self) {
+ if let Err(err) = self.terminate() {
+ warn!("Failed to terminate display listener: {}", err);
+ }
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/windows/event_loop.rs b/packages/wm-platform/src/platform_impl/windows/event_loop.rs
new file mode 100644
index 00000000..1f3ab96c
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/windows/event_loop.rs
@@ -0,0 +1,297 @@
+use std::{
+ cell::RefCell,
+ collections::HashMap,
+ sync::{
+ atomic::{AtomicBool, AtomicUsize, Ordering},
+ Arc,
+ },
+ thread::{self, ThreadId},
+};
+
+use windows::{
+ core::w,
+ Win32::{
+ Foundation::{HWND, LPARAM, LRESULT, WPARAM},
+ System::Threading::GetCurrentThreadId,
+ UI::WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW,
+ GetMessageW, PostMessageW, PostThreadMessageW, RegisterClassW,
+ RegisterWindowMessageW, SendMessageW, TranslateMessage, CS_HREDRAW,
+ CS_VREDRAW, CW_USEDEFAULT, MSG, WINDOW_EX_STYLE, WM_QUIT, WNDCLASSW,
+ WNDPROC, WS_OVERLAPPEDWINDOW,
+ },
+ },
+};
+
+use crate::{DispatchFn, Dispatcher, WndProcCallback};
+
+thread_local! {
+ /// Custom message ID for dispatching closures to be run on the event
+ /// loop thread.
+ ///
+ /// `WPARAM` contains a `Box<Box<dyn FnOnce()>>` that must be retrieved
+ /// with `Box::from_raw`. `LPARAM` is unused.
+ ///
+ /// This message is sent using `PostMessageW` and handled in
+ /// [`EventLoop::window_proc`].
+ static WM_DISPATCH_CALLBACK: u32 = unsafe { RegisterWindowMessageW(w!("GlazeWM:Dispatch")) };
+
+ /// Registered callbacks that pre-process messages in the event loop's
+ /// window procedure.
+ ///
+ /// Keyed by a unique callback ID for later deregistration.
+ static WNDPROC_CALLBACKS: RefCell<HashMap<usize, Box<WndProcCallback>>> =
+ RefCell::new(HashMap::new());
+}
+
+/// Source for dispatching callbacks onto the event loop thread.
+#[derive(Clone)]
+pub(crate) struct EventLoopSource {
+ pub(crate) message_window_handle: isize,
+ pub(crate) thread_id: ThreadId,
+ os_thread_id: u32,
+ next_callback_id: Arc<AtomicUsize>,
+}
+
+impl EventLoopSource {
+ pub(crate) fn send_dispatch_async<F>(
+ &self,
+ dispatch_fn: F,
+ ) -> crate::Result<()>
+ where
+ F: FnOnce() + Send + 'static,
+ {
+ // Double box the callback to avoid `STATUS_ACCESS_VIOLATION` on
+ // Windows. Ref: https://github.com/tauri-apps/tao/blob/dev/src/platform_impl/windows/event_loop.rs#L596
+ let dispatch_fn: Box<Box<DispatchFn>> =
+ Box::new(Box::new(dispatch_fn));
+
+ // Leak to a raw pointer to then be passed as `WPARAM` in the message.
+ let callback_ptr = Box::into_raw(dispatch_fn);
+
+ unsafe {
+ if PostMessageW(
+ HWND(self.message_window_handle),
+ WM_DISPATCH_CALLBACK.with(|v| *v),
+ WPARAM(callback_ptr as _),
+ LPARAM(0),
+ )
+ .is_ok()
+ {
+ Ok(())
+ } else {
+ // If `PostMessage` fails, we need to clean up the callback.
+ let _ = Box::from_raw(callback_ptr);
+ Err(crate::Error::WindowMessage(
+ "Failed to post message".to_string(),
+ ))
+ }
+ }
+ }
+
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn send_dispatch_sync<F>(
+ &self,
+ dispatch_fn: F,
+ ) -> crate::Result<()>
+ where
+ F: FnOnce() + Send,
+ {
+ let dispatch_fn: Box<Box<dyn FnOnce() + Send>> =
+ Box::new(Box::new(dispatch_fn));
+ let callback_ptr = Box::into_raw(dispatch_fn);
+
+ // `SendMessageW` blocks the calling thread until the window procedure
+ // processes the message and executes the closure. This guarantees the
+ // closure's lifetime remains valid.
+ unsafe {
+ SendMessageW(
+ HWND(self.message_window_handle),
+ WM_DISPATCH_CALLBACK.with(|v| *v),
+ WPARAM(callback_ptr as _),
+ LPARAM(0),
+ );
+ }
+
+ Ok(())
+ }
+
+ pub(crate) fn send_stop(&self) -> crate::Result<()> {
+ unsafe {
+ PostThreadMessageW(self.os_thread_id, WM_QUIT, WPARAM(0), LPARAM(0))
+ }
+ .map_err(|_| {
+ crate::Error::WindowMessage(
+ "Failed to post quit message".to_string(),
+ )
+ })
+ }
+
+ pub(crate) fn register_wndproc_callback(
+ &self,
+ callback: Box<WndProcCallback>,
+ ) -> crate::Result<usize> {
+ let id = self.next_callback_id.fetch_add(1, Ordering::Relaxed);
+
+ // The callback is installed asynchronously on the event loop thread.
+ self.send_dispatch_async(move || {
+ WNDPROC_CALLBACKS.with(|cbs| {
+ cbs.borrow_mut().insert(id, callback);
+ });
+ })?;
+
+ Ok(id)
+ }
+
+ pub(crate) fn deregister_wndproc_callback(
+ &self,
+ id: usize,
+ ) -> crate::Result<()> {
+ self.send_dispatch_async(move || {
+ WNDPROC_CALLBACKS.with(|cbs| {
+ cbs.borrow_mut().remove(&id);
+ });
+ })
+ }
+}
+
+/// Platform-specific implementation of [`EventLoop`].
+pub(crate) struct EventLoop {
+ source: EventLoopSource,
+}
+
+impl EventLoop {
+ /// Implements [`EventLoop::new`].
+ pub(crate) fn new() -> crate::Result<(Self, Dispatcher)> {
+ // Create a hidden message window on the current thread.
+ let window_handle =
+ Self::create_message_window(Some(Self::window_proc))?;
+
+ let source = EventLoopSource {
+ message_window_handle: window_handle,
+ thread_id: thread::current().id(),
+ os_thread_id: unsafe { GetCurrentThreadId() },
+ next_callback_id: Arc::new(AtomicUsize::new(0)),
+ };
+
+ let stopped = Arc::new(AtomicBool::new(false));
+ let dispatcher = Dispatcher::new(Some(source.clone()), stopped);
+
+ Ok((Self { source }, dispatcher))
+ }
+
+ /// Implements [`EventLoop::run`].
+ pub(crate) fn run(&self) -> crate::Result<()> {
+ tracing::info!("Starting event loop.");
+ let mut msg = MSG::default();
+
+ // Start the message loop. Blocks until `WM_QUIT` is received.
+ loop {
+ if unsafe { GetMessageW(&raw mut msg, None, 0, 0) }.as_bool() {
+ unsafe {
+ TranslateMessage(&raw const msg);
+ DispatchMessageW(&raw const msg);
+ }
+ } else {
+ break;
+ }
+ }
+
+ tracing::info!("Event loop thread exiting.");
+ unsafe { DestroyWindow(HWND(self.source.message_window_handle)) }?;
+
+ Ok(())
+ }
+
+ /// Shuts down the event loop gracefully.
+ pub(crate) fn shutdown(&mut self) -> crate::Result<()> {
+ tracing::info!("Shutting down event loop.");
+ self.source.send_stop()?;
+
+ Ok(())
+ }
+
+ /// Creates a hidden message window.
+ ///
+ /// Returns a handle to the created window.
+ fn create_message_window(
+ window_procedure: WNDPROC,
+ ) -> crate::Result<isize> {
+ let wnd_class = WNDCLASSW {
+ lpszClassName: w!("MessageWindow"),
+ style: CS_HREDRAW | CS_VREDRAW,
+ lpfnWndProc: window_procedure,
+ ..Default::default()
+ };
+
+ unsafe { RegisterClassW(&raw const wnd_class) };
+
+ let handle = unsafe {
+ CreateWindowExW(
+ WINDOW_EX_STYLE::default(),
+ w!("MessageWindow"),
+ w!("MessageWindow"),
+ WS_OVERLAPPEDWINDOW,
+ CW_USEDEFAULT,
+ CW_USEDEFAULT,
+ CW_USEDEFAULT,
+ CW_USEDEFAULT,
+ None,
+ None,
+ wnd_class.hInstance,
+ None,
+ )
+ };
+
+ if handle.0 == 0 {
+ return Err(crate::Error::Platform(
+ "Creation of message window failed.".to_string(),
+ ));
+ }
+
+ Ok(handle.0)
+ }
+
+ /// Window procedure for handling messages.
+ unsafe extern "system" fn window_proc(
+ hwnd: HWND,
+ msg: u32,
+ wparam: WPARAM,
+ lparam: LPARAM,
+ ) -> LRESULT {
+ // Handle dispatch callbacks first.
+ if msg == WM_DISPATCH_CALLBACK.with(|v| *v) {
+ // Convert the `WPARAM` fn pointer back to a double-boxed function.
+ let dispatch_fn: Box<Box<dyn FnOnce() + Send>> =
+ Box::from_raw(wparam.0 as *mut _);
+ dispatch_fn();
+ return LRESULT(0);
+ }
+
+ // Let registered callbacks pre-process the message.
+ let handled = WNDPROC_CALLBACKS.with(|cbs| {
+ for callback in cbs.borrow().values() {
+ if let Some(result) = callback(hwnd.0, msg, wparam.0, lparam.0) {
+ return Some(LRESULT(result));
+ }
+ }
+ None
+ });
+
+ if let Some(result) = handled {
+ return result;
+ }
+
+ // `WM_QUIT` is handled by the message loop and should be forwarded
+ // along with other messages.
+ DefWindowProcW(hwnd, msg, wparam, lparam)
+ }
+}
+
+impl Drop for EventLoop {
+ fn drop(&mut self) {
+ if let Err(err) = self.shutdown() {
+ tracing::warn!("Failed to shut down event loop: {err}");
+ }
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/windows/keyboard_hook.rs b/packages/wm-platform/src/platform_impl/windows/keyboard_hook.rs
new file mode 100644
index 00000000..1c76ab1a
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/windows/keyboard_hook.rs
@@ -0,0 +1,202 @@
+use std::cell::Cell;
+
+use windows::Win32::{
+ Foundation::{HINSTANCE, LPARAM, LRESULT, WPARAM},
+ UI::{
+ Input::KeyboardAndMouse::{
+ GetKeyState, VK_LCONTROL, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_RCONTROL,
+ VK_RMENU, VK_RSHIFT, VK_RWIN,
+ },
+ WindowsAndMessaging::{
+ CallNextHookEx, SetWindowsHookExW, UnhookWindowsHookEx, HHOOK,
+ KBDLLHOOKSTRUCT, WH_KEYBOARD_LL, WM_KEYDOWN, WM_SYSKEYDOWN,
+ },
+ },
+};
+
+use crate::{Dispatcher, Key, KeyCode};
+
+/// Callback stored in [`HOOK`] for intercepting keyboard events.
+type HookCallback = Box<dyn Fn(KeyEvent) -> bool>;
+
+thread_local! {
+ /// Stores the hook callback for the current thread.
+ ///
+ /// The hook callback is called for every keyboard event and returns
+ /// `true` if the event should be intercepted.
+ static HOOK: Cell<Option<HookCallback>> = Cell::default();
+}
+
+/// A key event received from the keyboard hook.
+#[derive(Clone, Debug)]
+pub struct KeyEvent {
+ /// The key that was pressed or released.
+ pub key: Key,
+
+ /// Key code that generated this event.
+ #[allow(dead_code)]
+ pub key_code: KeyCode,
+
+ /// Whether the event is for a key press or release.
+ pub is_keypress: bool,
+}
+
+impl KeyEvent {
+ /// Gets whether the specified key is currently pressed.
+ #[allow(clippy::unused_self)]
+ pub fn is_key_down(&self, key: Key) -> bool {
+ match key {
+ Key::Cmd | Key::Win => {
+ Self::is_key_down_raw(VK_LWIN.0)
+ || Self::is_key_down_raw(VK_RWIN.0)
+ }
+ Key::Alt => {
+ Self::is_key_down_raw(VK_LMENU.0)
+ || Self::is_key_down_raw(VK_RMENU.0)
+ }
+ Key::Ctrl => {
+ Self::is_key_down_raw(VK_LCONTROL.0)
+ || Self::is_key_down_raw(VK_RCONTROL.0)
+ }
+ Key::Shift => {
+ Self::is_key_down_raw(VK_LSHIFT.0)
+ || Self::is_key_down_raw(VK_RSHIFT.0)
+ }
+ _ => {
+ if let Ok(key_code) = KeyCode::try_from(key) {
+ Self::is_key_down_raw(key_code.0)
+ } else {
+ false
+ }
+ }
+ }
+ }
+
+ /// Gets whether the specified key is currently down using the raw key
+ /// code.
+ fn is_key_down_raw(key: u16) -> bool {
+ unsafe { (GetKeyState(key.into()) & 0x80) == 0x80 }
+ }
+}
+
+/// A system-wide low-level keyboard hook.
+#[derive(Debug)]
+pub struct KeyboardHook {
+ handle: HHOOK,
+ dispatcher: Dispatcher,
+}
+
+impl KeyboardHook {
+ /// Creates an instance of `KeyboardHook`.
+ ///
+ /// The callback is called for every keyboard event and returns `true` if
+ /// the event should be intercepted.
+ ///
+ /// # Panics
+ ///
+ /// Panics when attempting to register multiple hooks on the dispatcher's
+ /// thread.
+ pub fn new<F>(
+ callback: F,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<Self>
+ where
+ F: Fn(KeyEvent) -> bool + Send + Sync + 'static,
+ {
+ let handle = dispatcher.dispatch_sync(move || {
+ HOOK.with(|state| {
+ assert!(
+ state.take().is_none(),
+ "Only one keyboard hook can be registered on the dispatcher's thread."
+ );
+
+ state.set(Some(Box::new(callback)));
+ });
+
+ unsafe {
+ SetWindowsHookExW(
+ WH_KEYBOARD_LL,
+ Some(Self::hook_proc),
+ HINSTANCE::default(),
+ 0,
+ )
+ }
+ })??;
+
+ Ok(Self {
+ handle,
+ dispatcher: dispatcher.clone(),
+ })
+ }
+
+ /// Terminates the keyboard hook by unregistering it.
+ pub fn terminate(&mut self) -> crate::Result<()> {
+ unsafe { UnhookWindowsHookEx(self.handle) }?;
+
+ // Dispatch cleanup to the event loop thread since the callback
+ // is stored in a thread-local on that thread.
+ let _ = self.dispatcher.dispatch_async(|| {
+ HOOK.with(|state| {
+ state.take();
+ });
+ });
+
+ Ok(())
+ }
+
+ /// Hook procedure for keyboard events.
+ ///
+ /// For use with `SetWindowsHookExW`.
+ extern "system" fn hook_proc(
+ code: i32,
+ wparam: WPARAM,
+ lparam: LPARAM,
+ ) -> LRESULT {
+ // If the code is less than zero, the hook procedure must pass the hook
+ // notification directly to other applications.
+ if code != 0 {
+ return unsafe { CallNextHookEx(None, code, wparam, lparam) };
+ }
+
+ // Get struct with the keyboard input event.
+ let input = unsafe { *(lparam.0 as *const KBDLLHOOKSTRUCT) };
+
+ #[allow(clippy::cast_possible_truncation)]
+ let key_code = KeyCode(input.vkCode as u16);
+ #[allow(clippy::cast_possible_truncation)]
+ let is_keypress =
+ wparam.0 as u32 == WM_KEYDOWN || wparam.0 as u32 == WM_SYSKEYDOWN;
+
+ let Ok(key) = Key::try_from(key_code) else {
+ return unsafe { CallNextHookEx(None, code, wparam, lparam) };
+ };
+
+ let key_event = KeyEvent {
+ key,
+ key_code,
+ is_keypress,
+ };
+
+ let should_intercept = HOOK.with(|state| {
+ if let Some(callback) = state.take() {
+ let result = callback(key_event);
+ state.set(Some(callback));
+ result
+ } else {
+ false
+ }
+ });
+
+ if should_intercept {
+ return LRESULT(1);
+ }
+
+ unsafe { CallNextHookEx(None, code, wparam, lparam) }
+ }
+}
+
+impl Drop for KeyboardHook {
+ fn drop(&mut self) {
+ let _ = self.terminate();
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/windows/mod.rs b/packages/wm-platform/src/platform_impl/windows/mod.rs
new file mode 100644
index 00000000..819e2e96
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/windows/mod.rs
@@ -0,0 +1,18 @@
+pub(crate) mod com;
+mod display;
+mod display_listener;
+mod event_loop;
+mod keyboard_hook;
+mod mouse_listener;
+mod native_window;
+mod single_instance;
+mod window_listener;
+
+pub(crate) use display::*;
+pub(crate) use display_listener::*;
+pub(crate) use event_loop::*;
+pub(crate) use keyboard_hook::*;
+pub(crate) use mouse_listener::*;
+pub(crate) use native_window::*;
+pub(crate) use single_instance::*;
+pub(crate) use window_listener::*;
diff --git a/packages/wm-platform/src/platform_impl/windows/mouse_listener.rs b/packages/wm-platform/src/platform_impl/windows/mouse_listener.rs
new file mode 100644
index 00000000..b8ece980
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/windows/mouse_listener.rs
@@ -0,0 +1,326 @@
+use std::{
+ sync::{Arc, Mutex},
+ time::{Duration, Instant},
+};
+
+use tokio::sync::mpsc;
+use windows::Win32::{
+ Devices::HumanInterfaceDevice::{
+ HID_USAGE_GENERIC_MOUSE, HID_USAGE_PAGE_GENERIC,
+ },
+ Foundation::{HWND, POINT},
+ UI::{
+ Input::{
+ GetRawInputData, RegisterRawInputDevices, HRAWINPUT, RAWINPUT,
+ RAWINPUTDEVICE, RAWINPUTHEADER, RIDEV_INPUTSINK, RIDEV_REMOVE,
+ RID_INPUT, RIM_TYPEMOUSE,
+ },
+ WindowsAndMessaging::{
+ GetCursorPos, RI_MOUSE_LEFT_BUTTON_DOWN, RI_MOUSE_LEFT_BUTTON_UP,
+ RI_MOUSE_RIGHT_BUTTON_DOWN, RI_MOUSE_RIGHT_BUTTON_UP, WM_INPUT,
+ },
+ },
+};
+
+use super::FOREGROUND_INPUT_IDENTIFIER;
+use crate::{
+ mouse_listener::MouseEventKind,
+ platform_event::{MouseButton, MouseEvent, PressedButtons},
+ Dispatcher, DispatcherExtWindows, Point,
+};
+
+/// Data shared with the window procedure callback.
+struct CallbackData {
+ event_tx: mpsc::UnboundedSender<MouseEvent>,
+
+ /// Pressed button state tracked from events.
+ pressed: PressedButtons,
+
+ /// Timestamp of the last emitted `Move` event for throttling.
+ last_move_emission: Option<Instant>,
+}
+
+/// Platform-specific implementation of [`MouseListener`].
+pub(crate) struct MouseListener {
+ callback_id: Option<usize>,
+ callback_data: Arc<Mutex<CallbackData>>,
+ dispatcher: Dispatcher,
+}
+
+impl MouseListener {
+ /// Implements [`MouseListener::new`].
+ pub(crate) fn new(
+ enabled_events: &[MouseEventKind],
+ event_tx: mpsc::UnboundedSender<MouseEvent>,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<Self> {
+ let callback_data = Arc::new(Mutex::new(CallbackData {
+ event_tx,
+ pressed: PressedButtons::default(),
+ last_move_emission: None,
+ }));
+
+ let callback_id = Self::register_callback(
+ enabled_events,
+ Arc::clone(&callback_data),
+ dispatcher,
+ )?;
+
+ Ok(Self {
+ callback_id: Some(callback_id),
+ dispatcher: dispatcher.clone(),
+ callback_data,
+ })
+ }
+
+ /// Implements [`MouseListener::enable`].
+ pub(crate) fn enable(&mut self, enabled: bool) -> crate::Result<()> {
+ if self.callback_id.is_some() {
+ let handle = self.dispatcher.message_window_handle();
+ self.dispatcher.dispatch_sync(move || {
+ Self::enable_raw_input(handle, enabled)
+ })??;
+ }
+
+ Ok(())
+ }
+
+ /// Implements [`MouseListener::set_enabled_events`].
+ pub(crate) fn set_enabled_events(
+ &mut self,
+ enabled_events: &[MouseEventKind],
+ ) -> crate::Result<()> {
+ let _ = self.terminate();
+
+ let callback_id = Self::register_callback(
+ enabled_events,
+ Arc::clone(&self.callback_data),
+ &self.dispatcher,
+ )?;
+
+ self.callback_id = Some(callback_id);
+
+ Ok(())
+ }
+
+ /// Implements [`MouseListener::terminate`].
+ pub(crate) fn terminate(&mut self) -> crate::Result<()> {
+ self.enable(false)?;
+
+ if let Some(id) = self.callback_id.take() {
+ self.dispatcher.deregister_wndproc_callback(id)?;
+ }
+
+ Ok(())
+ }
+
+ /// Registers a window procedure callback for `WM_INPUT` and enables raw
+ /// input.
+ ///
+ /// Returns the ID of the created callback.
+ fn register_callback(
+ enabled_events: &[MouseEventKind],
+ callback_data: Arc<Mutex<CallbackData>>,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<usize> {
+ let enabled_events: Arc<[MouseEventKind]> =
+ Arc::from(enabled_events.to_vec().into_boxed_slice());
+
+ let callback_id = dispatcher.register_wndproc_callback(Box::new(
+ move |_hwnd, msg, _wparam, lparam| {
+ if msg != WM_INPUT {
+ return None;
+ }
+
+ let mut callback_data = callback_data
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+
+ if let Err(err) = Self::handle_wm_input(
+ lparam,
+ &enabled_events,
+ &mut callback_data,
+ ) {
+ tracing::warn!("Failed to handle WM_INPUT message: {}", err);
+ }
+
+ Some(0)
+ },
+ ))?;
+
+ // Register raw input devices, which will then deliver `WM_INPUT`
+ // messages to the event loop's message window.
+ let handle = dispatcher.message_window_handle();
+ dispatcher
+ .dispatch_sync(move || Self::enable_raw_input(handle, true))??;
+
+ Ok(callback_id)
+ }
+
+ /// Processes a `WM_INPUT` message, extracting raw input data and
+ /// sending the appropriate [`MouseEvent`] on the channel.
+ fn handle_wm_input(
+ lparam: isize,
+ enabled_events: &[MouseEventKind],
+ callback_data: &mut CallbackData,
+ ) -> crate::Result<()> {
+ let mut raw_input: RAWINPUT = unsafe { std::mem::zeroed() };
+ #[allow(clippy::cast_possible_truncation)]
+ let mut raw_input_size = std::mem::size_of::<RAWINPUT>() as u32;
+
+ let res_size = unsafe {
+ #[allow(clippy::cast_possible_truncation)]
+ GetRawInputData(
+ HRAWINPUT(lparam),
+ RID_INPUT,
+ Some(std::ptr::from_mut(&mut raw_input).cast()),
+ &raw mut raw_input_size,
+ std::mem::size_of::<RAWINPUTHEADER>() as u32,
+ )
+ };
+
+ // Ignore if input is invalid or not a mouse event. Inputs from our own
+ // process are also ignored, since `NativeWindow::focus` simulates
+ // mouse input.
+ #[allow(clippy::cast_possible_truncation)]
+ if res_size == 0
+ || raw_input_size == u32::MAX
+ || raw_input.header.dwType != RIM_TYPEMOUSE.0
+ || unsafe { raw_input.data.mouse.ulExtraInformation } as u32
+ == FOREGROUND_INPUT_IDENTIFIER
+ {
+ return Ok(());
+ }
+
+ // Map button flags to a `MouseEventKind`.
+ let event_kind = {
+ let button_flags = u32::from(unsafe {
+ raw_input.data.mouse.Anonymous.Anonymous.usButtonFlags
+ });
+
+ // Button flags indicate a transition in mouse button state.
+ // Ref: https://learn.microsoft.com/en-us/windows/win32/api/ntddmou/ns-ntddmou-mouse_input_data#members
+ if button_flags & RI_MOUSE_LEFT_BUTTON_DOWN != 0 {
+ MouseEventKind::LeftButtonDown
+ } else if button_flags & RI_MOUSE_LEFT_BUTTON_UP != 0 {
+ MouseEventKind::LeftButtonUp
+ } else if button_flags & RI_MOUSE_RIGHT_BUTTON_DOWN != 0 {
+ MouseEventKind::RightButtonDown
+ } else if button_flags & RI_MOUSE_RIGHT_BUTTON_UP != 0 {
+ MouseEventKind::RightButtonUp
+ } else {
+ MouseEventKind::Move
+ }
+ };
+
+ if !enabled_events.contains(&event_kind) {
+ return Ok(());
+ }
+
+ // Throttle mouse move events so that there's a minimum of 50ms between
+ // each emission. State change events (button down/up) always get
+ // emitted.
+ let should_emit = match event_kind {
+ MouseEventKind::Move => {
+ callback_data.last_move_emission.is_none_or(|timestamp| {
+ timestamp.elapsed() >= Duration::from_millis(50)
+ })
+ }
+ _ => true,
+ };
+
+ if !should_emit {
+ return Ok(());
+ }
+
+ callback_data.pressed.update(event_kind);
+
+ let mouse_event = match event_kind {
+ MouseEventKind::LeftButtonDown => MouseEvent::ButtonDown {
+ position: Self::cursor_pos()?,
+ button: MouseButton::Left,
+ pressed_buttons: callback_data.pressed,
+ },
+ MouseEventKind::LeftButtonUp => MouseEvent::ButtonUp {
+ position: Self::cursor_pos()?,
+ button: MouseButton::Left,
+ pressed_buttons: callback_data.pressed,
+ },
+ MouseEventKind::RightButtonDown => MouseEvent::ButtonDown {
+ position: Self::cursor_pos()?,
+ button: MouseButton::Right,
+ pressed_buttons: callback_data.pressed,
+ },
+ MouseEventKind::RightButtonUp => MouseEvent::ButtonUp {
+ position: Self::cursor_pos()?,
+ button: MouseButton::Right,
+ pressed_buttons: callback_data.pressed,
+ },
+ MouseEventKind::Move => MouseEvent::Move {
+ position: Self::cursor_pos()?,
+ pressed_buttons: callback_data.pressed,
+ window_below_cursor: None,
+ },
+ };
+
+ let _ = callback_data.event_tx.send(mouse_event);
+
+ if event_kind == MouseEventKind::Move {
+ callback_data.last_move_emission = Some(Instant::now());
+ }
+
+ Ok(())
+ }
+
+ /// Gets the current cursor position.
+ fn cursor_pos() -> crate::Result<Point> {
+ let mut point = POINT { x: 0, y: 0 };
+ unsafe { GetCursorPos(&raw mut point) }?;
+ Ok(Point {
+ x: point.x,
+ y: point.y,
+ })
+ }
+
+ /// Registers or deregisters the raw input device for mouse events.
+ fn enable_raw_input(
+ target_handle: isize,
+ enabled: bool,
+ ) -> crate::Result<()> {
+ let mode_flag = if enabled {
+ RIDEV_INPUTSINK
+ } else {
+ RIDEV_REMOVE
+ };
+
+ let target_hwnd = if enabled {
+ HWND(target_handle)
+ } else {
+ HWND::default()
+ };
+
+ let rid = RAWINPUTDEVICE {
+ usUsagePage: HID_USAGE_PAGE_GENERIC,
+ usUsage: HID_USAGE_GENERIC_MOUSE,
+ dwFlags: mode_flag,
+ hwndTarget: target_hwnd,
+ };
+
+ unsafe {
+ #[allow(clippy::cast_possible_truncation)]
+ RegisterRawInputDevices(
+ &[rid],
+ std::mem::size_of::<RAWINPUTDEVICE>() as u32,
+ )
+ }
+ .map_err(crate::Error::from)
+ }
+}
+
+impl Drop for MouseListener {
+ fn drop(&mut self) {
+ if let Err(err) = self.terminate() {
+ tracing::warn!("Failed to terminate mouse listener: {}", err);
+ }
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/windows/native_window.rs b/packages/wm-platform/src/platform_impl/windows/native_window.rs
new file mode 100644
index 00000000..b375c49a
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/windows/native_window.rs
@@ -0,0 +1,837 @@
+use std::time::Duration;
+
+use tokio::task;
+use tracing::warn;
+use windows::{
+ core::PWSTR,
+ Win32::{
+ Foundation::{CloseHandle, BOOL, HWND, LPARAM, POINT, RECT},
+ Graphics::Dwm::{
+ DwmGetWindowAttribute, DwmSetWindowAttribute, DWMWA_BORDER_COLOR,
+ DWMWA_CLOAKED, DWMWA_COLOR_NONE, DWMWA_EXTENDED_FRAME_BOUNDS,
+ DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_DEFAULT, DWMWCP_DONOTROUND,
+ DWMWCP_ROUND, DWMWCP_ROUNDSMALL,
+ },
+ System::Threading::{
+ OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32,
+ PROCESS_QUERY_LIMITED_INFORMATION,
+ },
+ UI::{
+ Input::KeyboardAndMouse::{
+ SendInput, INPUT, INPUT_0, INPUT_MOUSE, MOUSEINPUT,
+ },
+ WindowsAndMessaging::{
+ EnumWindows, GetAncestor, GetClassNameW, GetDesktopWindow,
+ GetForegroundWindow, GetLayeredWindowAttributes, GetShellWindow,
+ GetWindow, GetWindowLongPtrW, GetWindowRect, GetWindowTextW,
+ GetWindowThreadProcessId, IsIconic, IsWindow, IsWindowVisible,
+ IsZoomed, SendNotifyMessageW, SetForegroundWindow,
+ SetLayeredWindowAttributes, SetWindowLongPtrW, SetWindowPlacement,
+ SetWindowPos, ShowWindowAsync, WindowFromPoint, GA_ROOT,
+ GWL_EXSTYLE, GWL_STYLE, GW_OWNER, HWND_NOTOPMOST, HWND_TOP,
+ HWND_TOPMOST, LAYERED_WINDOW_ATTRIBUTES_FLAGS, LWA_ALPHA,
+ LWA_COLORKEY, SET_WINDOW_POS_FLAGS, SWP_ASYNCWINDOWPOS,
+ SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOCOPYBITS, SWP_NOMOVE,
+ SWP_NOOWNERZORDER, SWP_NOSENDCHANGING, SWP_NOSIZE, SWP_NOZORDER,
+ SWP_SHOWWINDOW, SW_HIDE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE,
+ SW_SHOWNA, WINDOWPLACEMENT, WINDOW_EX_STYLE, WINDOW_STYLE,
+ WM_CLOSE, WPF_ASYNCWINDOWPLACEMENT, WS_DLGFRAME, WS_EX_LAYERED,
+ WS_THICKFRAME,
+ },
+ },
+ },
+};
+
+use super::com::{IApplicationView, COM_INIT};
+use crate::{
+ Color, CornerStyle, Delta, Dispatcher, LengthValue, OpacityValue, Point,
+ Rect, RectDelta, WindowId, WindowZOrder,
+};
+
+/// Magic number used to identify programmatic mouse inputs from our own
+/// process.
+pub(crate) const FOREGROUND_INPUT_IDENTIFIER: u32 = 6379;
+
+/// Platform-specific implementation of [`NativeWindow`].
+#[derive(Clone, Debug)]
+pub(crate) struct NativeWindow {
+ pub(crate) handle: isize,
+}
+
+impl NativeWindow {
+ /// Creates an instance of `NativeWindow`.
+ #[must_use]
+ pub(crate) fn new(handle: isize) -> Self {
+ Self { handle }
+ }
+
+ /// Implements [`NativeWindow::id`].
+ #[must_use]
+ pub(crate) fn id(&self) -> WindowId {
+ WindowId(self.handle)
+ }
+
+ /// Implements [`NativeWindow::title`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn title(&self) -> crate::Result<String> {
+ let mut text: [u16; 512] = [0; 512];
+ let length = unsafe { GetWindowTextW(self.hwnd(), &mut text) };
+
+ #[allow(clippy::cast_sign_loss)]
+ Ok(String::from_utf16_lossy(&text[..length as usize]))
+ }
+
+ /// Implements [`NativeWindow::process_name`].
+ pub(crate) fn process_name(&self) -> crate::Result<String> {
+ let mut process_id = 0u32;
+ unsafe {
+ GetWindowThreadProcessId(self.hwnd(), Some(&raw mut process_id));
+ }
+
+ let process_handle = unsafe {
+ OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, process_id)
+ }?;
+
+ let mut buffer = [0u16; 256];
+ let mut length = u32::try_from(buffer.len())?;
+
+ unsafe {
+ let query_res = QueryFullProcessImageNameW(
+ process_handle,
+ PROCESS_NAME_WIN32,
+ PWSTR(buffer.as_mut_ptr()),
+ &raw mut length,
+ );
+
+ // Always close the process handle regardless of the query result.
+ CloseHandle(process_handle)?;
+
+ query_res
+ }?;
+
+ let exe_path = String::from_utf16_lossy(&buffer[..length as usize]);
+
+ exe_path
+ .split('\\')
+ .next_back()
+ .map(|file_name| {
+ file_name.split('.').next().unwrap_or(file_name).to_string()
+ })
+ .ok_or_else(|| {
+ crate::Error::Platform("Failed to parse process name.".to_string())
+ })
+ }
+
+ /// Implements [`NativeWindow::frame`].
+ pub(crate) fn frame(&self) -> crate::Result<Rect> {
+ let mut rect = RECT::default();
+
+ let dwm_res = unsafe {
+ #[allow(clippy::cast_possible_truncation)]
+ DwmGetWindowAttribute(
+ self.hwnd(),
+ DWMWA_EXTENDED_FRAME_BOUNDS,
+ std::ptr::from_mut(&mut rect).cast(),
+ std::mem::size_of::<RECT>() as u32,
+ )
+ };
+
+ if let Ok(()) = dwm_res {
+ Ok(Rect::from_ltrb(
+ rect.left,
+ rect.top,
+ rect.right,
+ rect.bottom,
+ ))
+ } else {
+ warn!("Failed to get window's frame position. Falling back to border position.");
+ self.frame_with_shadows()
+ }
+ }
+
+ /// Implements [`NativeWindow::position`].
+ pub(crate) fn position(&self) -> crate::Result<(f64, f64)> {
+ let frame = self.frame()?;
+ Ok((f64::from(frame.left), f64::from(frame.top)))
+ }
+
+ /// Implements [`NativeWindow::size`].
+ pub(crate) fn size(&self) -> crate::Result<(f64, f64)> {
+ let frame = self.frame()?;
+ Ok((f64::from(frame.width()), f64::from(frame.height())))
+ }
+
+ /// Implements [`NativeWindow::is_valid`].
+ pub(crate) fn is_valid(&self) -> bool {
+ unsafe { IsWindow(self.hwnd()) }.as_bool()
+ }
+
+ /// Implements [`NativeWindow::is_visible`].
+ pub(crate) fn is_visible(&self) -> crate::Result<bool> {
+ let is_visible = unsafe { IsWindowVisible(self.hwnd()) }.as_bool();
+
+ Ok(is_visible && !self.is_cloaked()?)
+ }
+
+ /// Implements [`NativeWindow::is_minimized`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn is_minimized(&self) -> crate::Result<bool> {
+ Ok(unsafe { IsIconic(self.hwnd()) }.as_bool())
+ }
+
+ /// Implements [`NativeWindow::is_maximized`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn is_maximized(&self) -> crate::Result<bool> {
+ Ok(unsafe { IsZoomed(self.hwnd()) }.as_bool())
+ }
+
+ /// Implements [`NativeWindow::is_resizable`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn is_resizable(&self) -> crate::Result<bool> {
+ Ok(self.has_window_style(WS_THICKFRAME))
+ }
+
+ /// Implements [`NativeWindow::is_desktop_window`].
+ #[allow(clippy::unnecessary_wraps)]
+ pub(crate) fn is_desktop_window(&self) -> crate::Result<bool> {
+ Ok(*self == desktop_window())
+ }
+
+ /// Implements [`NativeWindow::set_frame`].
+ pub(crate) fn set_frame(&self, rect: &Rect) -> crate::Result<()> {
+ unsafe {
+ SetWindowPos(
+ self.hwnd(),
+ HWND_NOTOPMOST,
+ rect.x(),
+ rect.y(),
+ rect.width(),
+ rect.height(),
+ SWP_NOACTIVATE
+ | SWP_NOZORDER
+ | SWP_NOCOPYBITS
+ | SWP_NOSENDCHANGING
+ | SWP_ASYNCWINDOWPOS
+ | SWP_FRAMECHANGED,
+ )
+ }?;
+
+ Ok(())
+ }
+
+ /// Implements [`NativeWindow::resize`].
+ pub(crate) fn resize(
+ &self,
+ width: i32,
+ height: i32,
+ ) -> crate::Result<()> {
+ unsafe {
+ SetWindowPos(
+ self.hwnd(),
+ HWND_NOTOPMOST,
+ 0,
+ 0,
+ width,
+ height,
+ SWP_NOACTIVATE
+ | SWP_NOZORDER
+ | SWP_NOMOVE
+ | SWP_NOCOPYBITS
+ | SWP_NOSENDCHANGING
+ | SWP_ASYNCWINDOWPOS
+ | SWP_FRAMECHANGED,
+ )
+ }?;
+
+ Ok(())
+ }
+
+ /// Implements [`NativeWindow::reposition`].
+ pub(crate) fn reposition(&self, x: i32, y: i32) -> crate::Result<()> {
+ unsafe {
+ SetWindowPos(
+ self.hwnd(),
+ HWND_NOTOPMOST,
+ x,
+ y,
+ 0,
+ 0,
+ SWP_NOACTIVATE
+ | SWP_NOZORDER
+ | SWP_NOSIZE
+ | SWP_NOCOPYBITS
+ | SWP_NOSENDCHANGING
+ | SWP_ASYNCWINDOWPOS
+ | SWP_FRAMECHANGED,
+ )
+ }?;
+
+ Ok(())
+ }
+
+ /// Implements [`NativeWindow::minimize`].
+ pub(crate) fn minimize(&self) -> crate::Result<()> {
+ unsafe { ShowWindowAsync(self.hwnd(), SW_MINIMIZE).ok() }?;
+ Ok(())
+ }
+
+ /// Implements [`NativeWindow::maximize`].
+ pub(crate) fn maximize(&self) -> crate::Result<()> {
+ unsafe { ShowWindowAsync(self.hwnd(), SW_MAXIMIZE).ok() }?;
+ Ok(())
+ }
+
+ /// Implements [`NativeWindow::focus`].
+ pub(crate) fn focus(&self) -> crate::Result<()> {
+ let input = [INPUT {
+ r#type: INPUT_MOUSE,
+ Anonymous: INPUT_0 {
+ mi: MOUSEINPUT {
+ dwExtraInfo: FOREGROUND_INPUT_IDENTIFIER as usize,
+ ..Default::default()
+ },
+ },
+ }];
+
+ // Bypass restriction for setting the foreground window by sending an
+ // input to our own process first.
+ #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
+ unsafe {
+ SendInput(&input, std::mem::size_of::<INPUT>() as i32)
+ };
+
+ // Set as the foreground window.
+ unsafe { SetForegroundWindow(self.hwnd()) }.ok()?;
+
+ Ok(())
+ }
+
+ /// Implements [`NativeWindow::close`].
+ pub(crate) fn close(&self) -> crate::Result<()> {
+ unsafe { SendNotifyMessageW(self.hwnd(), WM_CLOSE, None, None) }?;
+ Ok(())
+ }
+
+ /// Implements [`NativeWindowWindowsExt::hwnd`].
+ pub(crate) fn hwnd(&self) -> HWND {
+ HWND(self.handle)
+ }
+
+ /// Implements [`NativeWindowWindowsExt::class_name`].
+ pub(crate) fn class_name(&self) -> crate::Result<String> {
+ let mut buffer = [0u16; 256];
+ let result = unsafe { GetClassNameW(self.hwnd(), &mut buffer) };
+
+ if result == 0 {
+ return Err(windows::core::Error::from_win32().into());
+ }
+
+ #[allow(clippy::cast_sign_loss)]
+ let class_name = String::from_utf16_lossy(&buffer[..result as usize]);
+ Ok(class_name)
+ }
+
+ /// Implements [`NativeWindowWindowsExt::frame_with_shadows`].
+ pub(crate) fn frame_with_shadows(&self) -> crate::Result<Rect> {
+ let mut rect = RECT::default();
+
+ unsafe {
+ GetWindowRect(self.hwnd(), std::ptr::from_mut(&mut rect).cast())
+ }?;
+
+ Ok(Rect::from_ltrb(
+ rect.left,
+ rect.top,
+ rect.right,
+ rect.bottom,
+ ))
+ }
+
+ /// Implements [`NativeWindowWindowsExt::shadow_borders`].
+ // TODO: Return tuple of (left, top, right, bottom) instead of
+ // `RectDelta`.
+ pub(crate) fn shadow_borders(&self) -> crate::Result<RectDelta> {
+ let border_pos = self.frame_with_shadows()?;
+ let frame_pos = self.frame()?;
+
+ Ok(RectDelta::new(
+ LengthValue::from_px(frame_pos.left - border_pos.left),
+ LengthValue::from_px(frame_pos.top - border_pos.top),
+ LengthValue::from_px(border_pos.right - frame_pos.right),
+ LengthValue::from_px(border_pos.bottom - frame_pos.bottom),
+ ))
+ }
+
+ /// Implements [`NativeWindowWindowsExt::has_owner_window`].
+ pub(crate) fn has_owner_window(&self) -> bool {
+ unsafe { GetWindow(self.hwnd(), GW_OWNER) }.0 != 0
+ }
+
+ /// Implements [`NativeWindowWindowsExt::has_window_style`].
+ pub(crate) fn has_window_style(&self, style: WINDOW_STYLE) -> bool {
+ let current_style =
+ unsafe { GetWindowLongPtrW(self.hwnd(), GWL_STYLE) };
+
+ #[allow(clippy::cast_possible_wrap)]
+ let style = style.0 as isize;
+ (current_style & style) != 0
+ }
+
+ /// Implements [`NativeWindowWindowsExt::has_window_style_ex`].
+ pub(crate) fn has_window_style_ex(
+ &self,
+ style: WINDOW_EX_STYLE,
+ ) -> bool {
+ let current_style =
+ unsafe { GetWindowLongPtrW(self.hwnd(), GWL_EXSTYLE) };
+
+ #[allow(clippy::cast_possible_wrap)]
+ let style = style.0 as isize;
+ (current_style & style) != 0
+ }
+
+ /// Implements [`NativeWindowWindowsExt::set_window_pos`].
+ pub(crate) fn set_window_pos(
+ &self,
+ z_order: &WindowZOrder,
+ rect: &Rect,
+ flags: SET_WINDOW_POS_FLAGS,
+ ) -> crate::Result<()> {
+ let z_order_hwnd = match z_order {
+ WindowZOrder::TopMost => HWND_TOPMOST,
+ WindowZOrder::Top => HWND_TOP,
+ WindowZOrder::Normal => HWND_NOTOPMOST,
+ WindowZOrder::AfterWindow(window_id) => HWND(window_id.0),
+ };
+
+ unsafe {
+ SetWindowPos(
+ self.hwnd(),
+ z_order_hwnd,
+ rect.x(),
+ rect.y(),
+ rect.width(),
+ rect.height(),
+ flags,
+ )
+ }?;
+
+ Ok(())
+ }
+
+ /// Implements [`NativeWindowWindowsExt::show`].
+ pub(crate) fn show(&self) -> crate::Result<()> {
+ unsafe { ShowWindowAsync(self.hwnd(), SW_SHOWNA) }.ok()?;
+ Ok(())
+ }
+
+ /// Implements [`NativeWindowWindowsExt::hide`].
+ pub(crate) fn hide(&self) -> crate::Result<()> {
+ unsafe { ShowWindowAsync(self.hwnd(), SW_HIDE) }.ok()?;
+ Ok(())
+ }
+
+ /// Implements [`NativeWindowWindowsExt::restore`].
+ pub(crate) fn restore(
+ &self,
+ outer_frame: Option<&Rect>,
+ ) -> crate::Result<()> {
+ match outer_frame {
+ None => {
+ unsafe { ShowWindowAsync(self.hwnd(), SW_RESTORE) }.ok()?;
+ Ok(())
+ }
+ Some(rect) => {
+ let placement = WINDOWPLACEMENT {
+ #[allow(clippy::cast_possible_truncation)]
+ length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
+ flags: WPF_ASYNCWINDOWPLACEMENT,
+ showCmd: SW_RESTORE.0 as u32,
+ rcNormalPosition: RECT {
+ left: rect.left,
+ top: rect.top,
+ right: rect.right,
+ bottom: rect.bottom,
+ },
+ ..Default::default()
+ };
+
+ unsafe { SetWindowPlacement(self.hwnd(), &raw const placement) }?;
+ Ok(())
+ }
+ }
+ }
+
+ /// Implements [`NativeWindowWindowsExt::set_cloaked`].
+ pub(crate) fn set_cloaked(&self, cloaked: bool) -> crate::Result<()> {
+ COM_INIT.with(|com_init| -> crate::Result<()> {
+ com_init.borrow_mut().with_retry(|com| {
+ let view_collection = com.application_view_collection()?;
+
+ let mut view: Option<IApplicationView> = None;
+ unsafe {
+ view_collection.get_view_for_hwnd(self.hwnd().0, &raw mut view)
+ }
+ .ok()?;
+
+ let view = view.ok_or_else(|| {
+ crate::Error::Platform(
+ "Unable to get application view by window handle.".to_string(),
+ )
+ })?;
+
+ // Ref: https://github.com/Ciantic/AltTabAccessor/issues/1#issuecomment-1426877843
+ unsafe { view.set_cloak(1, if cloaked { 2 } else { 0 }) }
+ .ok()
+ .map_err(|_| {
+ crate::Error::Platform("Failed to cloak window.".to_string())
+ })
+ })
+ })
+ }
+
+ /// Implements [`NativeWindowWindowsExt::mark_fullscreen`].
+ pub(crate) fn mark_fullscreen(
+ &self,
+ fullscreen: bool,
+ ) -> crate::Result<()> {
+ COM_INIT.with(|com_init| -> crate::Result<()> {
+ com_init.borrow_mut().with_retry(|com| {
+ let taskbar_list = com.taskbar_list()?;
+
+ unsafe {
+ taskbar_list.MarkFullscreenWindow(self.hwnd(), fullscreen)
+ }?;
+
+ Ok(())
+ })
+ })
+ }
+
+ /// Implements [`NativeWindowWindowsExt::set_taskbar_visibility`].
+ pub(crate) fn set_taskbar_visibility(
+ &self,
+ visible: bool,
+ ) -> crate::Result<()> {
+ COM_INIT.with(|com_init| -> crate::Result<()> {
+ com_init.borrow_mut().with_retry(|com| {
+ let taskbar_list = com.taskbar_list()?;
+
+ if visible {
+ unsafe { taskbar_list.AddTab(self.hwnd())? };
+ } else {
+ unsafe { taskbar_list.DeleteTab(self.hwnd())? };
+ }
+
+ Ok(())
+ })
+ })
+ }
+
+ /// Implements [`NativeWindowWindowsExt::add_window_style_ex`].
+ pub(crate) fn add_window_style_ex(&self, style: WINDOW_EX_STYLE) {
+ let current_style =
+ unsafe { GetWindowLongPtrW(self.hwnd(), GWL_EXSTYLE) };
+
+ #[allow(clippy::cast_possible_wrap)]
+ if current_style & style.0 as isize == 0 {
+ let new_style = current_style | style.0 as isize;
+
+ unsafe { SetWindowLongPtrW(self.hwnd(), GWL_EXSTYLE, new_style) };
+ }
+ }
+
+ /// Implements [`NativeWindowWindowsExt::set_z_order`].
+ pub(crate) fn set_z_order(
+ &self,
+ z_order: &WindowZOrder,
+ ) -> crate::Result<()> {
+ let z_order_hwnd = match z_order {
+ WindowZOrder::TopMost => HWND_TOPMOST,
+ WindowZOrder::Top => HWND_TOP,
+ WindowZOrder::Normal => HWND_NOTOPMOST,
+ WindowZOrder::AfterWindow(window_id) => HWND(window_id.0),
+ };
+
+ let flags = SWP_NOACTIVATE
+ | SWP_NOCOPYBITS
+ | SWP_ASYNCWINDOWPOS
+ | SWP_SHOWWINDOW
+ | SWP_NOMOVE
+ | SWP_NOSIZE;
+
+ unsafe { SetWindowPos(self.hwnd(), z_order_hwnd, 0, 0, 0, 0, flags) }?;
+
+ // Z-order can sometimes still be incorrect after the above call.
+ let handle = self.handle;
+ task::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ let _ = unsafe {
+ SetWindowPos(HWND(handle), z_order_hwnd, 0, 0, 0, 0, flags)
+ };
+ });
+
+ Ok(())
+ }
+
+ /// Implements [`NativeWindowWindowsExt::set_title_bar_visibility`].
+ pub(crate) fn set_title_bar_visibility(
+ &self,
+ visible: bool,
+ ) -> crate::Result<()> {
+ let style = unsafe { GetWindowLongPtrW(self.hwnd(), GWL_STYLE) };
+
+ #[allow(clippy::cast_possible_wrap)]
+ let new_style = if visible {
+ style | (WS_DLGFRAME.0 as isize)
+ } else {
+ style & !(WS_DLGFRAME.0 as isize)
+ };
+
+ if new_style != style {
+ unsafe {
+ SetWindowLongPtrW(self.hwnd(), GWL_STYLE, new_style);
+ SetWindowPos(
+ self.hwnd(),
+ HWND_NOTOPMOST,
+ 0,
+ 0,
+ 0,
+ 0,
+ SWP_FRAMECHANGED
+ | SWP_NOMOVE
+ | SWP_NOSIZE
+ | SWP_NOZORDER
+ | SWP_NOOWNERZORDER
+ | SWP_NOACTIVATE
+ | SWP_NOCOPYBITS
+ | SWP_NOSENDCHANGING
+ | SWP_ASYNCWINDOWPOS,
+ )?;
+ }
+ }
+
+ Ok(())
+ }
+
+ /// Implements [`NativeWindowWindowsExt::set_border_color`].
+ pub(crate) fn set_border_color(
+ &self,
+ color: Option<&Color>,
+ ) -> crate::Result<()> {
+ let bgr = match color {
+ Some(color) => color.to_bgr(),
+ None => DWMWA_COLOR_NONE,
+ };
+
+ unsafe {
+ #[allow(clippy::cast_possible_truncation)]
+ DwmSetWindowAttribute(
+ self.hwnd(),
+ DWMWA_BORDER_COLOR,
+ std::ptr::from_ref(&bgr).cast(),
+ std::mem::size_of::<u32>() as u32,
+ )?;
+ }
+
+ Ok(())
+ }
+
+ /// Implements [`NativeWindowWindowsExt::set_corner_style`].
+ pub(crate) fn set_corner_style(
+ &self,
+ corner_style: &CornerStyle,
+ ) -> crate::Result<()> {
+ let corner_preference = match corner_style {
+ CornerStyle::Default => DWMWCP_DEFAULT,
+ CornerStyle::Square => DWMWCP_DONOTROUND,
+ CornerStyle::Rounded => DWMWCP_ROUND,
+ CornerStyle::SmallRounded => DWMWCP_ROUNDSMALL,
+ };
+
+ unsafe {
+ #[allow(clippy::cast_possible_truncation)]
+ DwmSetWindowAttribute(
+ self.hwnd(),
+ DWMWA_WINDOW_CORNER_PREFERENCE,
+ std::ptr::from_ref(&(corner_preference.0)).cast(),
+ std::mem::size_of::<i32>() as u32,
+ )?;
+ }
+
+ Ok(())
+ }
+
+ /// Implements [`NativeWindowWindowsExt::set_transparency`].
+ pub(crate) fn set_transparency(
+ &self,
+ opacity_value: &OpacityValue,
+ ) -> crate::Result<()> {
+ // Make the window layered if it isn't already.
+ self.add_window_style_ex(WS_EX_LAYERED);
+
+ unsafe {
+ SetLayeredWindowAttributes(
+ self.hwnd(),
+ None,
+ opacity_value.to_alpha(),
+ LWA_ALPHA,
+ )?;
+ }
+
+ Ok(())
+ }
+
+ /// Implements [`NativeWindowWindowsExt::adjust_transparency`].
+ pub(crate) fn adjust_transparency(
+ &self,
+ opacity_delta: &Delta<OpacityValue>,
+ ) -> crate::Result<()> {
+ let mut alpha = u8::MAX;
+ let mut flag = LAYERED_WINDOW_ATTRIBUTES_FLAGS::default();
+
+ unsafe {
+ GetLayeredWindowAttributes(
+ self.hwnd(),
+ None,
+ Some(&raw mut alpha),
+ Some(&raw mut flag),
+ )?;
+ }
+
+ if flag.contains(LWA_COLORKEY) {
+ return Err(crate::Error::Platform(
+ "Window uses color key for its transparency and cannot be adjusted."
+ .to_string(),
+ ));
+ }
+
+ let target_alpha = if opacity_delta.is_negative {
+ alpha.saturating_sub(opacity_delta.inner.to_alpha())
+ } else {
+ alpha.saturating_add(opacity_delta.inner.to_alpha())
+ };
+
+ self.set_transparency(&OpacityValue::from_alpha(target_alpha))
+ }
+
+ /// Whether the window is cloaked. For some UWP apps, `WS_VISIBLE` will
+ /// be present even if the window isn't actually visible. The
+ /// `DWMWA_CLOAKED` attribute is used to check whether these apps are
+ /// visible.
+ fn is_cloaked(&self) -> crate::Result<bool> {
+ let mut cloaked = 0u32;
+
+ unsafe {
+ #[allow(clippy::cast_possible_truncation)]
+ DwmGetWindowAttribute(
+ self.hwnd(),
+ DWMWA_CLOAKED,
+ std::ptr::from_mut::<u32>(&mut cloaked).cast(),
+ std::mem::size_of::<u32>() as u32,
+ )
+ }?;
+
+ Ok(cloaked != 0)
+ }
+}
+
+impl PartialEq for NativeWindow {
+ fn eq(&self, other: &Self) -> bool {
+ self.handle == other.handle
+ }
+}
+
+impl Eq for NativeWindow {}
+
+impl From<NativeWindow> for crate::NativeWindow {
+ fn from(window: NativeWindow) -> Self {
+ crate::NativeWindow { inner: window }
+ }
+}
+
+/// Implements [`Dispatcher::visible_windows`].
+pub(crate) fn visible_windows(
+ _: &Dispatcher,
+) -> crate::Result<Vec<crate::NativeWindow>> {
+ let mut handles: Vec<isize> = Vec::new();
+
+ #[allow(clippy::items_after_statements)]
+ extern "system" fn visible_windows_proc(
+ handle: HWND,
+ data: LPARAM,
+ ) -> BOOL {
+ let handles = data.0 as *mut Vec<isize>;
+ unsafe { (*handles).push(handle.0) };
+ true.into()
+ }
+
+ unsafe {
+ EnumWindows(
+ Some(visible_windows_proc),
+ LPARAM(std::ptr::from_mut(&mut handles) as _),
+ )
+ }?;
+
+ Ok(
+ handles
+ .into_iter()
+ .map(NativeWindow::new)
+ .filter(|window| window.is_visible().unwrap_or(false))
+ .map(Into::into)
+ .collect(),
+ )
+}
+
+/// Implements [`Dispatcher::focused_window`].
+#[allow(clippy::unnecessary_wraps)]
+pub(crate) fn focused_window(
+ _: &Dispatcher,
+) -> crate::Result<crate::NativeWindow> {
+ let handle = unsafe { GetForegroundWindow() };
+ Ok(NativeWindow::new(handle.0).into())
+}
+
+/// Implements [`Dispatcher::window_from_point`].
+#[allow(clippy::unnecessary_wraps)]
+pub(crate) fn window_from_point(
+ point: &Point,
+ _: &Dispatcher,
+) -> crate::Result<Option<crate::NativeWindow>> {
+ let point = POINT {
+ x: point.x,
+ y: point.y,
+ };
+
+ let handle = unsafe { WindowFromPoint(point) };
+ if handle.0 == 0 {
+ return Ok(None);
+ }
+
+ let root = unsafe { GetAncestor(handle, GA_ROOT) };
+ if root.0 == 0 {
+ return Ok(None);
+ }
+
+ Ok(Some(NativeWindow::new(root.0).into()))
+}
+
+/// Implements [`Dispatcher::reset_focus`].
+pub(crate) fn reset_focus(_dispatcher: &Dispatcher) -> crate::Result<()> {
+ desktop_window().focus()
+}
+
+/// Gets the `NativeWindow` instance of the desktop window.
+///
+/// This is the explorer.exe wallpaper window (i.e. "Progman"). If
+/// explorer.exe isn't running, then default to the desktop window below
+/// the wallpaper window.
+#[must_use]
+fn desktop_window() -> NativeWindow {
+ let handle = match unsafe { GetShellWindow() } {
+ HWND(0) => unsafe { GetDesktopWindow() },
+ handle => handle,
+ };
+
+ NativeWindow::new(handle.0)
+}
diff --git a/packages/wm-platform/src/platform_impl/windows/single_instance.rs b/packages/wm-platform/src/platform_impl/windows/single_instance.rs
new file mode 100644
index 00000000..5264593c
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/windows/single_instance.rs
@@ -0,0 +1,64 @@
+use windows::{
+ core::{w, PCWSTR},
+ Win32::{
+ Foundation::{
+ CloseHandle, GetLastError, ERROR_ALREADY_EXISTS,
+ ERROR_FILE_NOT_FOUND, HANDLE,
+ },
+ System::Threading::{
+ CreateMutexW, OpenMutexW, ReleaseMutex,
+ SYNCHRONIZATION_ACCESS_RIGHTS,
+ },
+ },
+};
+
+/// Arbitrary GUID to uniquely identify the application.
+const APP_GUID: PCWSTR =
+ w!("Global\\325d0ed7-7f60-4925-8d1b-aa287b26b218");
+
+/// Platform-specific implementation of [`SingleInstance`].
+pub struct SingleInstance {
+ handle: HANDLE,
+}
+
+impl SingleInstance {
+ /// Implements [`SingleInstance::new`].
+ pub(crate) fn new() -> crate::Result<Self> {
+ // Create a named system-wide mutex.
+ let handle = unsafe { CreateMutexW(None, true, APP_GUID) }?;
+
+ if let Err(err) = unsafe { GetLastError() } {
+ if err == ERROR_ALREADY_EXISTS.into() {
+ return Err(crate::Error::Platform(
+ "Another instance of the application is already running."
+ .to_string(),
+ ));
+ }
+ }
+
+ Ok(Self { handle })
+ }
+
+ /// Implements [`SingleInstance::is_running`].
+ #[must_use]
+ pub(crate) fn is_running() -> bool {
+ let res = unsafe {
+ OpenMutexW(SYNCHRONIZATION_ACCESS_RIGHTS::default(), false, APP_GUID)
+ };
+
+ // If the mutex exists, then another instance is running.
+ match res {
+ Ok(_) => false,
+ Err(err) => err == ERROR_FILE_NOT_FOUND.into(),
+ }
+ }
+}
+
+impl Drop for SingleInstance {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = ReleaseMutex(self.handle);
+ let _ = CloseHandle(self.handle);
+ }
+ }
+}
diff --git a/packages/wm-platform/src/platform_impl/windows/window_listener.rs b/packages/wm-platform/src/platform_impl/windows/window_listener.rs
new file mode 100644
index 00000000..29838431
--- /dev/null
+++ b/packages/wm-platform/src/platform_impl/windows/window_listener.rs
@@ -0,0 +1,192 @@
+use std::sync::OnceLock;
+
+use tokio::sync::mpsc;
+use windows::Win32::{
+ Foundation::HWND,
+ UI::{
+ Accessibility::{SetWinEventHook, UnhookWinEvent, HWINEVENTHOOK},
+ WindowsAndMessaging::{
+ EVENT_OBJECT_CLOAKED, EVENT_OBJECT_DESTROY, EVENT_OBJECT_HIDE,
+ EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_NAMECHANGE,
+ EVENT_OBJECT_SHOW, EVENT_OBJECT_UNCLOAKED, EVENT_SYSTEM_FOREGROUND,
+ EVENT_SYSTEM_MINIMIZEEND, EVENT_SYSTEM_MINIMIZESTART,
+ EVENT_SYSTEM_MOVESIZEEND, EVENT_SYSTEM_MOVESIZESTART, OBJID_WINDOW,
+ WINEVENT_OUTOFCONTEXT, WINEVENT_SKIPOWNPROCESS,
+ },
+ },
+};
+
+use super::NativeWindow;
+use crate::{Dispatcher, WindowEvent, WindowId};
+
+thread_local! {
+ /// Sender for window events. For use with hook procedure.
+ static EVENT_TX: OnceLock<mpsc::UnboundedSender<WindowEvent>> = const { OnceLock::new() };
+}
+
+/// Platform-specific implementation of [`WindowEventNotification`].
+#[derive(Clone, Debug)]
+pub struct WindowEventNotificationInner;
+
+/// Platform-specific implementation of [`WindowListener`].
+#[derive(Debug)]
+pub(crate) struct WindowListener {
+ hook_handles: Vec<HWINEVENTHOOK>,
+}
+
+impl WindowListener {
+ /// Implements [`WindowListener::new`].
+ pub(crate) fn new(
+ event_tx: mpsc::UnboundedSender<WindowEvent>,
+ dispatcher: &Dispatcher,
+ ) -> crate::Result<Self> {
+ let hook_handles = dispatcher.dispatch_sync(move || {
+ EVENT_TX.with(|lock| lock.set(event_tx)).map_err(|_| {
+ crate::Error::Platform(
+ "Window event sender already set.".to_string(),
+ )
+ })?;
+
+ Self::hook_win_events()
+ })??;
+
+ Ok(Self { hook_handles })
+ }
+
+ /// Implements [`WindowListener::terminate`].
+ pub(crate) fn terminate(&mut self) {
+ for handle in self.hook_handles.drain(..) {
+ let _ = unsafe { UnhookWinEvent(handle) };
+ }
+ }
+
+ /// Creates several window event hooks via `SetWinEventHook`.
+ ///
+ /// Separate hooks are created per event range, which is more performant
+ /// than a single hook covering all events.
+ fn hook_win_events() -> crate::Result<Vec<HWINEVENTHOOK>> {
+ let event_ranges = [
+ (EVENT_OBJECT_DESTROY, EVENT_OBJECT_HIDE),
+ (EVENT_SYSTEM_MINIMIZESTART, EVENT_SYSTEM_MINIMIZEEND),
+ (EVENT_SYSTEM_MOVESIZESTART, EVENT_SYSTEM_MOVESIZEEND),
+ (EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND),
+ (EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_NAMECHANGE),
+ (EVENT_OBJECT_CLOAKED, EVENT_OBJECT_UNCLOAKED),
+ ];
+
+ event_ranges
+ .iter()
+ .try_fold(Vec::new(), |mut handles, (min, max)| {
+ // Create a window hook for the event range.
+ let hook_handle = unsafe {
+ SetWinEventHook(
+ *min,
+ *max,
+ None,
+ Some(Self::window_event_proc),
+ 0,
+ 0,
+ WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
+ )
+ };
+
+ if hook_handle.is_invalid() {
+ return Err(crate::Error::Platform(
+ "Failed to set window event hook.".to_string(),
+ ));
+ }
+
+ handles.push(hook_handle);
+ Ok(handles)
+ })
+ }
+
+ /// Callback passed to `SetWinEventHook`.
+ ///
+ /// This function is called on selected window events, and forwards them
+ /// through an MPSC channel.
+ extern "system" fn window_event_proc(
+ _hook: HWINEVENTHOOK,
+ event_type: u32,
+ handle: HWND,
+ id_object: i32,
+ id_child: i32,
+ _event_thread: u32,
+ _event_time: u32,
+ ) {
+ // Check whether the event is associated with a window object rather
+ // than a UI control.
+ let is_window_event =
+ id_object == OBJID_WINDOW.0 && id_child == 0 && handle != HWND(0);
+
+ if !is_window_event {
+ return;
+ }
+
+ let Some(event_tx) = EVENT_TX.with(|lock| lock.get().cloned()) else {
+ return;
+ };
+
+ let notification = crate::WindowEventNotification(None);
+
+ let event = match event_type {
+ EVENT_OBJECT_DESTROY => WindowEvent::Destroyed {
+ window_id: WindowId(handle.0),
+ notification,
+ },
+ EVENT_SYSTEM_FOREGROUND => WindowEvent::Focused {
+ window: NativeWindow::new(handle.0).into(),
+ notification,
+ },
+ EVENT_OBJECT_HIDE | EVENT_OBJECT_CLOAKED => WindowEvent::Hidden {
+ window: NativeWindow::new(handle.0).into(),
+ notification,
+ },
+ EVENT_OBJECT_LOCATIONCHANGE => WindowEvent::MovedOrResized {
+ window: NativeWindow::new(handle.0).into(),
+ is_interactive_start: false,
+ is_interactive_end: false,
+ notification,
+ },
+ EVENT_SYSTEM_MINIMIZESTART => WindowEvent::Minimized {
+ window: NativeWindow::new(handle.0).into(),
+ notification,
+ },
+ EVENT_SYSTEM_MINIMIZEEND => WindowEvent::MinimizeEnded {
+ window: NativeWindow::new(handle.0).into(),
+ notification,
+ },
+ EVENT_SYSTEM_MOVESIZESTART => WindowEvent::MovedOrResized {
+ window: NativeWindow::new(handle.0).into(),
+ is_interactive_start: true,
+ is_interactive_end: false,
+ notification,
+ },
+ EVENT_SYSTEM_MOVESIZEEND => WindowEvent::MovedOrResized {
+ window: NativeWindow::new(handle.0).into(),
+ is_interactive_start: false,
+ is_interactive_end: true,
+ notification,
+ },
+ EVENT_OBJECT_SHOW | EVENT_OBJECT_UNCLOAKED => WindowEvent::Shown {
+ window: NativeWindow::new(handle.0).into(),
+ notification,
+ },
+ EVENT_OBJECT_NAMECHANGE => WindowEvent::TitleChanged {
+ window: NativeWindow::new(handle.0).into(),
+ notification,
+ },
+ _ => return,
+ };
+
+ if let Err(err) = event_tx.send(event) {
+ tracing::warn!("Failed to send window event: {}.", err);
+ }
+ }
+}
+
+impl Drop for WindowListener {
+ fn drop(&mut self) {
+ self.terminate();
+ }
+}
diff --git a/packages/wm-platform/src/single_instance.rs b/packages/wm-platform/src/single_instance.rs
index 3a54775e..eb574de8 100644
--- a/packages/wm-platform/src/single_instance.rs
+++ b/packages/wm-platform/src/single_instance.rs
@@ -1,63 +1,32 @@
-use anyhow::{bail, Context, Result};
-use windows::{
- core::{w, PCWSTR},
- Win32::{
- Foundation::{
- CloseHandle, GetLastError, ERROR_ALREADY_EXISTS,
- ERROR_FILE_NOT_FOUND, HANDLE,
- },
- System::Threading::{
- CreateMutexW, OpenMutexW, ReleaseMutex,
- SYNCHRONIZATION_ACCESS_RIGHTS,
- },
- },
-};
-
+use crate::platform_impl;
+
+/// Ensures only one instance of the application is running at a time.
+///
+/// # Platform-specific
+///
+/// - **Windows**: Uses a named system-wide mutex.
+/// - **macOS**: Uses an exclusive file lock.
pub struct SingleInstance {
- handle: HANDLE,
+ /// Inner platform-specific single instance implementation.
+ _inner: platform_impl::SingleInstance,
}
-/// Arbitrary GUID used to identify the application.
-const APP_GUID: PCWSTR =
- w!("Global\\325d0ed7-7f60-4925-8d1b-aa287b26b218");
-
impl SingleInstance {
- /// Creates a new system-wide mutex to ensure that only one instance of
- /// the application is running.
- pub fn new() -> Result<Self> {
- let handle = unsafe { CreateMutexW(None, true, APP_GUID) }
- .context("Failed to create single instance mutex.")?;
-
- if let Err(err) = unsafe { GetLastError() } {
- if err == ERROR_ALREADY_EXISTS.into() {
- bail!("Another instance of the application is already running.");
- }
- }
-
- Ok(Self { handle })
+ /// Creates a new [`SingleInstance`], acquiring the platform-specific
+ /// lock or mutex.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`Error::Platform`] if another instance is already running.
+ pub fn new() -> crate::Result<Self> {
+ let inner = platform_impl::SingleInstance::new()?;
+ Ok(Self { _inner: inner })
}
- /// Gets whether there is an active instance of the application.
+ /// Returns whether another instance of the application is currently
+ /// running.
#[must_use]
pub fn is_running() -> bool {
- let res = unsafe {
- OpenMutexW(SYNCHRONIZATION_ACCESS_RIGHTS::default(), false, APP_GUID)
- };
-
- // Check whether the mutex exists. If it doesn't, then this is the
- // only instance.
- match res {
- Ok(_) => false,
- Err(err) => err == ERROR_FILE_NOT_FOUND.into(),
- }
- }
-}
-
-impl Drop for SingleInstance {
- fn drop(&mut self) {
- unsafe {
- let _ = ReleaseMutex(self.handle);
- let _ = CloseHandle(self.handle);
- }
+ platform_impl::SingleInstance::is_running()
}
}
diff --git a/packages/wm-platform/src/test.rs b/packages/wm-platform/src/test.rs
new file mode 100644
index 00000000..2fca23e1
--- /dev/null
+++ b/packages/wm-platform/src/test.rs
@@ -0,0 +1,40 @@
+#![feature(iterator_try_collect)]
+
+#[macro_use]
+extern crate libtest_mimic_collect;
+
+mod dispatcher;
+mod display;
+mod error;
+mod event_loop;
+mod keybinding_listener;
+mod models;
+mod mouse_listener;
+mod native_window;
+mod platform_event;
+mod platform_impl;
+mod thread_bound;
+mod window_listener;
+
+pub use dispatcher::*;
+pub use display::*;
+pub use error::*;
+pub use event_loop::*;
+pub use keybinding_listener::*;
+pub use models::*;
+pub use mouse_listener::*;
+pub use native_window::*;
+pub use platform_event::*;
+pub use thread_bound::*;
+pub use window_listener::*;
+
+pub fn main() {
+ // Due to macOS requiring the main thread for some UI APIs, these
+ // tests must execute on the main thread. Until this is natively
+ // supported via cargo's test harness, we use `libtest_mimic_collect`.
+ //
+ // To run these tests, run `cargo test <...args> -- --test-threads=1`.
+ //
+ // Ref: https://github.com/rust-lang/rust/issues/104053
+ libtest_mimic_collect::TestCollection::run();
+}
diff --git a/packages/wm-platform/src/thread_bound.rs b/packages/wm-platform/src/thread_bound.rs
new file mode 100644
index 00000000..97b932c4
--- /dev/null
+++ b/packages/wm-platform/src/thread_bound.rs
@@ -0,0 +1,202 @@
+use core::{
+ fmt,
+ mem::{self, ManuallyDrop},
+};
+use std::thread::ThreadId;
+
+use crate::Dispatcher;
+
+/// Binds a value to the current event loop thread.
+///
+/// `ThreadBound<T>` wraps a value created on an event loop thread and
+/// guarantees that all access and destruction of that value happens on
+/// the same thread, using the provided [`Dispatcher`]. This allows the
+/// wrapper to be used across threads (`Send + Sync`) even when `T` itself
+/// is not thread-safe.
+///
+/// Inspired by:
+/// - `threadbound::ThreadBound` <https://github.com/dtolnay/threadbound>
+/// - `dispatch2::MainThreadBound` <https://github.com/madsmtm/objc2/tree/main/crates/dispatch2>
+///
+/// NOTE: Dropping the wrapper schedules the inner value to be dropped on
+/// the event loop thread. If the event loop has already stopped, the drop
+/// is skipped to avoid running `T`'s destructor on the wrong thread,
+/// potentially leaking the value.
+///
+/// # Example usage
+///
+/// ```no_run
+/// use wm_platform::{EventLoop, Dispatcher, ThreadBound};
+///
+/// # fn main() -> wm_platform::Result<()> {
+/// let (event_loop, dispatcher) = EventLoop::new()?;
+///
+/// // Create the value on the event loop thread.
+/// let bound = dispatcher.dispatch_sync(|| {
+/// ThreadBound::new(String::from("hello"), dispatcher.clone())
+/// })?;
+///
+/// // Access from any thread via the dispatcher.
+/// let len = bound.with(|s| s.len())?;
+/// assert_eq!(len, 5);
+///
+/// // Direct access only works on the original thread.
+/// assert!(bound.get_ref().is_ok());
+///
+/// drop(bound); // Drop is scheduled on the event loop thread.
+/// # Ok(()) }
+/// ```
+#[derive(Clone)]
+pub struct ThreadBound<T> {
+ value: ManuallyDrop<T>,
+ thread_id: ThreadId,
+ dispatcher: Dispatcher,
+}
+
+// SAFETY: Access to the inner value is only exposed on the event loop
+// thread.
+unsafe impl<T> Send for ThreadBound<T> {}
+unsafe impl<T> Sync for ThreadBound<T> {}
+
+impl<T> ThreadBound<T> {
+ /// Binds a value to the current event loop thread.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `dispatcher` is not tied to an event loop running on the
+ /// current thread.
+ #[inline]
+ pub fn new(inner: T, dispatcher: Dispatcher) -> Self {
+ let thread_id = std::thread::current().id();
+
+ // Ensure the dispatcher is tied to the same thread.
+ assert_eq!(thread_id, dispatcher.thread_id());
+
+ Self {
+ value: ManuallyDrop::new(inner),
+ thread_id,
+ dispatcher,
+ }
+ }
+
+ /// Returns `Ok(&T)` if called on the event loop thread.
+ ///
+ /// # Errors
+ ///
+ /// Returns `Error::NotMainThread` if called from a different thread.
+ #[inline]
+ pub fn get_ref(&self) -> crate::Result<&T> {
+ if self.is_event_loop_thread() {
+ Ok(&self.value)
+ } else {
+ Err(crate::Error::NotMainThread)
+ }
+ }
+
+ /// Returns `Ok(&mut T)` if called on the event loop thread.
+ ///
+ /// # Errors
+ ///
+ /// Returns `Error::NotMainThread` if called from a different thread.
+ #[inline]
+ pub fn get_mut(&mut self) -> crate::Result<&mut T> {
+ if self.is_event_loop_thread() {
+ Ok(&mut self.value)
+ } else {
+ Err(crate::Error::NotMainThread)
+ }
+ }
+
+ /// Consumes the wrapper and returns `Ok(T)` if called on the event loop
+ /// thread.
+ ///
+ /// # Errors
+ ///
+ /// Returns `Error::NotMainThread` if called from a different thread.
+ #[inline]
+ pub fn into_inner(self) -> crate::Result<T> {
+ if self.is_event_loop_thread() {
+ // Prevent `Drop` from running.
+ let mut this = ManuallyDrop::new(self);
+
+ // SAFETY: `self` is consumed by this function, and wrapped in
+ // `ManuallyDrop`, so the item's destructor is never run.
+ Ok(unsafe { ManuallyDrop::take(&mut this.value) })
+ } else {
+ Err(crate::Error::NotMainThread)
+ }
+ }
+
+ /// Execute a closure with `&T` on the event loop thread.
+ ///
+ /// Runs synchronously and returns the closure's result.
+ #[inline]
+ pub fn with<F, R>(&self, f: F) -> crate::Result<R>
+ where
+ F: Send + FnOnce(&T) -> R,
+ R: Send,
+ {
+ self.dispatcher.dispatch_sync(|| f(&self.value))
+ }
+
+ /// Execute a closure with `&mut T` on the event loop thread.
+ ///
+ /// Runs synchronously and returns the closure's result.
+ #[inline]
+ #[allow(
+ clippy::borrow_as_ptr,
+ clippy::ptr_as_ptr,
+ clippy::as_conversions
+ )]
+ pub fn with_mut<F, R>(&mut self, f: F) -> crate::Result<R>
+ where
+ F: Send + FnOnce(&mut T) -> R,
+ R: Send,
+ {
+ // TODO: This is pretty cursed. Should be a better way.
+ let value_ptr =
+ std::ptr::from_mut::<ManuallyDrop<T>>(&mut self.value) as usize;
+ self.dispatcher.dispatch_sync(|| unsafe {
+ // SAFETY: The closure executes on the event loop thread where the
+ // value was created, and we only create a unique mutable reference.
+ let value_mut: &mut T = &mut *(value_ptr as *mut T);
+ f(value_mut)
+ })
+ }
+
+ /// Returns `true` if called on the event loop thread.
+ #[inline]
+ #[must_use]
+ pub fn is_event_loop_thread(&self) -> bool {
+ std::thread::current().id() == self.thread_id
+ }
+}
+
+impl<T> fmt::Debug for ThreadBound<T> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("ThreadBound").finish_non_exhaustive()
+ }
+}
+
+impl<T> Drop for ThreadBound<T> {
+ #[allow(
+ clippy::borrow_as_ptr,
+ clippy::ptr_as_ptr,
+ clippy::as_conversions,
+ clippy::ref_as_ptr
+ )]
+ fn drop(&mut self) {
+ if mem::needs_drop::<T>() {
+ // TODO: This is pretty cursed. Should be a better way.
+ let value_ptr =
+ std::ptr::from_mut::<ManuallyDrop<T>>(&mut self.value) as usize;
+
+ let _ = self.dispatcher.dispatch_sync(|| unsafe {
+ // SAFETY: The value is dropped on the event loop thread, which is
+ // the same thread that it originated from (guaranteed by `new`).
+ // Additionally, the value is never used again after this point.
+ ManuallyDrop::drop(&mut *(value_ptr as *mut ManuallyDrop<T>));
+ });
+ }
+ }
+}
diff --git a/packages/wm-platform/src/window_event_hook.rs b/packages/wm-platform/src/window_event_hook.rs
deleted file mode 100644
index 19af532b..00000000
--- a/packages/wm-platform/src/window_event_hook.rs
+++ /dev/null
@@ -1,185 +0,0 @@
-use std::sync::{Arc, Mutex, OnceLock};
-
-use anyhow::Result;
-use tokio::sync::mpsc;
-use tracing::warn;
-use windows::Win32::{
- Foundation::HWND,
- UI::{
- Accessibility::{SetWinEventHook, UnhookWinEvent, HWINEVENTHOOK},
- WindowsAndMessaging::{
- EVENT_OBJECT_CLOAKED, EVENT_OBJECT_DESTROY, EVENT_OBJECT_HIDE,
- EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_NAMECHANGE,
- EVENT_OBJECT_SHOW, EVENT_OBJECT_UNCLOAKED, EVENT_SYSTEM_FOREGROUND,
- EVENT_SYSTEM_MINIMIZEEND, EVENT_SYSTEM_MINIMIZESTART,
- EVENT_SYSTEM_MOVESIZEEND, EVENT_SYSTEM_MOVESIZESTART, OBJID_WINDOW,
- WINEVENT_OUTOFCONTEXT, WINEVENT_SKIPOWNPROCESS,
- },
- },
-};
-
-use super::{NativeWindow, PlatformEvent};
-
-/// Global instance of `WindowEventHook`.
-///
-/// For use with hook procedure.
-static WIN_EVENT_HOOK: OnceLock<Arc<WindowEventHook>> = OnceLock::new();
-
-#[derive(Debug)]
-pub struct WindowEventHook {
- event_tx: mpsc::UnboundedSender<PlatformEvent>,
- hook_handles: Arc<Mutex<Vec<HWINEVENTHOOK>>>,
-}
-
-impl WindowEventHook {
- /// Creates an instance of `WindowEventHook`.
- pub fn new(
- event_tx: mpsc::UnboundedSender<PlatformEvent>,
- ) -> anyhow::Result<Arc<Self>> {
- let win_event_hook = Arc::new(Self {
- event_tx,
- hook_handles: Arc::new(Mutex::new(Vec::new())),
- });
-
- WIN_EVENT_HOOK.set(win_event_hook.clone()).map_err(|_| {
- anyhow::anyhow!("Window event hook already running.")
- })?;
-
- Ok(win_event_hook)
- }
-
- /// Starts a window event hook on the current thread. This assumes that a
- /// message loop is currently running.
- ///
- /// # Panics
- ///
- /// If the internal mutex is poisoned.
- pub fn start(&self) -> anyhow::Result<()> {
- *self.hook_handles.lock().unwrap() = Self::hook_win_events()?;
- Ok(())
- }
-
- /// Creates several window event hooks via `SetWinEventHook`.
- fn hook_win_events() -> Result<Vec<HWINEVENTHOOK>> {
- let event_ranges = [
- (EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_LOCATIONCHANGE),
- (EVENT_OBJECT_DESTROY, EVENT_OBJECT_HIDE),
- (EVENT_SYSTEM_MINIMIZESTART, EVENT_SYSTEM_MINIMIZEEND),
- (EVENT_SYSTEM_MOVESIZEEND, EVENT_SYSTEM_MOVESIZEEND),
- (EVENT_SYSTEM_MOVESIZESTART, EVENT_SYSTEM_MOVESIZESTART),
- (EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND),
- (EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_NAMECHANGE),
- (EVENT_OBJECT_CLOAKED, EVENT_OBJECT_UNCLOAKED),
- ];
-
- // Create separate hooks for each event range. This is more performant
- // than creating a single hook for all events and filtering them.
- event_ranges
- .iter()
- .try_fold(Vec::new(), |mut handles, event_range| {
- let hook_handle =
- Self::hook_win_event(event_range.0, event_range.1)?;
- handles.push(hook_handle);
- Ok(handles)
- })
- }
-
- /// Creates a window hook for the specified event range.
- fn hook_win_event(
- event_min: u32,
- event_max: u32,
- ) -> Result<HWINEVENTHOOK> {
- let hook_handle = unsafe {
- SetWinEventHook(
- event_min,
- event_max,
- None,
- Some(window_event_hook_proc),
- 0,
- 0,
- WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
- )
- };
-
- if hook_handle.is_invalid() {
- Err(anyhow::anyhow!("Failed to set window event hook."))
- } else {
- Ok(hook_handle)
- }
- }
-
- /// Invoked by the hook procedure when a window event is received.
- fn handle_event(&self, event_type: u32, handle: isize) {
- let window = NativeWindow::new(handle);
-
- let platform_event = match event_type {
- EVENT_OBJECT_DESTROY => PlatformEvent::WindowDestroyed(window),
- EVENT_SYSTEM_FOREGROUND => PlatformEvent::WindowFocused(window),
- EVENT_OBJECT_HIDE | EVENT_OBJECT_CLOAKED => {
- PlatformEvent::WindowHidden(window)
- }
- EVENT_OBJECT_LOCATIONCHANGE => {
- PlatformEvent::WindowLocationChanged(window)
- }
- EVENT_SYSTEM_MINIMIZESTART => PlatformEvent::WindowMinimized(window),
- EVENT_SYSTEM_MINIMIZEEND => {
- PlatformEvent::WindowMinimizeEnded(window)
- }
- EVENT_SYSTEM_MOVESIZEEND => {
- PlatformEvent::WindowMovedOrResizedEnd(window)
- }
- EVENT_SYSTEM_MOVESIZESTART => {
- PlatformEvent::WindowMovedOrResizedStart(window)
- }
- EVENT_OBJECT_SHOW | EVENT_OBJECT_UNCLOAKED => {
- PlatformEvent::WindowShown(window)
- }
- EVENT_OBJECT_NAMECHANGE => PlatformEvent::WindowTitleChanged(window),
- _ => return,
- };
-
- if let Err(err) = self.event_tx.send(platform_event) {
- warn!("Failed to send platform event '{}'.", err);
- }
- }
-
- /// Stops the window event hook and unhooks from all window events.
- ///
- /// # Panics
- ///
- /// If the internal mutex is poisoned.
- pub fn stop(&self) -> anyhow::Result<()> {
- for hook_handle in self.hook_handles.lock().unwrap().drain(..) {
- unsafe { UnhookWinEvent(hook_handle) }.ok()?;
- }
-
- Ok(())
- }
-}
-
-/// Callback passed to `SetWinEventHook` to handle window events.
-///
-/// This function is called on selected window events, and forwards them
-/// through an MPSC channel for the WM to process.
-extern "system" fn window_event_hook_proc(
- _hook: HWINEVENTHOOK,
- event_type: u32,
- handle: HWND,
- id_object: i32,
- id_child: i32,
- _event_thread: u32,
- _event_time: u32,
-) {
- let is_window_event =
- id_object == OBJID_WINDOW.0 && id_child == 0 && handle != HWND(0);
-
- // Check whether the event is associated with a window object instead
- // of a UI control.
- if !is_window_event {
- return;
- }
-
- if let Some(hook) = WIN_EVENT_HOOK.get() {
- hook.handle_event(event_type, handle.0);
- }
-}
diff --git a/packages/wm-platform/src/window_listener.rs b/packages/wm-platform/src/window_listener.rs
new file mode 100644
index 00000000..e6323834
--- /dev/null
+++ b/packages/wm-platform/src/window_listener.rs
@@ -0,0 +1,33 @@
+use tokio::sync::mpsc;
+
+use crate::{platform_impl, Dispatcher, WindowEvent};
+
+/// A listener for system-wide window events.
+pub struct WindowListener {
+ event_rx: mpsc::UnboundedReceiver<WindowEvent>,
+
+ /// Inner platform-specific window listener.
+ inner: platform_impl::WindowListener,
+}
+
+impl WindowListener {
+ /// Creates a new window listener.
+ pub fn new(dispatcher: &Dispatcher) -> crate::Result<Self> {
+ let (event_tx, event_rx) = mpsc::unbounded_channel();
+ let inner = platform_impl::WindowListener::new(event_tx, dispatcher)?;
+
+ Ok(Self { event_rx, inner })
+ }
+
+ /// Returns the next window event from the listener.
+ ///
+ /// This will block until a window event is available.
+ pub async fn next_event(&mut self) -> Option<WindowEvent> {
+ self.event_rx.recv().await
+ }
+
+ /// Terminates the window listener.
+ pub fn terminate(&mut self) {
+ self.inner.terminate();
+ }
+}
diff --git a/packages/wm-watcher/build.rs b/packages/wm-watcher/build.rs
index 2ecbffb1..996088ec 100644
--- a/packages/wm-watcher/build.rs
+++ b/packages/wm-watcher/build.rs
@@ -1,6 +1,10 @@
use tauri_winres::VersionInfo;
fn main() {
+ if cfg!(not(target_os = "windows")) {
+ panic!("wm-watcher is only supported on Windows.");
+ }
+
println!("cargo:rerun-if-env-changed=VERSION_NUMBER");
let mut res = tauri_winres::WindowsResource::new();
diff --git a/packages/wm-watcher/src/main.rs b/packages/wm-watcher/src/main.rs
index 0b9d691b..fa253eee 100644
--- a/packages/wm-watcher/src/main.rs
+++ b/packages/wm-watcher/src/main.rs
@@ -2,17 +2,13 @@
// whether a console window is spawned on launch, if not already ran
// through a console. The following prevents this additional console window
// in release mode.
-#![cfg_attr(
- all(not(debug_assertions), target_os = "windows"),
- windows_subsystem = "windows"
-)]
+#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![warn(clippy::all, clippy::pedantic)]
-use anyhow::{bail, Context};
-use tracing::info;
+use anyhow::Context;
use wm_common::{ClientResponseData, ContainerDto, WindowDto, WmEvent};
use wm_ipc_client::IpcClient;
-use wm_platform::NativeWindow;
+use wm_platform::{NativeWindow, NativeWindowWindowsExt, OpacityValue};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
@@ -32,17 +28,27 @@ async fn main() -> anyhow::Result<()> {
watch_managed_handles(&mut client, &mut managed_handles).await;
match subscribe_res {
- Ok(()) => info!("WM exited successfully. Skipping watcher cleanup."),
+ Ok(()) => {
+ tracing::info!("WM exited successfully. Skipping watcher cleanup.");
+ }
Err(err) => {
- info!("Running watcher cleanup. WM exited unexpectedly: {}", err);
+ tracing::info!(
+ "Running watcher cleanup. WM exited unexpectedly: {}",
+ err
+ );
- let managed_windows = managed_handles
- .into_iter()
- .map(NativeWindow::new)
- .collect::<Vec<_>>();
+ let managed_windows =
+ managed_handles.into_iter().map(NativeWindow::from_handle);
for window in managed_windows {
- window.cleanup();
+ if let Err(err) = window.show() {
+ tracing::warn!("Failed to show window: {:?}", err);
+ }
+
+ let _ = window.set_taskbar_visibility(true);
+ let _ = window.set_border_color(None);
+ let _ =
+ window.set_transparency(&OpacityValue::from_alpha(u8::MAX));
}
}
}
@@ -112,14 +118,14 @@ async fn watch_managed_handles(
match event_data {
Some(WmEvent::WindowManaged { managed_window }) => {
if let ContainerDto::Window(window) = managed_window {
- info!("Watcher added handle: {}.", window.handle);
+ tracing::info!("Watcher added handle: {}.", window.handle);
handles.push(window.handle);
}
}
Some(WmEvent::WindowUnmanaged {
unmanaged_handle, ..
}) => {
- info!("Watcher removed handle: {}.", unmanaged_handle);
+ tracing::info!("Watcher removed handle: {}.", unmanaged_handle);
handles.retain(|&handle| handle != unmanaged_handle);
}
Some(WmEvent::ApplicationExiting) => {
@@ -127,7 +133,7 @@ async fn watch_managed_handles(
}
Some(_) => unreachable!(),
None => {
- bail!("IPC connection closed unexpectedly.")
+ anyhow::bail!("IPC connection closed unexpectedly.")
}
}
}
diff --git a/packages/wm/Cargo.toml b/packages/wm/Cargo.toml
index ad1dd7a4..d98fbf56 100644
--- a/packages/wm/Cargo.toml
+++ b/packages/wm/Cargo.toml
@@ -19,23 +19,26 @@ tauri-winres = { workspace = true }
[dependencies]
anyhow = { workspace = true }
+auto-launch = "0.5"
ambassador = "0.4"
clap = { workspace = true }
enum-as-inner = "0.6"
futures-util = { workspace = true }
home = { workspace = true }
+image = "0.25"
serde = { workspace = true }
serde_json = { workspace = true }
serde_yaml = "0.9"
+shell-util = "0.0"
tokio = { workspace = true }
tokio-tungstenite = { workspace = true }
tracing = { workspace = true }
tracing-appender = "0.2"
tracing-subscriber = { workspace = true }
-tray-icon = "0.20"
+tray-icon = "0.21"
uuid = { workspace = true }
-wm-common = { path = "../wm-common" }
wm-cli = { path = "../wm-cli" }
-wm-platform = { path = "../wm-platform" }
+wm-common = { path = "../wm-common" }
wm-ipc-client = { path = "../wm-ipc-client" }
-wm-macros.workspace = true
+wm-macros = { workspace = true }
+wm-platform = { path = "../wm-platform" }
diff --git a/packages/wm/src/commands/container/focus_in_direction.rs b/packages/wm/src/commands/container/focus_in_direction.rs
index 8ffda03d..1a3c5b67 100644
--- a/packages/wm/src/commands/container/focus_in_direction.rs
+++ b/packages/wm/src/commands/container/focus_in_direction.rs
@@ -1,5 +1,6 @@
use anyhow::Context;
-use wm_common::{Direction, TilingDirection, WindowState};
+use wm_common::{TilingDirection, WindowState};
+use wm_platform::Direction;
use super::set_focused_descendant;
use crate::{
diff --git a/packages/wm/src/commands/general/platform_sync.rs b/packages/wm/src/commands/general/platform_sync.rs
index 5e1d6818..6f4a9dab 100644
--- a/packages/wm/src/commands/general/platform_sync.rs
+++ b/packages/wm/src/commands/general/platform_sync.rs
@@ -1,13 +1,15 @@
-use std::time::Duration;
-
use anyhow::Context;
-use tokio::task;
-use tracing::{info, warn};
+#[cfg(target_os = "windows")]
+use wm_common::WindowEffectConfig;
use wm_common::{
- CornerStyle, CursorJumpTrigger, DisplayState, HideMethod, OpacityValue,
- UniqueExt, WindowEffectConfig, WindowState, WmEvent,
+ CursorJumpTrigger, DisplayState, HideCorner, HideMethod, UniqueExt,
+ WindowState, WmEvent,
};
-use wm_platform::{Platform, ZOrder};
+#[cfg(target_os = "windows")]
+use wm_platform::NativeWindowWindowsExt;
+#[cfg(target_os = "windows")]
+use wm_platform::{CornerStyle, OpacityValue};
+use wm_platform::{Rect, WindowZOrder};
use crate::{
models::{Container, WindowContainer},
@@ -80,23 +82,25 @@ fn sync_focus(
focused_container: &Container,
state: &mut WmState,
) -> anyhow::Result<()> {
- let native_window = match focused_container.as_window_container() {
- Ok(window) => window.native().clone(),
- _ => Platform::desktop_window(),
+ let native_window = focused_container.as_window_container().ok();
+
+ // Sets focus to the appropriate target:
+ // - If the container is a window, focuses that window.
+ // - If the container is a workspace, "resets" focus by focusing the
+ // desktop window.
+ //
+ // In either case, a `PlatformEvent::WindowFocused` event is subsequently
+ // triggered.
+ let result = if let Some(window) = native_window {
+ tracing::info!("Setting focus to window: {window}");
+ window.native().focus()
+ } else {
+ tracing::info!("Setting focus to the desktop window.");
+ state.dispatcher.reset_focus()
};
- // Set focus to the given window handle. If the container is a normal
- // window, then this will trigger a `PlatformEvent::WindowFocused` event.
- if Platform::foreground_window() != native_window {
- if let Ok(window) = focused_container.as_window_container() {
- info!("Setting focus to window: {window}");
- } else {
- info!("Setting focus to the desktop window.");
- }
-
- if let Err(err) = native_window.set_foreground() {
- warn!("Failed to set foreground window: {}", err);
- }
+ if let Err(err) = result {
+ tracing::warn!("Failed to set focus: {}", err);
}
state.emit_event(WmEvent::FocusChanged {
@@ -189,6 +193,8 @@ fn redraw_containers(
// Sort the windows to update by their focus order. The most recently
// focused window will be updated first.
+ // TODO: To reduce flicker, redraw windows that will be shown first,
+ // then redraw the ones to be hidden last.
windows.sort_by_key(|window| {
descendant_focus_order
.iter()
@@ -198,19 +204,29 @@ fn redraw_containers(
windows
};
+ // Get monitors by their optimal hide corner.
+ let monitors_by_hide_corner = state.monitors_by_hide_corner();
+
for window in windows_to_update.iter().rev() {
let should_bring_to_front = windows_to_bring_to_front.contains(window);
let workspace =
window.workspace().context("Window has no workspace.")?;
+ let monitor = window.monitor().context("No monitor.")?;
+ let hide_corner = monitors_by_hide_corner
+ .iter()
+ .find(|(m, _)| m.id() == monitor.id())
+ .map(|(_, hide_corner)| hide_corner)
+ .context("Monitor not found in hide corner map.")?;
+
// Whether the window should be shown above all other windows.
let z_order = match window.state() {
WindowState::Floating(config) if config.shown_on_top => {
- ZOrder::TopMost
+ WindowZOrder::TopMost
}
WindowState::Fullscreen(config) if config.shown_on_top => {
- ZOrder::TopMost
+ WindowZOrder::TopMost
}
_ if should_bring_to_front => {
let focused_descendant = workspace
@@ -220,26 +236,33 @@ fn redraw_containers(
if let Some(focused_descendant) = focused_descendant {
if window.id() == focused_descendant.id() {
- ZOrder::Normal
+ WindowZOrder::Normal
} else {
- ZOrder::AfterWindow(focused_descendant.native().handle)
+ WindowZOrder::AfterWindow(focused_descendant.native().id())
}
} else {
- ZOrder::Normal
+ WindowZOrder::Normal
}
}
- _ => ZOrder::Normal,
+ _ => WindowZOrder::Normal,
};
- // Set the z-order of the window and skip updating it's position if the
- // window only requires a z-order change.
+ // Set the z-order of the window.
+ //
+ // NOTE: macOS doesn't have a robust public API for setting the z-order
+ // of a window. See `NativeWindow::raise` for more details.
+ #[cfg(target_os = "windows")]
if should_bring_to_front && !windows_to_redraw.contains(window) {
- info!("Updating window z-order: {window}");
+ tracing::info!("Updating window z-order: {window}");
if let Err(err) = window.native().set_z_order(&z_order) {
- warn!("Failed to set window z-order: {}", err);
+ tracing::warn!("Failed to set window z-order: {}", err);
}
+ }
+ // Skip updating the window's position if it only required a z-order
+ // change.
+ if !windows_to_redraw.contains(window) {
continue;
}
@@ -257,44 +280,36 @@ fn redraw_containers(
},
);
- let rect = window
- .to_rect()?
- .apply_delta(&window.total_border_delta()?, None);
-
let is_visible = matches!(
window.display_state(),
DisplayState::Showing | DisplayState::Shown
);
- info!("Updating window position: {window}");
-
- if let Err(err) = window.native().set_position(
- &window.state(),
- &rect,
- &z_order,
- is_visible,
- &config.value.general.hide_method,
- window.has_pending_dpi_adjustment(),
- ) {
- warn!("Failed to set window position: {}", err);
+ if let Err(err) =
+ reposition_window(window, *hide_corner, &z_order, is_visible, config)
+ {
+ tracing::warn!("Failed to set window position: {}", err);
}
// Whether the window is either transitioning to or from fullscreen.
// TODO: This check can be improved since `prev_state` can be
// fullscreen without it needing to be marked as not fullscreen.
- let is_transitioning_fullscreen =
- match (window.prev_state(), window.state()) {
- (Some(_), WindowState::Fullscreen(s)) if !s.maximized => true,
- (Some(WindowState::Fullscreen(_)), _) => true,
- _ => false,
- };
-
- if is_transitioning_fullscreen {
- if let Err(err) = window.native().mark_fullscreen(matches!(
- window.state(),
- WindowState::Fullscreen(_)
- )) {
- warn!("Failed to mark window as fullscreen: {}", err);
+ #[cfg(target_os = "windows")]
+ {
+ let is_transitioning_fullscreen =
+ match (window.prev_state(), window.state()) {
+ (Some(_), WindowState::Fullscreen(s)) if !s.maximized => true,
+ (Some(WindowState::Fullscreen(_)), _) => true,
+ _ => false,
+ };
+
+ if is_transitioning_fullscreen {
+ if let Err(err) = window.native().mark_fullscreen(matches!(
+ window.state(),
+ WindowState::Fullscreen(_)
+ )) {
+ tracing::warn!("Failed to mark window as fullscreen: {}", err);
+ }
}
}
@@ -302,6 +317,7 @@ fn redraw_containers(
// effect). Since cloaked windows are normally always visible in the
// taskbar, we only need to set visibility if `show_all_in_taskbar` is
// `false`.
+ #[cfg(target_os = "windows")]
if config.value.general.hide_method == HideMethod::Cloak
&& !config.value.general.show_all_in_taskbar
&& matches!(
@@ -311,7 +327,143 @@ fn redraw_containers(
{
if let Err(err) = window.native().set_taskbar_visibility(is_visible)
{
- warn!("Failed to set taskbar visibility: {}", err);
+ tracing::warn!("Failed to set taskbar visibility: {}", err);
+ }
+ }
+ }
+
+ Ok(())
+}
+
+fn reposition_window(
+ window: &WindowContainer,
+ hide_corner: HideCorner,
+ // LINT: `z_order` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
+ z_order: &WindowZOrder,
+ is_visible: bool,
+ config: &UserConfig,
+) -> anyhow::Result<()> {
+ let rect = window
+ .to_rect()?
+ .apply_delta(&window.total_border_delta()?, None);
+
+ // For `HideMethod::PlaceInCorner`, we need to reposition hidden windows
+ // to the corner of the monitor.
+ if config.value.general.hide_method == HideMethod::PlaceInCorner
+ && !is_visible
+ {
+ const VISIBLE_SLIVER: i32 = 1;
+
+ let monitor_rect = window
+ .monitor()
+ .context("No monitor.")?
+ .native_properties()
+ .working_area;
+
+ let frame = window.native_properties().frame;
+
+ let position_y = monitor_rect.bottom - VISIBLE_SLIVER;
+ let position_x = match hide_corner {
+ HideCorner::BottomLeft => {
+ monitor_rect.left + VISIBLE_SLIVER - frame.width()
+ }
+ HideCorner::BottomRight => monitor_rect.right - VISIBLE_SLIVER,
+ };
+
+ // Even though the window size is unchanged, `NativeWindow::set_frame`
+ // is used instead of `NativeWindow::reposition` because the latter
+ // resulted in occasional incorrect positionings on macOS.
+ window.native().set_frame(&Rect::from_xy(
+ position_x,
+ position_y,
+ frame.width(),
+ frame.height(),
+ ))?;
+
+ return Ok(());
+ }
+
+ if window.active_drag().is_some() {
+ window.native().resize(rect.width(), rect.height())?;
+ } else {
+ #[cfg(target_os = "macos")]
+ window.native().set_frame(&rect)?;
+
+ #[cfg(target_os = "windows")]
+ {
+ use wm_platform::{
+ SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED, SWP_NOACTIVATE,
+ SWP_NOCOPYBITS, SWP_NOSENDCHANGING, WS_MAXIMIZEBOX,
+ };
+
+ // Restore window if it's minimized/maximized and shouldn't be. This
+ // is needed to be able to move and resize it.
+ let should_restore = match &window.state() {
+ // Need to restore window if transitioning from maximized
+ // fullscreen to non-maximized fullscreen.
+ WindowState::Fullscreen(fullscreen) => {
+ !fullscreen.maximized && window.native().is_maximized()?
+ }
+ // No need to restore window if it'll be minimized. Transitioning
+ // from maximized to minimized works without having to
+ // restore.
+ WindowState::Minimized => false,
+ _ => {
+ window.native().is_minimized()?
+ || window.native().is_maximized()?
+ }
+ };
+
+ if should_restore {
+ // Restoring to position has the same effect as `ShowWindow` with
+ // `SW_RESTORE`, but doesn't cause a flicker.
+ window.native().restore(Some(&rect))?;
+ }
+
+ let mut swp_flags = SWP_NOACTIVATE
+ | SWP_NOCOPYBITS
+ | SWP_NOSENDCHANGING
+ | SWP_ASYNCWINDOWPOS;
+
+ match &window.state() {
+ WindowState::Minimized => {
+ if !window.native().is_minimized()? {
+ window.native().minimize()?;
+ }
+ }
+ WindowState::Fullscreen(fullscreen)
+ if fullscreen.maximized
+ && window.native().has_window_style(WS_MAXIMIZEBOX) =>
+ {
+ if !window.native().is_maximized()? {
+ window.native().maximize()?;
+ }
+
+ window.native().set_window_pos(z_order, &rect, swp_flags)?;
+ }
+ _ => {
+ swp_flags |= SWP_FRAMECHANGED;
+
+ window.native().set_window_pos(z_order, &rect, swp_flags)?;
+
+ // When there's a mismatch between the DPI of the monitor and the
+ // window, the window might be sized incorrectly after the first
+ // move. If we set the position twice, inconsistencies after the
+ // first move are resolved.
+ if window.has_pending_dpi_adjustment() {
+ window.native().set_window_pos(z_order, &rect, swp_flags)?;
+ }
+ }
+ }
+
+ // Set visibility based on the hide method.
+ if config.value.general.hide_method == HideMethod::Cloak {
+ window.native().set_cloaked(!is_visible)?;
+ } else if is_visible {
+ window.native().show()?;
+ } else {
+ window.native().hide()?;
}
}
}
@@ -332,7 +484,9 @@ fn jump_cursor(
let target_monitor =
focused_container.monitor().context("No monitor.")?;
- let cursor_monitor = Platform::mouse_position()
+ let cursor_monitor = state
+ .dispatcher
+ .cursor_position()
.ok()
.and_then(|pos| state.monitor_at_point(&pos));
@@ -346,8 +500,8 @@ fn jump_cursor(
if let Some(jump_target) = jump_target {
let center = jump_target.to_rect()?.center_point();
- if let Err(err) = Platform::set_cursor_pos(center.x, center.y) {
- warn!("Failed to set cursor position: {}", err);
+ if let Err(err) = state.dispatcher.set_cursor_position(&center) {
+ tracing::warn!("Failed to set cursor position: {}", err);
}
}
@@ -355,12 +509,16 @@ fn jump_cursor(
}
fn apply_window_effects(
+ // LINT: `window` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
window: &WindowContainer,
is_focused: bool,
config: &UserConfig,
) {
let window_effects = &config.value.window_effects;
+ // LINT: `effect_config` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
let effect_config = if is_focused {
&window_effects.focused_window
} else {
@@ -368,24 +526,28 @@ fn apply_window_effects(
};
// Skip if both focused + non-focused window effects are disabled.
+ #[cfg(target_os = "windows")]
if window_effects.focused_window.border.enabled
|| window_effects.other_windows.border.enabled
{
apply_border_effect(window, effect_config);
}
+ #[cfg(target_os = "windows")]
if window_effects.focused_window.hide_title_bar.enabled
|| window_effects.other_windows.hide_title_bar.enabled
{
apply_hide_title_bar_effect(window, effect_config);
}
+ #[cfg(target_os = "windows")]
if window_effects.focused_window.corner_style.enabled
|| window_effects.other_windows.corner_style.enabled
{
apply_corner_effect(window, effect_config);
}
+ #[cfg(target_os = "windows")]
if window_effects.focused_window.transparency.enabled
|| window_effects.other_windows.transparency.enabled
{
@@ -393,6 +555,7 @@ fn apply_window_effects(
}
}
+#[cfg(target_os = "windows")]
fn apply_border_effect(
window: &WindowContainer,
effect_config: &WindowEffectConfig,
@@ -410,12 +573,13 @@ fn apply_border_effect(
// Re-apply border color after a short delay to better handle
// windows that change it themselves.
- task::spawn(async move {
- tokio::time::sleep(Duration::from_millis(50)).await;
+ tokio::task::spawn(async move {
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
_ = native.set_border_color(border_color.as_ref());
});
}
+#[cfg(target_os = "windows")]
fn apply_hide_title_bar_effect(
window: &WindowContainer,
effect_config: &WindowEffectConfig,
@@ -425,6 +589,7 @@ fn apply_hide_title_bar_effect(
.set_title_bar_visibility(!effect_config.hide_title_bar.enabled);
}
+#[cfg(target_os = "windows")]
fn apply_corner_effect(
window: &WindowContainer,
effect_config: &WindowEffectConfig,
@@ -438,6 +603,7 @@ fn apply_corner_effect(
_ = window.native().set_corner_style(corner_style);
}
+#[cfg(target_os = "windows")]
fn apply_transparency_effect(
window: &WindowContainer,
effect_config: &WindowEffectConfig,
diff --git a/packages/wm/src/commands/general/reload_config.rs b/packages/wm/src/commands/general/reload_config.rs
index 59665a74..362895bb 100644
--- a/packages/wm/src/commands/general/reload_config.rs
+++ b/packages/wm/src/commands/general/reload_config.rs
@@ -1,6 +1,10 @@
use anyhow::Context;
use tracing::{info, warn};
-use wm_common::{HideMethod, ParsedConfig, WindowRuleEvent, WmEvent};
+#[cfg(target_os = "windows")]
+use wm_common::{HideMethod, ParsedConfig};
+use wm_common::{WindowRuleEvent, WmEvent};
+#[cfg(target_os = "windows")]
+use wm_platform::NativeWindowWindowsExt;
use crate::{
commands::{window::run_window_rules, workspace::sort_workspaces},
@@ -17,6 +21,7 @@ pub fn reload_config(
info!("Config reloaded.");
// Keep reference to old config for comparison.
+ #[cfg(target_os = "windows")]
let old_config = config.value.clone();
// Re-evaluate user config file and set its values in state.
@@ -32,9 +37,11 @@ pub fn reload_config(
update_container_gaps(state, config);
+ #[cfg(target_os = "windows")]
update_window_effects(&old_config, state, config)?;
// Ensure all windows are shown when hide method is changed.
+ #[cfg(target_os = "windows")]
if old_config.general.hide_method != config.value.general.hide_method
&& config.value.general.hide_method == HideMethod::Cloak
{
@@ -45,6 +52,7 @@ pub fn reload_config(
// Ensure all windows are shown in taskbar when `show_all_in_taskbar` is
// changed.
+ #[cfg(target_os = "windows")]
if old_config.general.show_all_in_taskbar
!= config.value.general.show_all_in_taskbar
&& config.value.general.show_all_in_taskbar
@@ -147,6 +155,7 @@ fn update_container_gaps(state: &mut WmState, config: &UserConfig) {
}
}
+#[cfg(target_os = "windows")]
fn update_window_effects(
old_config: &ParsedConfig,
state: &mut WmState,
diff --git a/packages/wm/src/commands/general/shell_exec.rs b/packages/wm/src/commands/general/shell_exec.rs
index 8d6f35ca..62bc0bf1 100644
--- a/packages/wm/src/commands/general/shell_exec.rs
+++ b/packages/wm/src/commands/general/shell_exec.rs
@@ -1,15 +1,148 @@
-use tracing::info;
-use wm_platform::Platform;
+use std::path::Path;
-pub fn shell_exec(command: &str, hide_window: bool) -> anyhow::Result<()> {
- let (program, args) = Platform::parse_command(command)?;
- info!("Parsed command program: '{}', args: '{}'.", program, args);
+#[cfg(target_os = "windows")]
+use anyhow::Context;
+#[cfg(target_os = "macos")]
+use shell_util::{CommandOptions, Shell};
+#[cfg(target_os = "windows")]
+use wm_platform::DispatcherExtWindows;
- Platform::run_command(&program, &args, hide_window).map_err(|err| {
- anyhow::anyhow!(format!(
- "Failed to execute '{command}'.\n\nError: {err}"
- ))
- })?;
+use crate::wm_state::WmState;
+
+pub fn shell_exec(
+ command: &str,
+ // LINT: `hide_window` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
+ hide_window: bool,
+ state: &WmState,
+) -> anyhow::Result<()> {
+ let (program, args) = parse_command(command, state)?;
+ tracing::info!(
+ "Parsed command program: '{}', args: '{}'.",
+ program,
+ args
+ );
+
+ // NOTE: The standard library's `Command::new` is not used because it
+ // launches the program as a subprocess. This prevents cleanup of handles
+ // held by our process (e.g. the IPC server port) until the subprocess
+ // exits.
+ #[cfg(target_os = "macos")]
+ {
+ Shell::spawn(
+ &program,
+ args.split_whitespace(),
+ &CommandOptions::default(),
+ )?;
+ }
+ #[cfg(target_os = "windows")]
+ {
+ let home_dir =
+ home::home_dir().context("Unable to get home directory.")?;
+
+ // TODO: Use `Shell::spawn` instead. `ShellExecuteExW` is still used to
+ // be able to launch programs from the App Paths registry
+ // (`HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths`), like
+ // `chrome` without it being in $PATH.
+ state.dispatcher.shell_execute_ex(
+ &program,
+ &args,
+ &home_dir,
+ hide_window,
+ )?;
+ }
Ok(())
}
+
+/// Parses a command string into a program name/path and arguments. This
+/// also expands any environment variables found in the command string if
+/// they are wrapped in `%` characters. If the command string is a path,
+/// a file extension is required.
+///
+/// This is similar to the `SHEvaluateSystemCommandTemplate` Win32
+/// function. It also parses program name/path and arguments, but can't
+/// handle `/` as file path delimiters and it errors for certain programs
+/// (e.g. `code`).
+///
+/// Returns a tuple containing the program name/path and arguments.
+///
+/// # Examples
+///
+/// ```no_run
+/// let (prog, args) = parse_command("code .")?;
+/// assert_eq!(prog, "code");
+/// assert_eq!(args, ".");
+///
+/// let (prog, args) = parse_command(
+/// r#"C:\Program Files\Git\git-bash --cd=C:\Users\larsb\.glaze-wm"#,
+/// )?;
+/// assert_eq!(prog, r#"C:\Program Files\Git\git-bash"#);
+/// assert_eq!(args, r#"--cd=C:\Users\larsb\.glaze-wm"#);
+/// ```
+fn parse_command(
+ command: &str,
+ // LINT: `state` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
+ state: &WmState,
+) -> anyhow::Result<(String, String)> {
+ // Expand environment variables in the command string.
+ let expanded_command = {
+ #[cfg(target_os = "windows")]
+ {
+ state.dispatcher.expand_env_strings(command)?
+ }
+ #[cfg(target_os = "macos")]
+ {
+ // TODO: Expand env variables on macOS.
+ command.to_string()
+ }
+ };
+
+ let command_parts =
+ expanded_command.split_whitespace().collect::<Vec<_>>();
+
+ // If the command starts with double quotes, then the program name/path
+ // is wrapped in double quotes (e.g. `"C:\path\to\app.exe" --flag`).
+ if expanded_command.starts_with('"') {
+ // Find the closing double quote.
+ let (closing_index, _) =
+ expanded_command.match_indices('"').nth(2).ok_or_else(|| {
+ anyhow::anyhow!(
+ "Command doesn't have an ending `\"`: '{expanded_command}'."
+ )
+ })?;
+
+ return Ok((
+ expanded_command[1..closing_index].to_string(),
+ expanded_command[closing_index + 1..].trim().to_string(),
+ ));
+ }
+
+ // The first part is the program name if it doesn't contain a slash or
+ // backslash.
+ if let Some(first_part) = command_parts.first() {
+ if !first_part.contains(&['/', '\\'][..]) {
+ let args = command_parts[1..].join(" ");
+ return Ok(((*first_part).to_string(), args));
+ }
+ }
+
+ let mut cumulative_path = Vec::new();
+
+ // Lastly, iterate over the command until a valid file path is found.
+ for (part_index, &part) in command_parts.iter().enumerate() {
+ cumulative_path.push(part);
+
+ if Path::new(&cumulative_path.join(" ")).is_file() {
+ return Ok((
+ cumulative_path.join(" "),
+ command_parts[part_index + 1..].join(" "),
+ ));
+ }
+ }
+
+ anyhow::bail!(
+ "Program path is not valid for command '{expanded_command}'."
+ )
+}
diff --git a/packages/wm/src/commands/monitor/add_monitor.rs b/packages/wm/src/commands/monitor/add_monitor.rs
index fea2b357..ca07d099 100644
--- a/packages/wm/src/commands/monitor/add_monitor.rs
+++ b/packages/wm/src/commands/monitor/add_monitor.rs
@@ -1,27 +1,28 @@
use anyhow::Context;
use tracing::info;
use wm_common::WmEvent;
-use wm_platform::NativeMonitor;
+use wm_platform::Display;
use crate::{
commands::{
container::{attach_container, move_container_within_tree},
workspace::{activate_workspace, sort_workspaces},
},
- models::{Monitor, Workspace},
+ models::{Monitor, NativeMonitorProperties, Workspace},
traits::{CommonGetters, PositionGetters, WindowGetters},
user_config::UserConfig,
wm_state::WmState,
};
pub fn add_monitor(
- native_monitor: NativeMonitor,
+ native_display: Display,
+ native_properties: NativeMonitorProperties,
state: &mut WmState,
) -> anyhow::Result<Monitor> {
// Create `Monitor` instance. This uses the working area of the monitor
// instead of the bounds of the display. The working area excludes
// taskbars and other reserved display space.
- let monitor = Monitor::new(native_monitor);
+ let monitor = Monitor::new(native_display, native_properties);
attach_container(
&monitor.clone().into(),
diff --git a/packages/wm/src/commands/monitor/remove_monitor.rs b/packages/wm/src/commands/monitor/remove_monitor.rs
index afdcf31f..899b5a91 100644
--- a/packages/wm/src/commands/monitor/remove_monitor.rs
+++ b/packages/wm/src/commands/monitor/remove_monitor.rs
@@ -53,7 +53,7 @@ pub fn remove_monitor(
state.emit_event(WmEvent::MonitorRemoved {
removed_id: monitor.id(),
- removed_device_name: monitor.native().device_name()?.clone(),
+ removed_device_name: monitor.native_properties().device_name,
});
Ok(())
diff --git a/packages/wm/src/commands/monitor/update_monitor.rs b/packages/wm/src/commands/monitor/update_monitor.rs
index 5767cc6b..1e4a1d28 100644
--- a/packages/wm/src/commands/monitor/update_monitor.rs
+++ b/packages/wm/src/commands/monitor/update_monitor.rs
@@ -1,15 +1,25 @@
use tracing::info;
use wm_common::WmEvent;
-use wm_platform::NativeMonitor;
+use wm_platform::Display;
-use crate::{models::Monitor, wm_state::WmState};
+use crate::{
+ models::{Monitor, NativeMonitorProperties},
+ wm_state::WmState,
+};
pub fn update_monitor(
monitor: &Monitor,
- native_monitor: NativeMonitor,
+ native_display: &Display,
state: &mut WmState,
) -> anyhow::Result<()> {
- monitor.set_native(native_monitor);
+ monitor.set_native(native_display.clone());
+
+ // TODO: Move this out.
+ if let Ok(native_properties) =
+ NativeMonitorProperties::try_from(native_display)
+ {
+ monitor.set_native_properties(native_properties);
+ }
info!("Monitor updated: {monitor}");
diff --git a/packages/wm/src/commands/window/manage_window.rs b/packages/wm/src/commands/window/manage_window.rs
index e08a4f17..df5f8ff5 100644
--- a/packages/wm/src/commands/window/manage_window.rs
+++ b/packages/wm/src/commands/window/manage_window.rs
@@ -1,9 +1,7 @@
use anyhow::Context;
use tracing::info;
-use wm_common::{
- try_warn, LengthValue, RectDelta, WindowRuleEvent, WindowState, WmEvent,
-};
-use wm_platform::NativeWindow;
+use wm_common::{try_warn, WindowRuleEvent, WindowState, WmEvent};
+use wm_platform::{NativeWindow, RectDelta};
use crate::{
commands::{
@@ -11,7 +9,8 @@ use crate::{
window::run_window_rules,
},
models::{
- Container, Monitor, NonTilingWindow, TilingWindow, WindowContainer,
+ Container, Monitor, NativeWindowProperties, NonTilingWindow,
+ TilingWindow, WindowContainer,
},
traits::{CommonGetters, PositionGetters, WindowGetters},
user_config::UserConfig,
@@ -24,10 +23,21 @@ pub fn manage_window(
state: &mut WmState,
config: &mut UserConfig,
) -> anyhow::Result<()> {
+ let Some(native_properties) =
+ check_is_manageable(&native_window).unwrap_or(None)
+ else {
+ return Ok(());
+ };
+
// Create the window instance. This may fail if the window handle has
// already been destroyed.
- let window =
- try_warn!(create_window(native_window, target_parent, state, config));
+ let window = try_warn!(create_window(
+ native_window,
+ native_properties,
+ target_parent,
+ state,
+ config
+ ));
// Set the newly added window as focus descendant. This means the window
// rules will be run as if the window is focused.
@@ -74,8 +84,75 @@ pub fn manage_window(
Ok(())
}
+/// Checks if a window is manageable and retrieves its native properties.
+///
+/// Returns `Ok(Some(properties))` if the window is manageable and its
+/// properties were retrieved successfully.
+fn check_is_manageable(
+ native_window: &NativeWindow,
+) -> anyhow::Result<Option<NativeWindowProperties>> {
+ if !native_window.is_visible()? {
+ return Ok(None);
+ }
+
+ #[cfg(target_os = "macos")]
+ {
+ use wm_platform::NativeWindowExtMacOs;
+
+ let is_standard_window = native_window.role()? == "AXWindow"
+ && native_window.subrole()? == "AXStandardWindow";
+
+ if !is_standard_window {
+ return Ok(None);
+ }
+ }
+
+ // Ensure window has a valid process name, title, etc.
+ let native_properties = NativeWindowProperties::try_from(native_window)?;
+
+ #[cfg(target_os = "windows")]
+ {
+ use wm_platform::{
+ NativeWindowWindowsExt, WS_CAPTION, WS_CHILD, WS_EX_NOACTIVATE,
+ WS_EX_TOOLWINDOW,
+ };
+
+ // TODO: Temporary fix for managing Flow Launcher until a force manage
+ // command is added.
+ let is_flow_launcher = native_properties.process_name
+ == "Flow.Launcher"
+ && native_properties.title == "Flow.Launcher";
+
+ if !is_flow_launcher {
+ // Ensure window is top-level (i.e. not a child window). Ignore
+ // windows that cannot be focused or if they're unavailable in
+ // task switcher (alt+tab menu).
+ if native_window.has_window_style(WS_CHILD)
+ || native_window
+ .has_window_style_ex(WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW)
+ {
+ return Ok(None);
+ }
+
+ // Some applications spawn top-level windows for menus that
+ // should be ignored. This includes the autocomplete popup in
+ // Notepad++ and title bar menu in Keepass. Although not
+ // foolproof, these can typically be identified by having an
+ // owner window and no title bar.
+ if native_window.has_owner_window()
+ && !native_window.has_window_style(WS_CAPTION)
+ {
+ return Ok(None);
+ }
+ }
+ }
+
+ Ok(Some(native_properties))
+}
+
fn create_window(
native_window: NativeWindow,
+ native_properties: NativeWindowProperties,
target_parent: Option<Container>,
state: &mut WmState,
config: &UserConfig,
@@ -90,7 +167,7 @@ fn create_window(
let gaps_config = config.value.gaps.clone();
let window_state =
- window_state_to_create(&native_window, &nearest_monitor, config)?;
+ window_state_to_create(&native_properties, &nearest_monitor, config)?;
// Attach the new window as the first child of the target parent (if
// provided), otherwise, add as a sibling of the focused container.
@@ -115,34 +192,31 @@ fn create_window(
let is_same_workspace = nearest_workspace.id() == target_workspace.id();
let floating_placement = {
let placement = if !is_same_workspace || prefers_centered {
- native_window
- .frame_position()?
+ native_properties
+ .frame
.translate_to_center(&target_workspace.to_rect()?)
} else {
- native_window.frame_position()?
+ native_properties.frame.clone()
};
- // Clamp the window size to 90% of the workspace size.
- #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
+ // Clamp the window size to be within the workspace's outer gaps. 10px
+ // is arbitrary - helps differentiate from tiling windows.
+ let max_workspace_rect = target_workspace.max_workspace_rect()?;
placement.clamp_size(
- (target_workspace.to_rect()?.width() as f32 * 0.9) as i32,
- (target_workspace.to_rect()?.height() as f32 * 0.9) as i32,
+ max_workspace_rect.width() - 10,
+ max_workspace_rect.height() - 10,
)
};
// Window has no border delta unless it's later changed via the
// `adjust_borders` command.
- let border_delta = RectDelta::new(
- LengthValue::from_px(0),
- LengthValue::from_px(0),
- LengthValue::from_px(0),
- LengthValue::from_px(0),
- );
+ let border_delta = RectDelta::zero();
let window_container: WindowContainer = match window_state {
WindowState::Tiling => TilingWindow::new(
None,
native_window,
+ native_properties,
None,
border_delta,
floating_placement,
@@ -155,6 +229,7 @@ fn create_window(
_ => NonTilingWindow::new(
None,
native_window,
+ native_properties,
window_state,
None,
border_delta,
@@ -188,28 +263,31 @@ fn create_window(
///
/// Note that maximized windows are initialized as tiling.
fn window_state_to_create(
- native_window: &NativeWindow,
+ native_properties: &NativeWindowProperties,
nearest_monitor: &Monitor,
config: &UserConfig,
) -> anyhow::Result<WindowState> {
- if native_window.is_minimized()? {
+ if native_properties.is_minimized {
return Ok(WindowState::Minimized);
}
let nearest_workspace = nearest_monitor
.displayed_workspace()
- .context("No Workspace.")?;
-
- let monitor_rect = if config
- .outer_gaps_for_workspace(&nearest_workspace)
- .is_significant()
+ .context("No workspace.")?;
+
+ // Only initialize as fullscreen if the window *exceeds* the workspace
+ // bounds (due to the 1px inset).
+ //
+ // For example, with 0px outer gaps and a window that covers the entire
+ // workspace, it would still not be initialized as fullscreen. The window
+ // needs to be within the workspace's outer gaps by at least 1px on each
+ // side.
+ if !native_properties.is_maximized
+ && native_properties
+ .frame
+ .inset(1)
+ .contains_rect(&nearest_workspace.max_workspace_rect()?)
{
- nearest_monitor.native().working_rect()?.clone()
- } else {
- nearest_monitor.to_rect()?
- };
-
- if native_window.is_fullscreen(&monitor_rect)? {
return Ok(WindowState::Fullscreen(
config
.value
@@ -221,7 +299,7 @@ fn window_state_to_create(
}
// Initialize windows that can't be resized as floating.
- if !native_window.is_resizable() {
+ if !native_properties.is_resizable {
return Ok(WindowState::Floating(
config.value.window_behavior.state_defaults.floating.clone(),
));
diff --git a/packages/wm/src/commands/window/move_window_in_direction.rs b/packages/wm/src/commands/window/move_window_in_direction.rs
index 93292674..5fcbc0c7 100644
--- a/packages/wm/src/commands/window/move_window_in_direction.rs
+++ b/packages/wm/src/commands/window/move_window_in_direction.rs
@@ -1,5 +1,6 @@
use anyhow::Context;
-use wm_common::{Direction, Rect, TilingDirection, WindowState};
+use wm_common::{TilingDirection, WindowState};
+use wm_platform::{Direction, Rect};
use crate::{
commands::container::{
@@ -412,8 +413,8 @@ fn new_floating_position(
state: &mut WmState,
) -> anyhow::Result<Option<(Rect, Monitor)>> {
let monitor = window_to_move.monitor().context("No monitor.")?;
- let monitor_rect = monitor.native().working_rect()?.clone();
- let window_pos = window_to_move.native().frame_position()?;
+ let monitor_rect = monitor.native_properties().working_area;
+ let window_pos = window_to_move.native_properties().frame;
let is_on_monitor_edge = match direction {
Direction::Up => window_pos.top == monitor_rect.top,
@@ -428,7 +429,7 @@ fn new_floating_position(
let next_monitor = state.monitor_in_direction(&monitor, direction)?;
if let Some(next_monitor) = next_monitor {
- let monitor_rect = next_monitor.native().working_rect()?.clone();
+ let monitor_rect = next_monitor.native().working_area()?.clone();
let position = snap_to_monitor_edge(
&window_pos,
diff --git a/packages/wm/src/commands/window/resize_window.rs b/packages/wm/src/commands/window/resize_window.rs
index d576b079..f0ba5fda 100644
--- a/packages/wm/src/commands/window/resize_window.rs
+++ b/packages/wm/src/commands/window/resize_window.rs
@@ -1,4 +1,4 @@
-use wm_common::LengthValue;
+use wm_platform::LengthValue;
use super::set_window_size;
use crate::{
@@ -56,7 +56,7 @@ pub fn resize_window(
.container_to_resize(false)?
.and_then(|container| container.parent())
.and_then(|parent| {
- parent.to_rect().ok().map(|rect| rect.width())
+ parent.to_rect().ok().map(|rect| rect.height())
})
.and_then(|parent_height| {
let (_, vertical_gap) = tiling_window.inner_gaps().ok()?;
@@ -72,7 +72,7 @@ pub fn resize_window(
)
}),
_ => window.parent().and_then(|parent| {
- parent.to_rect().ok().map(|rect| rect.width())
+ parent.to_rect().ok().map(|rect| rect.height())
}),
};
diff --git a/packages/wm/src/commands/window/run_window_rules.rs b/packages/wm/src/commands/window/run_window_rules.rs
index 53fea023..96bb0d74 100644
--- a/packages/wm/src/commands/window/run_window_rules.rs
+++ b/packages/wm/src/commands/window/run_window_rules.rs
@@ -18,7 +18,7 @@ pub fn run_window_rules(
config: &mut UserConfig,
) -> anyhow::Result<Option<WindowContainer>> {
let pending_window_rules =
- config.pending_window_rules(&window, event_type)?;
+ config.pending_window_rules(&window, event_type);
let mut subject_window = window;
diff --git a/packages/wm/src/commands/window/set_window_position.rs b/packages/wm/src/commands/window/set_window_position.rs
index f71235f1..97206c10 100644
--- a/packages/wm/src/commands/window/set_window_position.rs
+++ b/packages/wm/src/commands/window/set_window_position.rs
@@ -1,5 +1,6 @@
use anyhow::Context;
-use wm_common::{Rect, WindowState};
+use wm_common::WindowState;
+use wm_platform::Rect;
use crate::{
models::WindowContainer,
diff --git a/packages/wm/src/commands/window/set_window_size.rs b/packages/wm/src/commands/window/set_window_size.rs
index b82d2666..7292aedc 100644
--- a/packages/wm/src/commands/window/set_window_size.rs
+++ b/packages/wm/src/commands/window/set_window_size.rs
@@ -1,5 +1,6 @@
use anyhow::Context;
-use wm_common::{LengthValue, Rect, WindowState};
+use wm_common::WindowState;
+use wm_platform::{LengthValue, Rect};
use crate::{
commands::container::resize_tiling_container,
diff --git a/packages/wm/src/commands/window/unmanage_window.rs b/packages/wm/src/commands/window/unmanage_window.rs
index dee29896..557d9735 100644
--- a/packages/wm/src/commands/window/unmanage_window.rs
+++ b/packages/wm/src/commands/window/unmanage_window.rs
@@ -33,7 +33,8 @@ pub fn unmanage_window(
state.emit_event(WmEvent::WindowUnmanaged {
unmanaged_id: window.id(),
- unmanaged_handle: window.native().handle,
+ #[allow(clippy::cast_possible_wrap, clippy::unnecessary_cast)]
+ unmanaged_handle: window.native().id().0 as isize,
});
// Reassign focus to suitable target.
diff --git a/packages/wm/src/commands/window/update_window_state.rs b/packages/wm/src/commands/window/update_window_state.rs
index 64ed1fd3..80d9f92c 100644
--- a/packages/wm/src/commands/window/update_window_state.rs
+++ b/packages/wm/src/commands/window/update_window_state.rs
@@ -125,11 +125,14 @@ fn set_non_tiling(
) -> anyhow::Result<WindowContainer> {
// A window can only be updated to a minimized state if it is
// natively minimized.
+ // TODO: Consider doing the same for maximized and fullscreen states.
if target_state == WindowState::Minimized
- && !window.native().is_minimized()?
+ && !window.native_properties().is_minimized
{
info!("No window state update. Minimizing window.");
+ // TODO: Instead of doing the platform call directly here, instead add
+ // a `queue_state_change` method to `PendingSync`.
if let Err(err) = window.native().minimize() {
warn!("Failed to minimize window: {}", err);
}
@@ -144,7 +147,11 @@ fn set_non_tiling(
let current_state = window.state();
// Update the window's previous state if the discriminant changes.
- if !current_state.is_same_state(&target_state) {
+ // TODO: Move out handling of active drag. Can then simplify calls to
+ // `set_active_drag` in `handle_window_moved_or_resized_end`.
+ if !current_state.is_same_state(&target_state)
+ && window.active_drag().is_none()
+ {
window.set_prev_state(current_state);
state.pending_sync.queue_workspace_to_reorder(workspace);
}
diff --git a/packages/wm/src/commands/workspace/mod.rs b/packages/wm/src/commands/workspace/mod.rs
index 60d6c4fb..b6156bcb 100644
--- a/packages/wm/src/commands/workspace/mod.rs
+++ b/packages/wm/src/commands/workspace/mod.rs
@@ -2,12 +2,12 @@ mod activate_workspace;
mod deactivate_workspace;
mod focus_workspace;
mod move_workspace_in_direction;
-mod update_workspace_config;
mod sort_workspaces;
+mod update_workspace_config;
pub use activate_workspace::*;
pub use deactivate_workspace::*;
pub use focus_workspace::*;
pub use move_workspace_in_direction::*;
-pub use update_workspace_config::*;
pub use sort_workspaces::*;
+pub use update_workspace_config::*;
diff --git a/packages/wm/src/commands/workspace/move_workspace_in_direction.rs b/packages/wm/src/commands/workspace/move_workspace_in_direction.rs
index 5312773d..0a5ad831 100644
--- a/packages/wm/src/commands/workspace/move_workspace_in_direction.rs
+++ b/packages/wm/src/commands/workspace/move_workspace_in_direction.rs
@@ -1,5 +1,6 @@
use anyhow::Context;
-use wm_common::{Direction, WmEvent};
+use wm_common::WmEvent;
+use wm_platform::Direction;
use super::{activate_workspace, deactivate_workspace, sort_workspaces};
use crate::{
diff --git a/packages/wm/src/commands/workspace/update_workspace_config.rs b/packages/wm/src/commands/workspace/update_workspace_config.rs
index 28c4bb12..7989ef9d 100644
--- a/packages/wm/src/commands/workspace/update_workspace_config.rs
+++ b/packages/wm/src/commands/workspace/update_workspace_config.rs
@@ -1,4 +1,4 @@
-use anyhow::{bail, Context};
+use anyhow::Context;
use wm_common::{InvokeUpdateWorkspaceConfig, WmEvent, WorkspaceConfig};
use super::sort_workspaces;
@@ -13,46 +13,45 @@ pub fn update_workspace_config(
config: &UserConfig,
new_config: &InvokeUpdateWorkspaceConfig,
) -> anyhow::Result<()> {
- let WorkspaceConfig {
- mut name,
- display_name,
- bind_to_monitor,
- keep_alive,
- } = workspace.config();
+ let current_config = workspace.config();
- let mut need_sort = false;
-
- // validate the workspace name change
+ // Validate the workspace name change.
if let Some(new_name) = &new_config.name {
- if new_name != &name {
+ if new_name != &current_config.name {
if let Some(_other_workspace) = state.workspace_by_name(new_name) {
- bail!("The workspace \"{}\" already exists", new_name);
+ anyhow::bail!("The workspace \"{}\" already exists", new_name);
}
- name.clone_from(new_name);
- need_sort = true;
}
}
- // the updated config
+ // Update the config with the incoming values.
let updated_config = WorkspaceConfig {
- name,
+ name: new_config
+ .name
+ .clone()
+ .unwrap_or(current_config.name.clone()),
display_name: if new_config.no_display_name {
None
} else {
- new_config.display_name.clone().or(display_name)
+ new_config
+ .display_name
+ .clone()
+ .or(current_config.display_name.clone())
},
- bind_to_monitor: new_config.bind_to_monitor.or(bind_to_monitor),
- keep_alive: new_config.keep_alive.unwrap_or(keep_alive),
+ bind_to_monitor: new_config
+ .bind_to_monitor
+ .or(current_config.bind_to_monitor),
+ keep_alive: new_config.keep_alive.unwrap_or(current_config.keep_alive),
};
- // Commit the change
workspace.set_config(updated_config);
- if need_sort {
- let monitor =
- workspace.monitor().context("No displayed workspace.")?;
- sort_workspaces(&monitor, config)?;
- }
+ sort_workspaces(
+ &workspace.monitor().context("No displayed workspace.")?,
+ config,
+ )?;
+
+ // TODO: Re-assign bound workspaces to their respective monitors.
state.emit_event(WmEvent::WorkspaceUpdated {
updated_workspace: workspace.to_dto()?,
diff --git a/packages/wm/src/events/handle_display_settings_changed.rs b/packages/wm/src/events/handle_display_settings_changed.rs
index fc1945f8..c940a274 100644
--- a/packages/wm/src/events/handle_display_settings_changed.rs
+++ b/packages/wm/src/events/handle_display_settings_changed.rs
@@ -1,13 +1,11 @@
use anyhow::Context;
-use tracing::info;
-use wm_platform::Platform;
use crate::{
commands::monitor::{
add_monitor, move_bounded_workspaces_to_new_monitor, remove_monitor,
sort_monitors, update_monitor,
},
- models::Monitor,
+ models::{Monitor, NativeMonitorProperties},
traits::{CommonGetters, PositionGetters, WindowGetters},
user_config::UserConfig,
wm_state::WmState,
@@ -17,98 +15,51 @@ pub fn handle_display_settings_changed(
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
- info!("Display settings changed.");
-
- let native_monitors = Platform::sorted_monitors()?;
-
- let hardware_ids = native_monitors
- .iter()
- .filter_map(|m| m.hardware_id().ok())
- .flatten()
- .cloned()
- .collect::<Vec<_>>();
+ tracing::info!("Display settings changed.");
+ let displays = state.dispatcher.sorted_displays()?;
let mut pending_monitors = state.monitors();
- let mut new_native_monitors = Vec::new();
-
- for native_monitor in native_monitors {
- // Get the corresponding `Monitor` instance by either its handle,
- // device path, or hardware ID. Monitor handles and device paths
- // *should* be unique, but can both change over time. The hardware ID
- // is not guaranteed to be unique, so we match against that last.
- let found_monitor = pending_monitors
- .iter()
- .find_map(|monitor| {
- if monitor.native().handle == native_monitor.handle {
- return Some(monitor);
- }
-
- if monitor.native().device_path().ok()??
- == native_monitor.device_path().ok()??
- {
- return Some(monitor);
- }
-
- let hardware_id = monitor.native().hardware_id().ok()??.clone();
-
- // Check that there aren't multiple monitors with the same
- // hardware ID.
- let is_unique =
- hardware_ids.iter().filter(|&id| *id == hardware_id).count()
- == 1;
-
- if is_unique
- && hardware_id == *native_monitor.hardware_id().ok()??
- {
- Some(monitor)
- } else {
- None
- }
- })
- .cloned();
-
- match found_monitor {
- Some(found_monitor) => {
- // Remove the monitor from the pending list so that we don't
- // consider it again in the next iteration.
- if let Some(index) = pending_monitors
- .iter()
- .position(|m| m.id() == found_monitor.id())
- {
- pending_monitors.remove(index);
- }
-
- update_monitor(&found_monitor, native_monitor, state)?;
- }
- None => {
- new_native_monitors.push(native_monitor);
+ let mut unmatched_displays = Vec::new();
+
+ // Match each display to an existing monitor and update it.
+ for display in displays {
+ // TODO: Create `NativeMonitorProperties` instances for displays just
+ // once (created in loop below and in `update_monitor`).
+ let properties = NativeMonitorProperties::try_from(&display)?;
+
+ match find_matching_monitor(&pending_monitors, &properties) {
+ Some((monitor, index)) => {
+ update_monitor(monitor, &display, state)?;
+ pending_monitors.remove(index);
}
+ None => unmatched_displays.push(display),
}
}
let mut new_monitors: Vec<Monitor> = Vec::new();
- for native_monitor in new_native_monitors {
+ // Pair unmatched displays with unmatched monitors, or add new ones.
+ for display in unmatched_displays {
if pending_monitors.is_empty() {
- let monitor = add_monitor(native_monitor, state)?;
+ let properties = NativeMonitorProperties::try_from(&display)?;
+ let monitor = add_monitor(display, properties, state)?;
new_monitors.push(monitor);
- Ok(())
} else {
let monitor = pending_monitors.remove(0);
- update_monitor(&monitor, native_monitor, state)
- }?;
+ update_monitor(&monitor, &display, state)?;
+ }
}
- // Remove any monitors that no longer exist and move their workspaces
- // to other monitors.
+ // Remove monitors that no longer have a corresponding display and move
+ // their workspaces to other monitors.
//
// Prevent removal of the last monitor (i.e. for when all monitors are
- // disconnected). This will cause the WM's monitors to mismatch the OS
- // monitor state, however, it'll be updated correctly when a new monitor
- // is connected again.
- for pending_monitor in pending_monitors {
- if state.monitors().len() != 1 {
- remove_monitor(pending_monitor, state, config)?;
+ // disconnected). This will cause the WM's monitors to temporarily
+ // mismatch the OS monitor state, however, it'll be updated correctly
+ // when a new monitor is connected again.
+ for monitor in pending_monitors {
+ if state.monitors().len() > 1 {
+ remove_monitor(monitor, state, config)?;
}
}
@@ -135,8 +86,10 @@ pub fn handle_display_settings_changed(
// Keep the placement if it still intersects the workspace, since
// `PlatformEvent::DisplaySettingsChanged` can be triggered by
// non-monitor changes (e.g. unplugging a USB device).
- !window.floating_placement().has_overlap_x(&workspace_rect)
- || !window.floating_placement().has_overlap_y(&workspace_rect)
+ window
+ .floating_placement()
+ .intersection_area(&workspace_rect)
+ == 0
} else {
true
};
@@ -157,3 +110,53 @@ pub fn handle_display_settings_changed(
Ok(())
}
+
+/// Finds the monitor matching the given display properties.
+///
+/// Returns the monitor and its index within the list of monitors.
+fn find_matching_monitor<'a>(
+ monitors: &'a [Monitor],
+ properties: &NativeMonitorProperties,
+) -> Option<(&'a Monitor, usize)> {
+ monitors.iter().enumerate().find_map(|(index, monitor)| {
+ let existing = monitor.native_properties();
+
+ let is_match = {
+ #[cfg(target_os = "macos")]
+ {
+ existing.device_uuid == properties.device_uuid
+ }
+
+ // On Windows, match the monitor by:
+ // 1. Its handle
+ // 2. Its device path
+ // 3. Its hardware ID (if unique)
+ //
+ // Monitor handles and device paths are unique, but can change over
+ // time. The hardware ID is not guaranteed to be unique, so we
+ // match against that last.
+ #[cfg(target_os = "windows")]
+ {
+ existing.handle == properties.handle
+ || existing.device_path.as_deref().is_some_and(|device_path| {
+ properties.device_path.as_deref() == Some(device_path)
+ })
+ || existing.hardware_id.as_deref().is_some_and(|hardware_id| {
+ let is_unique = monitors
+ .iter()
+ .filter(|other_monitor| {
+ other_monitor.native_properties().hardware_id.as_deref()
+ == Some(hardware_id)
+ })
+ .count()
+ == 1;
+
+ is_unique
+ && properties.hardware_id.as_deref() == Some(hardware_id)
+ })
+ }
+ };
+
+ is_match.then_some((monitor, index))
+ })
+}
diff --git a/packages/wm/src/events/handle_mouse_move.rs b/packages/wm/src/events/handle_mouse_move.rs
index 695adc59..27634686 100644
--- a/packages/wm/src/events/handle_mouse_move.rs
+++ b/packages/wm/src/events/handle_mouse_move.rs
@@ -1,56 +1,128 @@
use anyhow::Context;
-use wm_platform::{MouseMoveEvent, Platform};
+#[cfg(target_os = "macos")]
+use wm_common::try_warn;
+use wm_platform::{MouseButton, MouseEvent};
use crate::{
commands::container::set_focused_descendant, traits::CommonGetters,
user_config::UserConfig, wm_state::WmState,
};
+#[cfg(target_os = "macos")]
+use crate::{
+ events::handle_window_moved_or_resized_end, traits::WindowGetters,
+};
pub fn handle_mouse_move(
- event: &MouseMoveEvent,
+ event: &MouseEvent,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
- // Ignore event if left/right-click is down. Otherwise, this causes focus
- // to jitter when a window is being resized by its drag handles.
- // Also ignore if the OS focused window isn't the same as the WM's
- // focused window.
- if event.is_mouse_down
- || !state.is_focus_synced
- || !config.value.general.focus_follows_cursor
- {
+ // Ignore mouse move events if the WM is paused. The mouse listener
+ // should anyways be disabled when the WM is paused, but this is just in
+ // case any events slipped through while disabling.
+ if state.is_paused {
return Ok(());
}
- let window_under_cursor = Platform::window_from_point(&event.point)
- .and_then(|window| Platform::root_ancestor(&window))
- .map(|root| state.window_from_native(&root))?;
+ // On macOS, detect when a window drag operation has ended by listening
+ // to the release of left click.
+ //
+ // This cannot be used for Windows, since it leads to race conditions
+ // where the mouse event comes in before the `MovedOrResized` event with
+ // `is_interactive_end`. For example, if the user drags to maximize a
+ // window, the WS_MAXIMIZED state is sometimes set after the mouse event.
+ #[cfg(target_os = "macos")]
+ if let MouseEvent::ButtonUp { button, .. } = event {
+ if *button == MouseButton::Left {
+ let active_drag_windows = state
+ .windows()
+ .into_iter()
+ .filter(|window| window.active_drag().is_some());
+
+ // Only one window should ever be actively dragged at a time, but
+ // just in case, iterate over all active drag windows.
+ for window in active_drag_windows {
+ let new_rect = try_warn!(window.native().frame());
- // Set focus to whichever window is currently under the cursor.
- if let Some(window) = window_under_cursor {
- let focused_container =
- state.focused_container().context("No focused container.")?;
+ window.update_native_properties(|properties| {
+ properties.frame = new_rect;
+ });
+
+ handle_window_moved_or_resized_end(&window, state, config)?;
+ }
+ }
+
+ return Ok(());
+ }
- if focused_container.id() != window.id() {
- set_focused_descendant(&window.as_container(), None);
- state.pending_sync.queue_focus_change();
+ if let MouseEvent::Move {
+ pressed_buttons,
+ // LINT: `window_below_cursor` is only used on macOS.
+ #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
+ window_below_cursor,
+ position,
+ ..
+ } = event
+ {
+ // Ignore event if left/right-click is down. Otherwise, this causes
+ // focus to jitter when a window is being resized by its drag
+ // handles. Also ignore if the OS focused window isn't the same as
+ // the WM's focused window.
+ if pressed_buttons.contains(&MouseButton::Left)
+ || pressed_buttons.contains(&MouseButton::Right)
+ || !state.is_focus_synced
+ || !config.value.general.focus_follows_cursor
+ {
+ return Ok(());
}
- } else {
- // Focus the monitor if no window is under the cursor.
- let cursor_monitor = state
- .monitor_at_point(&event.point)
- .context("No monitor under cursor.")?;
-
- let focused_monitor = state
- .focused_container()
- .context("No focused container.")?
- .monitor()
- .context("Focused container has no monitor.")?;
-
- // Avoid setting focus to the same monitor.
- if cursor_monitor.id() != focused_monitor.id() {
- set_focused_descendant(&cursor_monitor.as_container(), None);
- state.pending_sync.queue_focus_change();
+
+ let window_under_cursor = {
+ #[cfg(target_os = "macos")]
+ {
+ window_below_cursor.and_then(|window_id| {
+ use crate::traits::WindowGetters;
+
+ state
+ .windows()
+ .into_iter()
+ .find(|w| w.native().id() == window_id)
+ })
+ }
+ #[cfg(target_os = "windows")]
+ {
+ state
+ .dispatcher
+ .window_from_point(position)?
+ .and_then(|native| state.window_from_native(&native))
+ }
+ };
+
+ // Set focus to whichever window is currently under the cursor.
+ if let Some(window) = window_under_cursor {
+ let focused_container =
+ state.focused_container().context("No focused container.")?;
+
+ if focused_container.id() != window.id() {
+ set_focused_descendant(&window.as_container(), None);
+ state.pending_sync.queue_focus_change();
+ }
+ } else {
+ // Focus the monitor if no window is under the cursor.
+ let cursor_monitor = state
+ .monitor_at_point(position)
+ .context("No monitor under cursor.")?;
+
+ let focused_monitor = state
+ .focused_container()
+ .context("No focused container.")?
+ .monitor()
+ .context("Focused container has no monitor.")?;
+
+ // Avoid setting focus to the same monitor.
+ if cursor_monitor.id() != focused_monitor.id() {
+ set_focused_descendant(&cursor_monitor.as_container(), None);
+ state.pending_sync.queue_focus_change();
+ }
}
}
diff --git a/packages/wm/src/events/handle_window_destroyed.rs b/packages/wm/src/events/handle_window_destroyed.rs
index 9d4abbce..f925bb08 100644
--- a/packages/wm/src/events/handle_window_destroyed.rs
+++ b/packages/wm/src/events/handle_window_destroyed.rs
@@ -1,18 +1,21 @@
use anyhow::Context;
use tracing::info;
-use wm_platform::NativeWindow;
+use wm_platform::WindowId;
use crate::{
commands::{window::unmanage_window, workspace::deactivate_workspace},
- traits::CommonGetters,
+ traits::{CommonGetters, WindowGetters},
wm_state::WmState,
};
pub fn handle_window_destroyed(
- native_window: &NativeWindow,
+ native_window_id: WindowId,
state: &mut WmState,
) -> anyhow::Result<()> {
- let found_window = state.window_from_native(native_window);
+ let found_window = state
+ .windows()
+ .into_iter()
+ .find(|window| window.native().id() == native_window_id);
// Unmanage the window if it's currently managed.
if let Some(window) = found_window {
diff --git a/packages/wm/src/events/handle_window_focused.rs b/packages/wm/src/events/handle_window_focused.rs
index d4410fb1..796f8631 100644
--- a/packages/wm/src/events/handle_window_focused.rs
+++ b/packages/wm/src/events/handle_window_focused.rs
@@ -1,7 +1,7 @@
use anyhow::Context;
use tracing::info;
use wm_common::{DisplayState, WindowRuleEvent, WmEvent};
-use wm_platform::{NativeWindow, Platform};
+use wm_platform::NativeWindow;
use crate::{
commands::{
@@ -27,7 +27,7 @@ pub fn handle_window_focused(
// the WM's focused container, then the focus is not synced.
state.is_focus_synced = match focused_container.as_window_container() {
Ok(window) => *window.native() == *native_window,
- _ => Platform::desktop_window() == *native_window,
+ _ => native_window.is_desktop_window().unwrap_or(false),
};
// Handle overriding focus on close/minimize. After a window is closed
@@ -49,11 +49,11 @@ pub fn handle_window_focused(
}
// Focus effect should be updated for any change in focus that shouldn't
- // be overwritten. Focus here is either:
- // 1. WM's focus container (window).
- // 2. WM's focus container (workspace - i.e. the desktop window).
- // 3. An ignored window.
- // 4. A window that received manual focus.
+ // be overwritten. The incoming focus event at this point is either:
+ // 1. WM's focus container (window or workspace). This is the desktop
+ // window in the case of a workspace.
+ // 2. An ignored window.
+ // 3. A window that received manual focus.
state.pending_sync.queue_focused_effect_update();
if let Some(window) = found_window {
diff --git a/packages/wm/src/events/handle_window_hidden.rs b/packages/wm/src/events/handle_window_hidden.rs
index 2a4ba41e..6c106f25 100644
--- a/packages/wm/src/events/handle_window_hidden.rs
+++ b/packages/wm/src/events/handle_window_hidden.rs
@@ -1,15 +1,16 @@
use tracing::info;
-use wm_common::DisplayState;
+use wm_common::{DisplayState, HideMethod};
use wm_platform::NativeWindow;
use crate::{
commands::window::unmanage_window, traits::WindowGetters,
- wm_state::WmState,
+ user_config::UserConfig, wm_state::WmState,
};
pub fn handle_window_hidden(
native_window: &NativeWindow,
state: &mut WmState,
+ config: &UserConfig,
) -> anyhow::Result<()> {
let found_window = state.window_from_native(native_window);
@@ -17,7 +18,9 @@ pub fn handle_window_hidden(
info!("Window hidden: {window}");
// Update the display state.
- if window.display_state() == DisplayState::Hiding {
+ if config.value.general.hide_method != HideMethod::PlaceInCorner
+ && window.display_state() == DisplayState::Hiding
+ {
window.set_display_state(DisplayState::Hidden);
return Ok(());
}
diff --git a/packages/wm/src/events/handle_window_location_changed.rs b/packages/wm/src/events/handle_window_location_changed.rs
deleted file mode 100644
index bfb2fb2d..00000000
--- a/packages/wm/src/events/handle_window_location_changed.rs
+++ /dev/null
@@ -1,235 +0,0 @@
-use anyhow::Context;
-use tracing::info;
-use wm_common::{
- try_warn, ActiveDrag, ActiveDragOperation, FloatingStateConfig,
- FullscreenStateConfig, Rect, WindowState,
-};
-use wm_platform::NativeWindow;
-
-use crate::{
- commands::{
- container::{flatten_split_container, move_container_within_tree},
- window::update_window_state,
- },
- models::{TilingWindow, WindowContainer},
- traits::{CommonGetters, PositionGetters, WindowGetters},
- user_config::UserConfig,
- wm_state::WmState,
-};
-
-#[allow(clippy::too_many_lines)]
-pub fn handle_window_location_changed(
- native_window: &NativeWindow,
- state: &mut WmState,
- config: &UserConfig,
-) -> anyhow::Result<()> {
- let found_window = state.window_from_native(native_window);
-
- // Update the window's state to be fullscreen or toggled from fullscreen.
- if let Some(window) = found_window {
- let old_frame_position = window.native().frame_position()?;
- let frame_position =
- try_warn!(window.native().refresh_frame_position());
-
- let old_is_maximized = window.native().is_maximized()?;
- let is_maximized = try_warn!(window.native().refresh_is_maximized());
-
- // Ignore duplicate location change events. Window position changes
- // can trigger multiple events (e.g. restore from maximized can trigger
- // as many as 4 identical events).
- if old_frame_position == frame_position
- && old_is_maximized == is_maximized
- {
- return Ok(());
- }
-
- let is_minimized = try_warn!(window.native().refresh_is_minimized());
-
- // Ignore events for minimized windows. Let them be handled by the
- // handler for `PlatformEvent::WindowMinimized` instead.
- if is_minimized {
- return Ok(());
- }
-
- let nearest_monitor = state
- .nearest_monitor(&window.native())
- .context("Failed to get workspace of nearest monitor.")?;
-
- // TODO: Include this as part of the `match` statement below.
- if let Some(tiling_window) = window.as_tiling_window() {
- update_drag_state(
- tiling_window,
- &frame_position,
- &old_frame_position,
- state,
- config,
- )?;
- }
-
- let nearest_workspace = nearest_monitor
- .displayed_workspace()
- .context("No Workspace")?;
-
- let monitor_rect = if config
- .outer_gaps_for_workspace(&nearest_workspace)
- .is_significant()
- {
- nearest_monitor.native().working_rect()?.clone()
- } else {
- nearest_monitor.to_rect()?
- };
-
- let is_fullscreen = window.native().is_fullscreen(&monitor_rect)?;
-
- match window.state() {
- WindowState::Fullscreen(fullscreen_state) => {
- // Restore the window if it's no longer fullscreen *or* for the
- // edge case of fullscreen -> maximized -> restore from maximized.
- if (fullscreen_state.maximized || !is_fullscreen) && !is_maximized
- {
- info!("Window restored from fullscreen: {window}");
-
- update_window_state(
- window.clone(),
- window.toggled_state(window.state(), config),
- state,
- config,
- )?;
- } else if is_maximized && !fullscreen_state.maximized {
- info!("Updating state from fullscreen -> maximized: {window}");
-
- update_window_state(
- window.clone(),
- WindowState::Fullscreen(FullscreenStateConfig {
- maximized: is_maximized,
- ..fullscreen_state
- }),
- state,
- config,
- )?;
- }
- }
- _ => {
- if is_maximized || is_fullscreen {
- info!("Window fullscreened: {window}");
-
- // Update the window to be fullscreen.
- update_window_state(
- window,
- WindowState::Fullscreen(FullscreenStateConfig {
- maximized: is_maximized,
- ..config.value.window_behavior.state_defaults.fullscreen
- }),
- state,
- config,
- )?;
- } else if matches!(window.state(), WindowState::Floating(_)) {
- // Update state with the new location of the floating window.
- info!("Updating floating window position: {window}");
- window.set_floating_placement(frame_position);
- window.set_has_custom_floating_placement(true);
-
- let monitor = window.monitor().context("No monitor.")?;
-
- // Update the window's workspace if it goes out of bounds of its
- // current workspace.
- if monitor.id() != nearest_monitor.id() {
- let updated_workspace = nearest_monitor
- .displayed_workspace()
- .context("Failed to get workspace of nearest monitor.")?;
-
- info!(
- "Floating window moved to new workspace: {updated_workspace}",
- );
-
- if let WindowContainer::NonTilingWindow(window) = &window {
- window.set_insertion_target(None);
- }
-
- move_container_within_tree(
- &window.into(),
- &updated_workspace.clone().into(),
- updated_workspace.child_count(),
- state,
- )?;
- }
- }
- }
- }
- }
-
- Ok(())
-}
-
-/// Updates the window operation based on changes in frame position.
-///
-/// This function determines whether a window is being moved or resized and
-/// updates its operation state accordingly. If the window is being moved,
-/// it's set to floating mode.
-fn update_drag_state(
- window: &TilingWindow,
- frame_position: &Rect,
- old_frame_position: &Rect,
- state: &mut WmState,
- config: &UserConfig,
-) -> anyhow::Result<()> {
- if let Some(active_drag) = window.active_drag() {
- let should_ignore = active_drag.operation.is_some()
- || frame_position == old_frame_position;
-
- if should_ignore {
- return Ok(());
- }
-
- let is_move = frame_position.height() == old_frame_position.height()
- && frame_position.width() == old_frame_position.width();
-
- let operation = if is_move {
- ActiveDragOperation::Moving
- } else {
- ActiveDragOperation::Resizing
- };
-
- window.set_active_drag(Some(ActiveDrag {
- operation: Some(operation),
- ..active_drag
- }));
-
- // Transition window to be floating while it's being dragged.
- if is_move {
- let parent = window.parent().context("No parent")?;
-
- let window = update_window_state(
- window.clone().into(),
- WindowState::Floating(FloatingStateConfig {
- centered: false,
- ..config.value.window_behavior.state_defaults.floating
- }),
- state,
- config,
- )?;
-
- // Windows are added for redraw on state changes, so here we need to
- // remove the window from the pending redraw.
- state
- .pending_sync
- .dequeue_container_from_redraw(window.clone());
-
- // Flatten the parent split container if it only contains the window.
- if let Some(split_parent) = parent.as_split() {
- if split_parent.child_count() == 1 {
- flatten_split_container(split_parent.clone())?;
-
- // Hacky fix to redraw siblings after flattening. The parent is
- // queued for redraw from the state change, which gets detached
- // on flatten.
- state
- .pending_sync
- .queue_containers_to_redraw(window.tiling_siblings());
- }
- }
- }
- }
-
- Ok(())
-}
diff --git a/packages/wm/src/events/handle_window_minimize_ended.rs b/packages/wm/src/events/handle_window_minimize_ended.rs
index 4bd489f2..3315f757 100644
--- a/packages/wm/src/events/handle_window_minimize_ended.rs
+++ b/packages/wm/src/events/handle_window_minimize_ended.rs
@@ -16,7 +16,11 @@ pub fn handle_window_minimize_ended(
// Update the window's state to not be minimized.
if let Some(window) = found_window {
- let is_minimized = try_warn!(window.native().refresh_is_minimized());
+ let is_minimized = try_warn!(window.native().is_minimized());
+
+ window.update_native_properties(|properties| {
+ properties.is_minimized = is_minimized;
+ });
if !is_minimized && window.state() == WindowState::Minimized {
info!("Window minimize ended: {window}");
diff --git a/packages/wm/src/events/handle_window_minimized.rs b/packages/wm/src/events/handle_window_minimized.rs
index e5da0374..4f0303c4 100644
--- a/packages/wm/src/events/handle_window_minimized.rs
+++ b/packages/wm/src/events/handle_window_minimized.rs
@@ -20,7 +20,11 @@ pub fn handle_window_minimized(
// Update the window's state to be minimized.
if let Some(window) = found_window {
- let is_minimized = try_warn!(window.native().refresh_is_minimized());
+ let is_minimized = try_warn!(window.native().is_minimized());
+
+ window.update_native_properties(|properties| {
+ properties.is_minimized = is_minimized;
+ });
if is_minimized && window.state() != WindowState::Minimized {
info!("Window minimized: {window}");
@@ -32,6 +36,12 @@ pub fn handle_window_minimized(
config,
)?;
+ // Clear the drag state, as a window can be minimized while
+ // being dragged (e.g. via `toggle-minimized`).
+ // TODO: Investigate other code paths where the drag state should be
+ // cleared (e.g. most commands that call `update_window_state`).
+ window.set_active_drag(None);
+
// Focus should be reassigned after a window has been minimized.
if let Some(focus_target) = state.focus_target_after_removal(&window)
{
diff --git a/packages/wm/src/events/handle_window_moved_or_resized.rs b/packages/wm/src/events/handle_window_moved_or_resized.rs
new file mode 100644
index 00000000..4e217956
--- /dev/null
+++ b/packages/wm/src/events/handle_window_moved_or_resized.rs
@@ -0,0 +1,496 @@
+use anyhow::Context;
+use wm_common::{
+ try_warn, ActiveDrag, ActiveDragOperation, DisplayState,
+ FloatingStateConfig, FullscreenStateConfig, HideMethod, WindowState,
+};
+#[cfg(target_os = "macos")]
+use wm_platform::{LengthValue, MouseButton, RectDelta};
+use wm_platform::{NativeWindow, Rect};
+
+use crate::{
+ commands::{
+ container::{flatten_split_container, move_container_within_tree},
+ window::update_window_state,
+ },
+ events::handle_window_moved_or_resized_end,
+ models::{Monitor, NonTilingWindow, WindowContainer},
+ traits::{CommonGetters, WindowGetters},
+ user_config::UserConfig,
+ wm_state::WmState,
+};
+
+#[allow(clippy::too_many_lines)]
+pub fn handle_window_moved_or_resized(
+ native_window: &NativeWindow,
+ // LINT: `is_interactive_start` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
+ is_interactive_start: bool,
+ // LINT: `is_interactive_end` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
+ is_interactive_end: bool,
+ state: &mut WmState,
+ config: &UserConfig,
+) -> anyhow::Result<()> {
+ let found_window = state.window_from_native(native_window);
+
+ if let Some(window) = found_window {
+ let old_frame_position = window.native_properties().frame;
+ let frame_position = try_warn!(window.native().frame());
+
+ window.update_native_properties(|properties| {
+ properties.frame = frame_position.clone();
+ });
+
+ // Handle windows that are actively being dragged.
+ if !state.is_paused && window.active_drag().is_some() {
+ let is_drag_end = {
+ // On Windows, the drag operation has ended when
+ // `is_interactive_end` is `true`. This corresponds to a
+ // `EVENT_SYSTEM_MOVESIZEEND` event, which is unavailable on macOS.
+ #[cfg(target_os = "windows")]
+ {
+ is_interactive_end
+ }
+ // On macOS, the drag operation has ended when the mouse button is
+ // no longer down. This is a fallback mechanism since for macOS,
+ // `is_interactive_end` is always `false`. The `MouseEvent` handler
+ // also catches `MouseButtonUp` events, but this provides
+ // additional safety.
+ // TODO: Can probably remove this check and rely 100% on the mouse
+ // event handler.
+ #[cfg(target_os = "macos")]
+ {
+ !state.dispatcher.is_mouse_down(&MouseButton::Left)
+ }
+ };
+
+ if is_drag_end {
+ return handle_window_moved_or_resized_end(&window, state, config);
+ }
+
+ return update_drag_state(&window, &frame_position, state, config);
+ }
+
+ let old_is_maximized = window.native_properties().is_maximized;
+ let is_maximized = try_warn!(window.native().is_maximized());
+
+ // Ignore duplicate move/resize events. Window position changes can
+ // trigger multiple events. For example, restoring from maximized can
+ // trigger as many as 4 identical events on Windows.
+ if old_frame_position == frame_position
+ && old_is_maximized == is_maximized
+ && !is_interactive_start
+ {
+ return Ok(());
+ }
+
+ window.update_native_properties(|properties| {
+ properties.is_maximized = is_maximized;
+ });
+
+ let is_minimized = try_warn!(window.native().is_minimized());
+
+ // Ignore events for minimized windows. Let them be handled by the
+ // `PlatformEvent::WindowMinimized` event handler instead.
+ if is_minimized {
+ return Ok(());
+ }
+
+ // Detect whether the window is starting to be interactively moved or
+ // resized by the user (e.g. via the window's drag handles).
+ let is_drag_start = !state.is_paused && {
+ #[cfg(target_os = "windows")]
+ {
+ // Drag events can be valid for all window states apart from
+ // minimized.
+ is_interactive_start
+ && !matches!(window.state(), WindowState::Minimized)
+ }
+ #[cfg(target_os = "macos")]
+ {
+ // Drag events are never valid for minimized or maximized windows.
+ let is_valid_state = !matches!(
+ window.state(),
+ WindowState::Fullscreen(FullscreenStateConfig {
+ maximized: true,
+ ..
+ }) | WindowState::Minimized
+ );
+
+ let is_dragging_other_window =
+ state.windows().iter().any(|w| w.active_drag().is_some());
+
+ let is_left_click =
+ state.dispatcher.is_mouse_down(&MouseButton::Left);
+
+ // Only consider the window to be dragging if:
+ // 1. The window is not minimized or maximized.
+ // 2. No other window is being dragged.
+ // 3. Left-click is down.
+ // 4. The cursor is within 40px margin around the window's frame.
+ if is_valid_state && !is_dragging_other_window && is_left_click {
+ // The window frame can lag behind the cursor when moving or
+ // resizing quickly, so allow for a bit of leeway.
+ let frame_to_check = frame_position.apply_delta(
+ &RectDelta::new(
+ LengthValue::from_px(40),
+ LengthValue::from_px(40),
+ LengthValue::from_px(40),
+ LengthValue::from_px(40),
+ ),
+ None,
+ );
+
+ // TODO: Might be more robust to also check if the window under
+ // the cursor (i.e. via `dispatcher.window_from_point`) is not a
+ // different window.
+ let cursor_position = state.dispatcher.cursor_position()?;
+ frame_to_check.contains_point(&cursor_position)
+ } else {
+ false
+ }
+ }
+ };
+
+ if is_drag_start {
+ tracing::info!("Window started dragging: {window}");
+
+ window.set_active_drag(Some(ActiveDrag {
+ operation: None,
+ is_from_floating: matches!(
+ window.state(),
+ WindowState::Floating(_)
+ ),
+ #[cfg(target_os = "windows")]
+ initial_position: old_frame_position.clone(),
+ // The updated frame position is used here instead of the initial
+ // frame position due to a quirk on macOS. When we resize an
+ // AXUIElement to a value outside the allowed min/max width &
+ // height, macOS doesn't actually apply that size. However, it
+ // still reports the value we attempted to set until a subsequent
+ // `WindowEvent::MovedOrResized` event.
+ #[cfg(target_os = "macos")]
+ initial_position: frame_position.clone(),
+ }));
+
+ #[cfg(target_os = "windows")]
+ update_drag_state(&window, &frame_position, state, config)?;
+
+ return Ok(());
+ }
+
+ let nearest_monitor = state
+ .nearest_monitor(&window.native())
+ .context("No nearest monitor.")?;
+
+ // For `HideMethod::PlaceInCorner`, hiding/showing is implemented by
+ // repositioning the window. Since the OS won't emit real
+ // shown/hidden events in this mode, update `DisplayState` based on
+ // whether the window has been moved to the monitor's bottom corner.
+ if config.value.general.hide_method == HideMethod::PlaceInCorner {
+ let is_in_corner = is_in_corner(
+ &frame_position,
+ &nearest_monitor.native_properties().working_area,
+ );
+
+ // TODO: Consider redrawing if hidden and should be shown, or if
+ // shown and should be hidden.
+ // TODO: It can be valid for a floating window to be in the corner,
+ // in which case, it currently doesn't get updated to
+ // `DisplayState::Shown`.
+ let display_state = match (window.display_state(), is_in_corner) {
+ (DisplayState::Hiding, true) => DisplayState::Hidden,
+ (DisplayState::Showing, false) => DisplayState::Shown,
+ _ => window.display_state(),
+ };
+
+ if display_state != window.display_state() {
+ window.set_display_state(display_state);
+ return Ok(());
+ }
+ }
+
+ let should_fullscreen = window.should_fullscreen(
+ &nearest_monitor
+ .displayed_workspace()
+ .context("No workspace.")?,
+ )?;
+
+ // Handle a window being maximized or entering fullscreen.
+ if is_maximized || should_fullscreen {
+ let fullscreen_state = if let WindowState::Fullscreen(
+ fullscreen_state,
+ ) = window.state()
+ {
+ fullscreen_state
+ } else {
+ config
+ .value
+ .window_behavior
+ .state_defaults
+ .fullscreen
+ .clone()
+ };
+
+ update_window_state(
+ window.clone(),
+ WindowState::Fullscreen(FullscreenStateConfig {
+ maximized: is_maximized,
+ ..fullscreen_state
+ }),
+ state,
+ config,
+ )?;
+
+ if is_maximized {
+ // Dequeue the window from redraw if it's maximized, since the
+ // window is already in the correct state.
+ state
+ .pending_sync
+ .dequeue_container_from_redraw(window.clone());
+ } else {
+ // Force a redraw to snap the window to the monitor edges.
+ // TODO: Skip redraw if it's already matches fullscreen frame.
+ state.pending_sync.queue_container_to_redraw(window.clone());
+ }
+
+ // TODO: Handle a fullscreen window being moved from one monitor to
+ // another.
+
+ return Ok(());
+ }
+
+ match window.state() {
+ WindowState::Fullscreen(_) => {
+ // Window is no longer maximized/fullscreen and should be restored.
+ tracing::info!("Restoring window from fullscreen: {window}");
+
+ update_window_state(
+ window.clone(),
+ window.toggled_state(window.state(), config),
+ state,
+ config,
+ )?;
+ }
+ WindowState::Floating(_) => {
+ if let WindowContainer::NonTilingWindow(window) = window {
+ update_floating_window_position(
+ &window,
+ frame_position,
+ &nearest_monitor,
+ state,
+ )?;
+ }
+ }
+ _ => {}
+ }
+ }
+
+ Ok(())
+}
+
+// TODO: Move to shared location. `handle_window_moved_or_resized_end.rs`
+// also uses this.
+pub fn update_floating_window_position(
+ window: &NonTilingWindow,
+ frame_position: Rect,
+ nearest_monitor: &Monitor,
+ state: &mut WmState,
+) -> anyhow::Result<()> {
+ tracing::info!(
+ "Updating floating window position: {}",
+ window.as_window_container()?
+ );
+
+ // Update state with the new location of the floating window.
+ window.set_floating_placement(frame_position);
+ window.set_has_custom_floating_placement(true);
+
+ let monitor = window.monitor().context("No monitor.")?;
+
+ // Update the window's workspace if it goes out of bounds of its
+ // current workspace.
+ if monitor.id() != nearest_monitor.id() {
+ let updated_workspace = nearest_monitor
+ .displayed_workspace()
+ .context("Failed to get workspace of nearest monitor.")?;
+
+ tracing::info!(
+ "Floating window moved to new workspace: {updated_workspace}",
+ );
+
+ window.set_insertion_target(None);
+
+ move_container_within_tree(
+ &window.clone().into(),
+ &updated_workspace.clone().into(),
+ updated_workspace.child_count(),
+ state,
+ )?;
+ }
+
+ Ok(())
+}
+
+/// Updates the window operation based on changes in frame position.
+///
+/// This function determines whether a window is being moved or resized and
+/// updates its operation state accordingly. If the window is being moved,
+/// it's set to floating mode.
+fn update_drag_state(
+ window: &WindowContainer,
+ frame_position: &Rect,
+ state: &mut WmState,
+ config: &UserConfig,
+) -> anyhow::Result<()> {
+ let Some(active_drag) = window.active_drag() else {
+ return Ok(());
+ };
+
+ // Ignore if the window position has not changed yet.
+ if *frame_position == active_drag.initial_position {
+ return Ok(());
+ }
+
+ // Determine the drag operation if not already set.
+ let is_move = if let Some(operation) = active_drag.operation {
+ matches!(operation, ActiveDragOperation::Move)
+ } else {
+ let is_move = *frame_position != active_drag.initial_position
+ && frame_position.height() == active_drag.initial_position.height()
+ && frame_position.width() == active_drag.initial_position.width();
+
+ let operation = if is_move {
+ ActiveDragOperation::Move
+ } else {
+ ActiveDragOperation::Resize
+ };
+
+ window.set_active_drag(Some(ActiveDrag {
+ operation: Some(operation),
+ ..active_drag.clone()
+ }));
+
+ is_move
+ };
+
+ // Transition window to be floating while it's being dragged, but only
+ // after it has been moved at least 10px from its initial position. The
+ // 10px threshold is to account for small movements that may be
+ // accidental.
+ if is_move && !matches!(window.state(), WindowState::Floating(_)) {
+ let move_distance = frame_position
+ .center_point()
+ .distance_between(&active_drag.initial_position.center_point());
+
+ // Dragging operations on a maximized window can only occur on Windows.
+ // The OS immediately restores it while it's being dragged, so we need
+ // to update state accordingly without a redraw.
+ let is_maximized = matches!(
+ window.state(),
+ WindowState::Fullscreen(FullscreenStateConfig {
+ maximized: true,
+ ..
+ })
+ );
+
+ if move_distance >= 10.0 || is_maximized {
+ let parent = window.parent().context("No parent")?;
+
+ let is_fullscreen =
+ matches!(window.state(), WindowState::Fullscreen(_))
+ && !is_maximized;
+
+ let window = update_window_state(
+ window.clone(),
+ WindowState::Floating(FloatingStateConfig {
+ centered: false,
+ ..config.value.window_behavior.state_defaults.floating
+ }),
+ state,
+ config,
+ )?;
+
+ // `update_window_state` automatically adds the window for redraw,
+ // which we don't want in this case. However, for fullscreen windows,
+ // we do actually want it to be resized initially so that it's
+ // easier to move around while dragging.
+ if !is_fullscreen {
+ state
+ .pending_sync
+ .dequeue_container_from_redraw(window.clone());
+ }
+
+ // Flatten the parent split container if it only contains the window.
+ // TODO: Consider doing this to `move_container_within_tree`, so that
+ // the behavior is consistent.
+ if let Some(split_parent) = parent.as_split() {
+ if split_parent.child_count() == 1 {
+ flatten_split_container(split_parent.clone())?;
+
+ // Hacky fix to redraw siblings after flattening. The parent is
+ // queued for redraw from the state change, which gets detached
+ // on flatten.
+ // TODO: Change `queue_containers_to_redraw` to iterate over its
+ // descendant windows and store those instead.
+ state
+ .pending_sync
+ .queue_containers_to_redraw(window.tiling_siblings());
+ }
+ }
+ }
+ }
+
+ Ok(())
+}
+
+/// Gets whether the window is in the corner of the monitor.
+fn is_in_corner(window_frame: &Rect, monitor_rect: &Rect) -> bool {
+ // Visible portion of the window used when positioning windows in the
+ // monitor's corner. See `platform_sync` for how hidden windows are
+ // positioned.
+ const VISIBLE_SLIVER_PX: i32 = 1;
+
+ // Allow 1px of leeway.
+ let is_left_corner =
+ (window_frame.right - VISIBLE_SLIVER_PX - monitor_rect.left).abs()
+ <= 1;
+
+ // Allow 1px of leeway.
+ let is_right_corner =
+ (window_frame.x() + VISIBLE_SLIVER_PX - monitor_rect.right).abs() <= 1;
+
+ // On macOS, the window's title bar is prevented from being positioned
+ // outside of monitor's working area, so we need to allow ~50px of
+ // vertical leeway.
+ let is_bottom_of_monitor =
+ (window_frame.y() - monitor_rect.bottom).abs() <= 50;
+
+ (is_left_corner || is_right_corner) && is_bottom_of_monitor
+}
+
+#[cfg(test)]
+mod tests {
+ use wm_platform::Rect;
+
+ use super::is_in_corner;
+
+ #[test]
+ fn matches_corner_positions() {
+ let monitor = Rect::from_xy(0, 0, 1920, 1080);
+
+ let frame_in_right_corner = Rect::from_xy(1919, 1050, 600, 600);
+ assert!(is_in_corner(&frame_in_right_corner, &monitor));
+
+ let frame_in_left_corner = Rect::from_xy(1, 1050, 600, 600);
+ assert!(is_in_corner(&frame_in_left_corner, &monitor));
+ }
+
+ #[test]
+ fn does_not_match_non_corner_positions() {
+ let monitor = Rect::from_xy(0, 0, 1920, 1080);
+ let frame = Rect::from_xy(100, 100, 800, 600);
+
+ assert!(!is_in_corner(&frame, &monitor));
+ }
+}
diff --git a/packages/wm/src/events/handle_window_moved_or_resized_end.rs b/packages/wm/src/events/handle_window_moved_or_resized_end.rs
index 522b503b..f26191be 100644
--- a/packages/wm/src/events/handle_window_moved_or_resized_end.rs
+++ b/packages/wm/src/events/handle_window_moved_or_resized_end.rs
@@ -1,16 +1,15 @@
use anyhow::Context;
-use tracing::info;
use wm_common::{
- try_warn, ActiveDragOperation, LengthValue, Point, Rect,
- TilingDirection, WindowState,
+ try_warn, FullscreenStateConfig, TilingDirection, WindowState,
};
-use wm_platform::{NativeWindow, Platform};
+use wm_platform::{LengthValue, Point, Rect};
use crate::{
commands::{
container::{move_container_within_tree, wrap_in_split_container},
- window::{resize_window, update_window_state},
+ window::{set_window_size, update_window_state},
},
+ events::update_floating_window_position,
models::{
DirectionContainer, NonTilingWindow, SplitContainer, TilingContainer,
WindowContainer,
@@ -27,59 +26,121 @@ use crate::{
///
/// This resizes the window if it's a tiling window and attach a dragged
/// floating window.
+///
+/// TODO: Move this to a better location - maybe a new `active_drag_ext`
+/// mod.
pub fn handle_window_moved_or_resized_end(
- native_window: &NativeWindow,
+ window: &WindowContainer,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
- // Don't update state on resize events if the WM is paused.
- if state.is_paused {
+ let Some(active_drag) = window.active_drag() else {
return Ok(());
- }
-
- let found_window = state.window_from_native(native_window);
-
- if let Some(window) = found_window {
- info!("Window move/resize ended: {window}");
-
- let new_rect = try_warn!(window.native().refresh_frame_position());
- let old_rect = window.to_rect()?;
-
- let width_delta = new_rect.width() - old_rect.width();
- let height_delta = new_rect.height() - old_rect.height();
-
- match &window {
- WindowContainer::NonTilingWindow(window) => {
- if let Some(active_drag) = window.active_drag() {
- if active_drag.is_from_tiling
- && active_drag.operation == Some(ActiveDragOperation::Moving)
- {
- // Window is a temporary floating window that should be
- // reverted back to tiling.
- drop_as_tiling_window(window, state, config)?;
- }
- }
- }
- WindowContainer::TilingWindow(window) => {
- let parent = window.parent().context("No parent.")?;
+ };
+
+ match &window {
+ WindowContainer::NonTilingWindow(window) => {
+ let is_maximized = try_warn!(window.native().is_maximized());
+
+ window.update_native_properties(|properties| {
+ properties.is_maximized = is_maximized;
+ });
+
+ let nearest_monitor = state
+ .nearest_monitor(&window.native())
+ .context("Failed to get workspace of nearest monitor.")?;
+
+ let should_fullscreen = window.should_fullscreen(
+ &nearest_monitor
+ .displayed_workspace()
+ .context("No workspace.")?,
+ )?;
+
+ if is_maximized || should_fullscreen {
+ let fullscreen_state = if let WindowState::Fullscreen(
+ fullscreen_state,
+ ) = window.state()
+ {
+ fullscreen_state
+ } else {
+ config
+ .value
+ .window_behavior
+ .state_defaults
+ .fullscreen
+ .clone()
+ };
+
+ let window = update_window_state(
+ window.clone().into(),
+ WindowState::Fullscreen(FullscreenStateConfig {
+ maximized: is_maximized,
+ ..fullscreen_state
+ }),
+ state,
+ config,
+ )?;
- // Snap window to its original position if it's the only window in
- // the workspace.
- if parent.is_workspace() && window.tiling_siblings().count() == 0 {
+ window.set_active_drag(None);
+
+ if is_maximized {
+ // Dequeue the window from redraw if it's maximized, since the
+ // window is already in the correct state.
+ state
+ .pending_sync
+ .dequeue_container_from_redraw(window.clone());
+ } else {
+ // Force a redraw to snap the window to the monitor edges.
+ // TODO: Skip redraw if it's already matches fullscreen frame.
state.pending_sync.queue_container_to_redraw(window.clone());
- return Ok(());
}
- resize_window(
- &window.clone().into(),
- Some(LengthValue::from_px(width_delta)),
- Some(LengthValue::from_px(height_delta)),
+ return Ok(());
+ }
+
+ if active_drag.is_from_floating {
+ update_floating_window_position(
+ window,
+ window.native_properties().frame,
+ &nearest_monitor,
state,
)?;
+ window.set_active_drag(None);
+ } else {
+ // Window is a temporary floating window that should be
+ // reverted back to tiling.
+ let window = drop_as_tiling_window(window, state, config)?;
+ window.set_active_drag(None);
}
}
-
- window.set_active_drag(None);
+ WindowContainer::TilingWindow(window) => {
+ tracing::info!(
+ "Tiling window move/resize ended: {}",
+ window.as_window_container()?
+ );
+
+ let frame = window.native_properties().frame;
+
+ // Update the window's size based on the new frame position. This
+ // means we use the actual window dimensions as the source of truth.
+ set_window_size(
+ window.clone().into(),
+ Some(LengthValue::from_px(frame.width())),
+ Some(LengthValue::from_px(frame.height())),
+ state,
+ )?;
+
+ window.set_active_drag(None);
+
+ // Force a redraw of the window to snap it back to its original
+ // position. This is necessary when:
+ // - The window is the only tiling window in the workspace.
+ // - The window is not past the movement threshold for transitioning
+ // to floating while being dragged.
+ // - Resizing in a direction that doesn't change the window's tiling
+ // size.
+ state.pending_sync.queue_container_to_redraw(window.clone());
+ }
}
Ok(())
@@ -92,13 +153,13 @@ fn drop_as_tiling_window(
moved_window: &NonTilingWindow,
state: &mut WmState,
config: &UserConfig,
-) -> anyhow::Result<()> {
- info!(
+) -> anyhow::Result<WindowContainer> {
+ tracing::info!(
"Tiling window drag ended: {}",
moved_window.as_window_container()?
);
- let mouse_pos = Platform::mouse_position()?;
+ let mouse_pos = state.dispatcher.cursor_position()?;
let mouse_workspace = state
.monitor_at_point(&mouse_pos)
.and_then(|monitor| monitor.displayed_workspace())
@@ -141,8 +202,6 @@ fn drop_as_tiling_window(
state,
config,
)?;
-
- return Ok(());
}
let nearest_container = target_parent
@@ -222,7 +281,7 @@ fn drop_as_tiling_window(
state.pending_sync.queue_container_to_redraw(target_parent);
- Ok(())
+ Ok(moved_window)
}
/// Represents where the window was dropped over another.
diff --git a/packages/wm/src/events/handle_window_moved_or_resized_start.rs b/packages/wm/src/events/handle_window_moved_or_resized_start.rs
deleted file mode 100644
index ef8ee2dc..00000000
--- a/packages/wm/src/events/handle_window_moved_or_resized_start.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-use wm_common::ActiveDrag;
-use wm_platform::NativeWindow;
-
-use crate::{traits::WindowGetters, wm_state::WmState};
-
-/// Handles the event for when a window is started being moved or resized
-/// by the user (e.g. via the window's drag handles).
-pub fn handle_window_moved_or_resized_start(
- native_window: &NativeWindow,
- state: &mut WmState,
-) {
- // Don't update state on resize events if the WM is paused.
- if state.is_paused {
- return;
- }
-
- let found_window = state.window_from_native(native_window);
-
- if let Some(found_window) = found_window {
- found_window.set_active_drag(Some(ActiveDrag {
- operation: None,
- is_from_tiling: found_window.is_tiling_window(),
- }));
- }
-}
diff --git a/packages/wm/src/events/handle_window_shown.rs b/packages/wm/src/events/handle_window_shown.rs
index 5523edb6..07383aba 100644
--- a/packages/wm/src/events/handle_window_shown.rs
+++ b/packages/wm/src/events/handle_window_shown.rs
@@ -1,5 +1,5 @@
use tracing::info;
-use wm_common::DisplayState;
+use wm_common::{DisplayState, HideMethod};
use wm_platform::NativeWindow;
use crate::{
@@ -14,23 +14,20 @@ pub fn handle_window_shown(
) -> anyhow::Result<()> {
let found_window = state.window_from_native(&native_window);
- match found_window {
- Some(window) => {
- info!("Window shown: {window}");
+ if let Some(window) = found_window {
+ info!("Window shown: {window}");
- // Update display state if window is already managed.
- if window.display_state() == DisplayState::Showing {
- window.set_display_state(DisplayState::Shown);
- } else {
- state.pending_sync.queue_container_to_redraw(window);
- }
- }
- None => {
- // If the window is not managed, manage it.
- if native_window.is_manageable().unwrap_or(false) {
- manage_window(native_window, None, state, config)?;
- }
+ // Update display state if window is already managed.
+ if config.value.general.hide_method != HideMethod::PlaceInCorner
+ && window.display_state() == DisplayState::Showing
+ {
+ window.set_display_state(DisplayState::Shown);
+ } else {
+ state.pending_sync.queue_container_to_redraw(window);
}
+ } else {
+ // If the window is not managed, manage it.
+ manage_window(native_window, None, state, config)?;
}
Ok(())
diff --git a/packages/wm/src/events/handle_window_title_changed.rs b/packages/wm/src/events/handle_window_title_changed.rs
index 9dbe36b7..85e513d1 100644
--- a/packages/wm/src/events/handle_window_title_changed.rs
+++ b/packages/wm/src/events/handle_window_title_changed.rs
@@ -17,7 +17,11 @@ pub fn handle_window_title_changed(
if let Some(window) = found_window {
info!("Window title changed: {window}");
- try_warn!(window.native().refresh_title());
+ let title = try_warn!(window.native().title());
+
+ window.update_native_properties(|properties| {
+ properties.title = title;
+ });
// Run window rules for title change events.
run_window_rules(
diff --git a/packages/wm/src/events/mod.rs b/packages/wm/src/events/mod.rs
index 0019a0f6..b4e1ad6b 100644
--- a/packages/wm/src/events/mod.rs
+++ b/packages/wm/src/events/mod.rs
@@ -3,11 +3,10 @@ mod handle_mouse_move;
mod handle_window_destroyed;
mod handle_window_focused;
mod handle_window_hidden;
-mod handle_window_location_changed;
mod handle_window_minimize_ended;
mod handle_window_minimized;
+mod handle_window_moved_or_resized;
mod handle_window_moved_or_resized_end;
-mod handle_window_moved_or_resized_start;
mod handle_window_shown;
mod handle_window_title_changed;
@@ -16,10 +15,9 @@ pub use handle_mouse_move::*;
pub use handle_window_destroyed::*;
pub use handle_window_focused::*;
pub use handle_window_hidden::*;
-pub use handle_window_location_changed::*;
pub use handle_window_minimize_ended::*;
pub use handle_window_minimized::*;
+pub use handle_window_moved_or_resized::*;
pub use handle_window_moved_or_resized_end::*;
-pub use handle_window_moved_or_resized_start::*;
pub use handle_window_shown::*;
pub use handle_window_title_changed::*;
diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rs
index 36216ff3..2b3f7541 100644
--- a/packages/wm/src/main.rs
+++ b/packages/wm/src/main.rs
@@ -9,21 +9,27 @@
#![warn(clippy::all, clippy::pedantic)]
#![feature(iterator_try_collect)]
-use std::{env, path::PathBuf, time::Duration};
+use std::{env, path::PathBuf, process, time::Duration};
use anyhow::{Context, Error};
-use tokio::{process::Command, signal, time};
-use tracing::{debug, error, info, warn, Level};
+use tokio::{process::Command, signal};
+use tracing::Level;
use tracing_subscriber::{
fmt::{self, writer::MakeWriterExt},
layer::SubscriberExt,
};
use wm_common::{AppCommand, InvokeCommand, Verbosity, WmEvent};
-use wm_platform::Platform;
+#[cfg(target_os = "macos")]
+use wm_platform::DispatcherExtMacOs;
+use wm_platform::{
+ Dispatcher, DisplayListener, EventLoop, KeybindingListener,
+ MouseEventKind, MouseListener, PlatformEvent, SingleInstance,
+ WindowListener,
+};
use crate::{
ipc_server::IpcServer, sys_tray::SystemTray, user_config::UserConfig,
- wm::WindowManager, wm_state::WINDOW_CLEANUP_INTERVAL_SECS,
+ wm::WindowManager,
};
mod commands;
@@ -41,96 +47,168 @@ mod wm_state;
///
/// Conditionally starts the WM or runs a CLI command based on the given
/// subcommand.
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
+fn main() -> anyhow::Result<()> {
let args = std::env::args().collect::<Vec<_>>();
let app_command = AppCommand::parse_with_default(&args);
- match app_command {
- AppCommand::Start {
- config_path,
- verbosity,
- } => {
- let res = start_wm(config_path, verbosity).await;
-
- // If unable to start the WM, the error is fatal and a message dialog
- // is shown.
- if let Err(err) = &res {
- error!("{:?}", err);
- Platform::show_error_dialog("Fatal error", &err.to_string());
- }
+ if let AppCommand::Start {
+ config_path,
+ verbosity,
+ } = app_command
+ {
+ let rt = tokio::runtime::Runtime::new()?;
+ let (event_loop, dispatcher) = EventLoop::new()?;
+
+ let task_handle = std::thread::spawn(move || {
+ rt.block_on(async {
+ let start_res =
+ start_wm(config_path, verbosity, &dispatcher).await;
+
+ if let Err(err) = &start_res {
+ // If unable to start the WM, the error is fatal and a message
+ // dialog is shown.
+ tracing::error!("{:?}", err);
+ dispatcher.show_error_dialog("Fatal error", &err.to_string());
+ }
- res
- }
- _ => wm_cli::start(args).await,
+ if let Err(err) = dispatcher.stop_event_loop() {
+ // Forcefully exit the process to ensure the event loop is
+ // stopped.
+ tracing::error!("Failed to stop event loop gracefully: {}", err);
+ process::exit(1);
+ }
+
+ start_res
+ })
+ });
+
+ // Run event loop (blocks until shutdown). This must be on the main
+ // thread for macOS compatibility.
+ event_loop.run()?;
+
+ // Wait for clean exit of the WM.
+ task_handle.join().unwrap()
+ } else {
+ let rt = tokio::runtime::Runtime::new()?;
+ rt.block_on(wm_cli::start(args))
}
}
+#[allow(clippy::too_many_lines)]
async fn start_wm(
config_path: Option<PathBuf>,
verbosity: Verbosity,
+ dispatcher: &Dispatcher,
) -> anyhow::Result<()> {
setup_logging(&verbosity)?;
// Ensure that only one instance of the WM is running.
- let _single_instance = Platform::new_single_instance()?;
+ let _single_instance = SingleInstance::new()?;
+
+ #[cfg(target_os = "macos")]
+ {
+ if !dispatcher.has_ax_permission(true) {
+ anyhow::bail!(
+ "Accessibility permissions are not granted. In System Preferences, \
+ go to Privacy & Security > Accessibility and enable GlazeWM."
+ );
+ }
+ }
// Parse and validate user config.
let mut config = UserConfig::new(config_path)?;
- // Start watcher process for restoring hidden windows on crash.
- start_watcher_process()?;
-
// Add application icon to system tray.
- let mut tray = SystemTray::new(&config.path)?;
+ let mut tray = SystemTray::new(&config.path, dispatcher.clone())?;
- let mut wm = WindowManager::new(&mut config)?;
+ let mut wm = WindowManager::new(&mut config, dispatcher.clone())?;
let mut ipc_server = IpcServer::start().await?;
- // Start listening for platform events after populating initial state.
- let mut event_listener = Platform::start_event_listener(&config.value)?;
-
- // Run startup commands.
- let startup_commands = config.value.general.startup_commands.clone();
- wm.process_commands(&startup_commands, None, &mut config)?;
+ // Start watcher process for restoring hidden windows on crash.
+ // Windows-only, since macOS' hidden windows remain accessible.
+ #[cfg(target_os = "windows")]
+ if let Err(err) = start_watcher_process() {
+ tracing::warn!(
+ "Failed to start watcher process: {err}{}",
+ cfg!(debug_assertions)
+ .then_some(".\n Run `cargo build -p wm-watcher` to build it.")
+ .unwrap_or_default()
+ );
+ }
- // Create an interval for cleaning up invalid/ghost windows.
- let mut cleanup_interval = time::interval(Duration::from_secs(WINDOW_CLEANUP_INTERVAL_SECS));
+ // Start listening for platform events after populating initial state.
+ let mut window_listener = WindowListener::new(dispatcher)?;
+ let mut display_listener = DisplayListener::new(dispatcher)?;
+ let mut mouse_listener = MouseListener::new(
+ if config.value.general.focus_follows_cursor {
+ &[MouseEventKind::Move, MouseEventKind::LeftButtonUp]
+ } else {
+ &[MouseEventKind::LeftButtonUp]
+ },
+ dispatcher,
+ )?;
+ let mut keybinding_listener = KeybindingListener::new(
+ &config
+ .active_keybinding_configs(&[], false)
+ .flat_map(|kb| kb.bindings)
+ .collect::<Vec<_>>(),
+ dispatcher,
+ )?;
+
+ // Run user's startup commands.
+ wm.process_commands(
+ &config.value.general.startup_commands.clone(),
+ None,
+ &mut config,
+ )?;
+
+ // Create an interval for periodically cleaning up invalid windows.
+ let mut cleanup_interval = tokio::time::interval(Duration::from_secs(5));
loop {
let res = tokio::select! {
- Some(()) = tray.exit_rx.recv() => {
- info!("Exiting through system tray.");
+ _ = signal::ctrl_c() => {
+ tracing::info!("Received SIGINT signal.");
break;
},
Some(()) = wm.exit_rx.recv() => {
- info!("Exiting through WM command.");
+ tracing::info!("Exiting through WM command.");
break;
},
- _ = signal::ctrl_c() => {
- info!("Received SIGINT signal.");
+ Some(()) = tray.exit_rx.recv() => {
+ tracing::info!("Exiting through system tray.");
break;
},
+ Some(event) = mouse_listener.next_event() => {
+ tracing::debug!("Received mouse event: {:?}", event);
+ wm.process_event(PlatformEvent::Mouse(event), &mut config)
+ },
+ Some(event) = window_listener.next_event() => {
+ tracing::debug!("Received window event: {:?}", event);
+ wm.process_event(PlatformEvent::Window(event), &mut config)
+ },
+ Some(()) = display_listener.next_event() => {
+ tracing::debug!("Received display settings changed event.");
+ wm.process_event(PlatformEvent::DisplaySettingsChanged, &mut config)
+ },
+ Some(event) = keybinding_listener.next_event() => {
+ tracing::debug!("Received keyboard event: {:?}", event);
+ wm.process_event(PlatformEvent::Keybinding(event), &mut config)
+ }
_ = cleanup_interval.tick() => {
- // Clean up invalid/ghost windows periodically.
- if !wm.state.is_paused {
- if let Err(err) = wm.state.cleanup_invalid_windows() {
- warn!("Failed to clean up invalid windows: {}", err);
- }
+ if wm.state.is_paused {
+ Ok(())
+ } else {
+ wm.state.cleanup_invalid_windows()
}
- Ok(())
- },
- Some(event) = event_listener.event_rx.recv() => {
- debug!("Received platform event: {:?}", event);
- wm.process_event(event, &mut config)
},
Some((
message,
response_tx,
disconnection_tx
)) = ipc_server.message_rx.recv() => {
- info!("Received IPC message: {:?}", message);
+ tracing::info!("Received IPC message: {:?}", message);
if let Err(err) = ipc_server.process_message(
message,
@@ -139,31 +217,44 @@ async fn start_wm(
&mut wm,
&mut config,
) {
- error!("{:?}", err);
+ tracing::error!("{:?}", err);
}
Ok(())
},
Some(wm_event) = wm.event_rx.recv() => {
- debug!("Received WM event: {:?}", wm_event);
+ tracing::debug!("Received WM event: {:?}", wm_event);
- // Update event listener when keyboard or mouse listener needs to
- // be changed.
+ // Disable mouse and keybinding listeners when the WM is paused.
+ if let WmEvent::PauseChanged { is_paused } = wm_event {
+ let _ = mouse_listener.enable(!is_paused);
+ keybinding_listener.enable(!is_paused);
+ }
+
+ // Update keybinding and mouse listeners on config changes.
if matches!(
wm_event,
WmEvent::UserConfigChanged { .. }
| WmEvent::BindingModesChanged { .. }
- | WmEvent::PauseChanged { .. }
) {
- event_listener.update(
- &config.value,
- &wm.state.binding_modes,
- wm.state.is_paused,
+ keybinding_listener.update(
+ &config
+ .active_keybinding_configs(&wm.state.binding_modes, false)
+ .flat_map(|kb| kb.bindings)
+ .collect::<Vec<_>>(),
);
+
+ mouse_listener.set_enabled_events(
+ if config.value.general.focus_follows_cursor {
+ &[MouseEventKind::Move, MouseEventKind::LeftButtonUp]
+ } else {
+ &[MouseEventKind::LeftButtonUp]
+ },
+ )?;
}
if let Err(err) = ipc_server.process_event(wm_event) {
- error!("{:?}", err);
+ tracing::error!("{:?}", err);
}
Ok(())
@@ -178,12 +269,15 @@ async fn start_wm(
};
if let Err(err) = res {
- error!("{:?}", err);
- Platform::show_error_dialog("Non-fatal error", &err.to_string());
+ tracing::error!("{:?}", err);
+ dispatcher.show_error_dialog("Non-fatal error", &err.to_string());
}
}
- run_cleanup(&mut wm, &mut config, &mut ipc_server)
+ tracing::info!("Window manager shutting down.");
+ wm.cleanup(&mut config, &mut ipc_server);
+
+ Ok(())
}
/// Initialize logging with the specified verbosity level.
@@ -211,7 +305,7 @@ fn setup_logging(verbosity: &Verbosity) -> anyhow::Result<()> {
tracing::subscriber::set_global_default(subscriber)?;
- info!(
+ tracing::info!(
"Starting WM with log level {:?}.",
verbosity.level().to_string()
);
@@ -219,11 +313,13 @@ fn setup_logging(verbosity: &Verbosity) -> anyhow::Result<()> {
Ok(())
}
-/// Launches watcher binary. This is a separate process that is responsible
-/// for restoring hidden windows in case the main WM process crashes.
+/// Launches watcher binary (Windows-only). This is a separate process that
+/// is responsible for restoring hidden windows in case the main WM process
+/// crashes.
///
-/// This assumes the watcher binary exists in the same directory as the WM
-/// binary.
+/// This assumes the watcher binary exists in the same directory as the
+/// WM binary.
+#[allow(unused)]
fn start_watcher_process() -> anyhow::Result<tokio::process::Child, Error>
{
let watcher_path = env::current_exe()?
@@ -235,31 +331,3 @@ fn start_watcher_process() -> anyhow::Result<tokio::process::Child, Error>
.spawn()
.context("Failed to start watcher process.")
}
-
-/// Runs cleanup tasks when the WM is exiting.
-fn run_cleanup(
- wm: &mut WindowManager,
- config: &mut UserConfig,
- ipc_server: &mut IpcServer,
-) -> anyhow::Result<()> {
- // Ensure that the WM is unpaused, otherwise, shutdown commands won't get
- // executed.
- wm.state.is_paused = false;
-
- // Run shutdown commands.
- let shutdown_commands = config.value.general.shutdown_commands.clone();
- wm.process_commands(&shutdown_commands, None, config)?;
-
- wm.state.emit_event(WmEvent::ApplicationExiting);
-
- // Emit remaining WM events before exiting.
- while let Ok(wm_event) = wm.event_rx.try_recv() {
- info!("Emitting WM event before shutting down: {:?}", wm_event);
-
- if let Err(err) = ipc_server.process_event(wm_event) {
- warn!("{:?}", err);
- }
- }
-
- Ok(())
-}
diff --git a/packages/wm/src/models/container.rs b/packages/wm/src/models/container.rs
index 086e623c..449e96e6 100644
--- a/packages/wm/src/models/container.rs
+++ b/packages/wm/src/models/container.rs
@@ -7,16 +7,16 @@ use ambassador::Delegate;
use enum_as_inner::EnumAsInner;
use uuid::Uuid;
use wm_common::{
- ActiveDrag, ContainerDto, Direction, DisplayState, GapsConfig, Rect,
- RectDelta, TilingDirection, WindowRuleConfig, WindowState,
+ ActiveDrag, ContainerDto, DisplayState, GapsConfig, TilingDirection,
+ WindowRuleConfig, WindowState,
};
-use wm_platform::NativeWindow;
+use wm_platform::{Direction, NativeWindow, Rect, RectDelta};
#[allow(clippy::wildcard_imports)]
use crate::{
models::{
- Monitor, NonTilingWindow, RootContainer, SplitContainer, TilingWindow,
- Workspace,
+ Monitor, NativeWindowProperties, NonTilingWindow, RootContainer,
+ SplitContainer, TilingWindow, Workspace,
},
traits::*,
user_config::UserConfig,
@@ -51,7 +51,7 @@ use crate::{
/// let direction: DirectionContainer = tiling.try_into().unwrap(); // Will be a `DirectionContainer::Split`
/// direction.tiling_direction(); // Can use methods from the `TilingDirectionGetters` trait.
///
-/// // Covert a sub container back into a [Container]
+/// // Convert a sub container back into a [Container]
/// let container: Container = direction.into(); // Will be a `Container::Split`
/// }
/// ```
@@ -131,24 +131,40 @@ impl Eq for WindowContainer {}
impl std::fmt::Display for WindowContainer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let native = self.native();
- let title = native.title().unwrap_or_default();
- let class = native.class_name().unwrap_or_default();
- let process = native.process_name().unwrap_or_default();
-
// Truncate title if longer than 20 chars. Need to use `chars()`
// instead of byte slices to handle invalid byte indices.
- let title = if title.len() > 20 {
- format!("{}...", &title.chars().take(17).collect::<String>())
- } else {
- title
+ let title = {
+ let title = self.native_properties().title;
+ if title.len() > 20 {
+ format!("{}...", title.chars().take(17).collect::<String>())
+ } else {
+ title
+ }
+ };
+
+ let class = {
+ #[cfg(target_os = "windows")]
+ {
+ self.native_properties().class_name
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ String::new()
+ }
};
+ let process = self.native_properties().process_name;
+
write!(
f,
- "Window(hwnd={}, process={}, class={}, title={})",
- native.handle, process, class, title,
- )
+ "Window(id={:?}, process={}, class={}, title={})",
+ self.native().id(),
+ process,
+ class,
+ title,
+ )?;
+
+ Ok(())
}
}
diff --git a/packages/wm/src/models/mod.rs b/packages/wm/src/models/mod.rs
index 58464c2d..dc934287 100644
--- a/packages/wm/src/models/mod.rs
+++ b/packages/wm/src/models/mod.rs
@@ -1,6 +1,8 @@
mod container;
mod insertion_target;
mod monitor;
+mod native_monitor_properties;
+mod native_window_properties;
mod non_tiling_window;
mod root_container;
mod split_container;
@@ -11,6 +13,8 @@ mod workspace_target;
pub use container::*;
pub use insertion_target::*;
pub use monitor::*;
+pub use native_monitor_properties::*;
+pub use native_window_properties::*;
pub use non_tiling_window::*;
pub use root_container::*;
pub use split_container::*;
diff --git a/packages/wm/src/models/monitor.rs b/packages/wm/src/models/monitor.rs
index 67c7f5b6..a2ea7362 100644
--- a/packages/wm/src/models/monitor.rs
+++ b/packages/wm/src/models/monitor.rs
@@ -6,14 +6,14 @@ use std::{
use anyhow::Context;
use uuid::Uuid;
-use wm_common::{ContainerDto, MonitorDto, Rect};
-use wm_platform::NativeMonitor;
+use wm_common::{ContainerDto, MonitorDto};
+use wm_platform::{Display, Rect};
use crate::{
impl_common_getters, impl_container_debug,
models::{
- Container, DirectionContainer, TilingContainer, WindowContainer,
- Workspace,
+ Container, DirectionContainer, NativeMonitorProperties,
+ TilingContainer, WindowContainer, Workspace,
},
traits::{CommonGetters, PositionGetters},
};
@@ -26,30 +26,46 @@ struct MonitorInner {
parent: Option<Container>,
children: VecDeque<Container>,
child_focus_order: VecDeque<Uuid>,
- native: NativeMonitor,
+ native: Display,
+ native_properties: NativeMonitorProperties,
}
impl Monitor {
- pub fn new(native_monitor: NativeMonitor) -> Self {
+ pub fn new(
+ native_display: Display,
+ native_properties: NativeMonitorProperties,
+ ) -> Self {
let monitor = MonitorInner {
id: Uuid::new_v4(),
parent: None,
children: VecDeque::new(),
child_focus_order: VecDeque::new(),
- native: native_monitor,
+ native: native_display,
+ native_properties,
};
Self(Rc::new(RefCell::new(monitor)))
}
- pub fn native(&self) -> NativeMonitor {
+ pub fn native(&self) -> Display {
self.0.borrow().native.clone()
}
- pub fn set_native(&self, native: NativeMonitor) {
+ pub fn set_native(&self, native: Display) {
self.0.borrow_mut().native = native;
}
+ pub fn native_properties(&self) -> NativeMonitorProperties {
+ self.0.borrow().native_properties.clone()
+ }
+
+ pub fn set_native_properties(
+ &self,
+ native_properties: NativeMonitorProperties,
+ ) {
+ self.0.borrow_mut().native_properties = native_properties;
+ }
+
pub fn displayed_workspace(&self) -> Option<Workspace> {
self
.child_focus_order()
@@ -71,11 +87,11 @@ impl Monitor {
&self,
other: &Container,
) -> anyhow::Result<bool> {
- let dpi = self.native().dpi()?;
+ let dpi = self.native_properties().dpi;
let other_dpi = other
.monitor()
- .and_then(|monitor| monitor.native().dpi().ok())
+ .map(|monitor| monitor.native_properties().dpi)
.context("Failed to get DPI of other monitor.")?;
Ok(dpi != other_dpi)
@@ -99,13 +115,22 @@ impl Monitor {
height: rect.height(),
x: rect.x(),
y: rect.y(),
- dpi: self.native().dpi()?,
- scale_factor: self.native().scale_factor()?,
- handle: self.native().handle,
- device_name: self.native().device_name()?.clone(),
- device_path: self.native().device_path()?.cloned(),
- hardware_id: self.native().hardware_id()?.cloned(),
- working_rect: self.native().working_rect()?.clone(),
+ dpi: self.native_properties().dpi,
+ scale_factor: self.native_properties().scale_factor,
+ #[cfg(target_os = "windows")]
+ handle: Some(self.native_properties().handle),
+ #[cfg(not(target_os = "windows"))]
+ handle: None,
+ device_name: self.native_properties().device_name,
+ #[cfg(target_os = "windows")]
+ device_path: self.native_properties().device_path,
+ #[cfg(not(target_os = "windows"))]
+ device_path: None,
+ #[cfg(target_os = "windows")]
+ hardware_id: self.native_properties().hardware_id,
+ #[cfg(not(target_os = "windows"))]
+ hardware_id: None,
+ working_rect: self.native_properties().working_area,
}))
}
}
@@ -115,23 +140,16 @@ impl_common_getters!(Monitor);
impl PositionGetters for Monitor {
fn to_rect(&self) -> anyhow::Result<Rect> {
- self.0.borrow().native.rect().cloned()
+ Ok(self.0.borrow().native_properties.bounds.clone())
}
}
impl std::fmt::Display for Monitor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let native = self.native();
- let device_name = native
- .device_name()
- .map_or_else(|_| "Unknown".to_string(), String::to_string);
- let device_path = native.device_path().unwrap_or_default();
- let hardware_id = native.hardware_id().unwrap_or_default();
-
write!(
f,
- "Monitor(handle={}, device_name={}, device_path={:?}, hardware_id={:?})",
- native.handle, device_name, device_path, hardware_id,
+ "Monitor(device_name={})",
+ self.native_properties().device_name,
)
}
}
diff --git a/packages/wm/src/models/native_monitor_properties.rs b/packages/wm/src/models/native_monitor_properties.rs
new file mode 100644
index 00000000..46a06bc2
--- /dev/null
+++ b/packages/wm/src/models/native_monitor_properties.rs
@@ -0,0 +1,42 @@
+use wm_platform::{Display, Rect};
+#[cfg(target_os = "windows")]
+use wm_platform::{DisplayDeviceExtWindows, DisplayExtWindows};
+
+#[derive(Debug, Clone)]
+pub struct NativeMonitorProperties {
+ #[cfg(target_os = "macos")]
+ pub device_uuid: String,
+ #[cfg(target_os = "windows")]
+ pub handle: isize,
+ #[cfg(target_os = "windows")]
+ pub hardware_id: Option<String>,
+ #[cfg(target_os = "windows")]
+ pub device_path: Option<String>,
+ pub device_name: String,
+ pub working_area: Rect,
+ pub bounds: Rect,
+ pub dpi: u32,
+ pub scale_factor: f32,
+}
+
+impl NativeMonitorProperties {
+ pub fn try_from(native_display: &Display) -> anyhow::Result<Self> {
+ let display_device = native_display.main_device()?;
+
+ Ok(Self {
+ #[cfg(target_os = "macos")]
+ device_uuid: display_device.id().0,
+ #[cfg(target_os = "windows")]
+ handle: native_display.hmonitor().0,
+ #[cfg(target_os = "windows")]
+ hardware_id: display_device.hardware_id(),
+ #[cfg(target_os = "windows")]
+ device_path: display_device.device_path(),
+ device_name: native_display.name()?,
+ working_area: native_display.working_area()?,
+ bounds: native_display.bounds()?,
+ dpi: native_display.dpi()?,
+ scale_factor: native_display.scale_factor()?,
+ })
+ }
+}
diff --git a/packages/wm/src/models/native_window_properties.rs b/packages/wm/src/models/native_window_properties.rs
new file mode 100644
index 00000000..fc870b45
--- /dev/null
+++ b/packages/wm/src/models/native_window_properties.rs
@@ -0,0 +1,32 @@
+#[cfg(target_os = "windows")]
+use wm_platform::NativeWindowWindowsExt;
+use wm_platform::{NativeWindow, Rect};
+
+#[derive(Debug, Clone)]
+pub struct NativeWindowProperties {
+ pub title: String,
+ #[cfg(target_os = "windows")]
+ pub class_name: String,
+ pub process_name: String,
+ pub frame: Rect,
+ pub is_minimized: bool,
+ pub is_maximized: bool,
+ pub is_resizable: bool,
+}
+
+impl TryFrom<&NativeWindow> for NativeWindowProperties {
+ type Error = anyhow::Error;
+
+ fn try_from(native_window: &NativeWindow) -> Result<Self, Self::Error> {
+ Ok(Self {
+ title: native_window.title()?,
+ #[cfg(target_os = "windows")]
+ class_name: native_window.class_name()?,
+ process_name: native_window.process_name()?,
+ frame: native_window.frame()?,
+ is_minimized: native_window.is_minimized()?,
+ is_maximized: native_window.is_maximized()?,
+ is_resizable: native_window.is_resizable()?,
+ })
+ }
+}
diff --git a/packages/wm/src/models/non_tiling_window.rs b/packages/wm/src/models/non_tiling_window.rs
index c4c3cbcd..4cde5e9d 100644
--- a/packages/wm/src/models/non_tiling_window.rs
+++ b/packages/wm/src/models/non_tiling_window.rs
@@ -7,16 +7,17 @@ use std::{
use anyhow::Context;
use uuid::Uuid;
use wm_common::{
- ActiveDrag, ContainerDto, DisplayState, GapsConfig, Rect, RectDelta,
- WindowDto, WindowRuleConfig, WindowState,
+ ActiveDrag, ContainerDto, DisplayState, GapsConfig, WindowDto,
+ WindowRuleConfig, WindowState,
};
-use wm_platform::NativeWindow;
+use wm_platform::{NativeWindow, Rect, RectDelta};
use crate::{
impl_common_getters, impl_container_debug, impl_window_getters,
models::{
- Container, DirectionContainer, InsertionTarget, TilingContainer,
- TilingWindow, WindowContainer,
+ Container, DirectionContainer, InsertionTarget,
+ NativeWindowProperties, TilingContainer, TilingWindow,
+ WindowContainer,
},
traits::{CommonGetters, PositionGetters, WindowGetters},
};
@@ -30,6 +31,7 @@ struct NonTilingWindowInner {
children: VecDeque<Container>,
child_focus_order: VecDeque<Uuid>,
native: NativeWindow,
+ native_properties: NativeWindowProperties,
state: WindowState,
prev_state: Option<WindowState>,
insertion_target: Option<InsertionTarget>,
@@ -47,6 +49,7 @@ impl NonTilingWindow {
pub fn new(
id: Option<Uuid>,
native: NativeWindow,
+ properties: NativeWindowProperties,
state: WindowState,
prev_state: Option<WindowState>,
border_delta: RectDelta,
@@ -62,6 +65,7 @@ impl NonTilingWindow {
children: VecDeque::new(),
child_focus_order: VecDeque::new(),
native,
+ native_properties: properties,
state,
prev_state,
insertion_target,
@@ -89,10 +93,17 @@ impl NonTilingWindow {
}
pub fn to_tiling(&self, gaps_config: GapsConfig) -> TilingWindow {
+ let prev_state = if self.active_drag().is_some() {
+ self.prev_state()
+ } else {
+ Some(self.state())
+ };
+
TilingWindow::new(
Some(self.id()),
self.native().clone(),
- Some(self.state()),
+ self.native_properties().clone(),
+ prev_state,
self.border_delta(),
self.floating_placement(),
self.has_custom_floating_placement(),
@@ -119,10 +130,12 @@ impl NonTilingWindow {
display_state: self.display_state(),
border_delta: self.border_delta(),
floating_placement: self.floating_placement(),
- handle: self.native().handle,
- title: self.native().title()?,
- class_name: self.native().class_name()?,
- process_name: self.native().process_name()?,
+ #[allow(clippy::cast_possible_wrap, clippy::unnecessary_cast)]
+ handle: self.native().id().0 as isize,
+ title: self.native_properties().title,
+ #[cfg(target_os = "windows")]
+ class_name: self.native_properties().class_name,
+ process_name: self.native_properties().process_name,
active_drag: self.active_drag(),
}))
}
@@ -136,7 +149,18 @@ impl PositionGetters for NonTilingWindow {
fn to_rect(&self) -> anyhow::Result<Rect> {
match self.state() {
WindowState::Fullscreen(_) => {
- self.monitor().context("No monitor.")?.to_rect()
+ let monitor = self.monitor().context("No monitor.")?;
+
+ #[cfg(target_os = "windows")]
+ {
+ monitor.to_rect()
+ }
+ #[cfg(target_os = "macos")]
+ {
+ // On macOS, the public APIs only allow window placement within
+ // the display's working area.
+ Ok(monitor.native_properties().working_area)
+ }
}
_ => Ok(self.floating_placement()),
}
diff --git a/packages/wm/src/models/root_container.rs b/packages/wm/src/models/root_container.rs
index 8ad60b2c..f085684c 100644
--- a/packages/wm/src/models/root_container.rs
+++ b/packages/wm/src/models/root_container.rs
@@ -6,7 +6,8 @@ use std::{
use anyhow::bail;
use uuid::Uuid;
-use wm_common::{ContainerDto, Rect, RootContainerDto};
+use wm_common::{ContainerDto, RootContainerDto};
+use wm_platform::Rect;
use crate::{
impl_common_getters, impl_container_debug,
diff --git a/packages/wm/src/models/split_container.rs b/packages/wm/src/models/split_container.rs
index 7c524872..7d86b68f 100644
--- a/packages/wm/src/models/split_container.rs
+++ b/packages/wm/src/models/split_container.rs
@@ -7,8 +7,9 @@ use std::{
use anyhow::Context;
use uuid::Uuid;
use wm_common::{
- ContainerDto, GapsConfig, Rect, SplitContainerDto, TilingDirection,
+ ContainerDto, GapsConfig, SplitContainerDto, TilingDirection,
};
+use wm_platform::Rect;
use crate::{
impl_common_getters, impl_container_debug,
diff --git a/packages/wm/src/models/tiling_window.rs b/packages/wm/src/models/tiling_window.rs
index 021511d2..7c6bbf0f 100644
--- a/packages/wm/src/models/tiling_window.rs
+++ b/packages/wm/src/models/tiling_window.rs
@@ -7,18 +7,19 @@ use std::{
use anyhow::Context;
use uuid::Uuid;
use wm_common::{
- ActiveDrag, ContainerDto, DisplayState, GapsConfig, Rect, RectDelta,
- TilingDirection, WindowDto, WindowRuleConfig, WindowState,
+ ActiveDrag, ContainerDto, DisplayState, GapsConfig, TilingDirection,
+ WindowDto, WindowRuleConfig, WindowState,
};
-use wm_platform::NativeWindow;
+use wm_platform::{NativeWindow, Rect, RectDelta};
use crate::{
impl_common_getters, impl_container_debug,
impl_position_getters_as_resizable, impl_tiling_size_getters,
impl_window_getters,
models::{
- Container, DirectionContainer, InsertionTarget, NonTilingWindow,
- TilingContainer, WindowContainer,
+ Container, DirectionContainer, InsertionTarget,
+ NativeWindowProperties, NonTilingWindow, TilingContainer,
+ WindowContainer,
},
traits::{
CommonGetters, PositionGetters, TilingDirectionGetters,
@@ -36,6 +37,7 @@ struct TilingWindowInner {
child_focus_order: VecDeque<Uuid>,
tiling_size: f32,
native: NativeWindow,
+ native_properties: NativeWindowProperties,
state: WindowState,
prev_state: Option<WindowState>,
display_state: DisplayState,
@@ -53,6 +55,7 @@ impl TilingWindow {
pub fn new(
id: Option<Uuid>,
native: NativeWindow,
+ properties: NativeWindowProperties,
prev_state: Option<WindowState>,
border_delta: RectDelta,
floating_placement: Rect,
@@ -68,6 +71,7 @@ impl TilingWindow {
child_focus_order: VecDeque::new(),
tiling_size: 1.0,
native,
+ native_properties: properties,
state: WindowState::Tiling,
prev_state,
display_state: DisplayState::Shown,
@@ -91,6 +95,7 @@ impl TilingWindow {
NonTilingWindow::new(
Some(self.id()),
self.native().clone(),
+ self.native_properties().clone(),
state,
Some(WindowState::Tiling),
self.border_delta(),
@@ -119,10 +124,12 @@ impl TilingWindow {
display_state: self.display_state(),
border_delta: self.border_delta(),
floating_placement: self.floating_placement(),
- handle: self.native().handle,
- title: self.native().title()?,
- class_name: self.native().class_name()?,
- process_name: self.native().process_name()?,
+ #[allow(clippy::cast_possible_wrap, clippy::unnecessary_cast)]
+ handle: self.native().id().0 as isize,
+ title: self.native_properties().title,
+ #[cfg(target_os = "windows")]
+ class_name: self.native_properties().class_name,
+ process_name: self.native_properties().process_name,
active_drag: self.active_drag(),
}))
}
diff --git a/packages/wm/src/models/workspace.rs b/packages/wm/src/models/workspace.rs
index e5daf323..9ad291f3 100644
--- a/packages/wm/src/models/workspace.rs
+++ b/packages/wm/src/models/workspace.rs
@@ -7,9 +7,9 @@ use std::{
use anyhow::Context;
use uuid::Uuid;
use wm_common::{
- ContainerDto, GapsConfig, Rect, TilingDirection, WorkspaceConfig,
- WorkspaceDto,
+ ContainerDto, GapsConfig, TilingDirection, WorkspaceConfig, WorkspaceDto,
};
+use wm_platform::{Rect, RectDelta};
use crate::{
impl_common_getters, impl_container_debug,
@@ -75,6 +75,80 @@ impl Workspace {
self.0.borrow_mut().gaps_config = gaps_config;
}
+ /// Effective outer gaps for this workspace.
+ ///
+ /// Uses `single_window_outer_gap` when the workspace has a single tiling
+ /// window, otherwise falls back to `outer_gap`.
+ pub fn outer_gaps(&self) -> RectDelta {
+ let is_single_window = self.tiling_children().nth(1).is_none();
+
+ let gaps_config = &self.0.borrow().gaps_config;
+ let gaps = if is_single_window {
+ gaps_config
+ .single_window_outer_gap
+ .as_ref()
+ .unwrap_or(&gaps_config.outer_gap)
+ } else {
+ &gaps_config.outer_gap
+ };
+
+ // TODO: Should this be scaled by the monitor's DPI?
+ gaps.clone()
+ }
+
+ /// Gets the bounds of a workspace with the given outer gap config.
+ fn workspace_rect_with_gap_config(
+ &self,
+ outer_gaps: &RectDelta,
+ ) -> anyhow::Result<Rect> {
+ let monitor =
+ self.monitor().context("Workspace has no parent monitor.")?;
+
+ let gaps_config = &self.0.borrow().gaps_config;
+ let scale_factor = if gaps_config.scale_with_dpi {
+ monitor.native_properties().scale_factor
+ } else {
+ 1.
+ };
+
+ // Get the delta between the monitor's bounds and its working area.
+ let monitor_bounds = monitor.native_properties().bounds;
+ let working_area_delta = monitor
+ .native_properties()
+ .working_area
+ .delta(&monitor_bounds);
+
+ Ok(
+ monitor_bounds
+ // Scale the gaps if `scale_with_dpi` is enabled. Outer gap config
+ // values can be a percentage (relative to the monitor bounds), so
+ // the outer gap delta needs to be applied prior to the working
+ // area delta.
+ .apply_delta(&outer_gaps.inverse(), Some(scale_factor))
+ .apply_delta(&working_area_delta, None),
+ )
+ }
+
+ /// Gets the maximum bounds of a workspace considering both `outer_gap`
+ /// and `single_window_outer_gap` config values.
+ pub fn max_workspace_rect(&self) -> anyhow::Result<Rect> {
+ let gaps_config = &self.0.borrow().gaps_config;
+
+ // Get the workspace rect using `outer_gap`.
+ let multi_window_rect =
+ self.workspace_rect_with_gap_config(&gaps_config.outer_gap)?;
+
+ let Some(single_gap) = &gaps_config.single_window_outer_gap else {
+ return Ok(multi_window_rect);
+ };
+
+ // Get the workspace rect using `single_window_outer_gap`.
+ let single_window_rect =
+ self.workspace_rect_with_gap_config(single_gap)?;
+
+ Ok(multi_window_rect.union(&single_window_rect))
+ }
+
pub fn to_dto(&self) -> anyhow::Result<ContainerDto> {
let rect = self.to_rect()?;
let config = self.config();
@@ -109,40 +183,7 @@ impl_tiling_direction_getters!(Workspace);
impl PositionGetters for Workspace {
fn to_rect(&self) -> anyhow::Result<Rect> {
- let monitor =
- self.monitor().context("Workspace has no parent monitor.")?;
-
- let gaps_config = &self.0.borrow().gaps_config;
- let scale_factor = match &gaps_config.scale_with_dpi {
- true => monitor.native().scale_factor()?,
- false => 1.,
- };
-
- // Get delta between monitor bounds and its working area.
- let working_delta = monitor
- .native()
- .working_rect()
- .context("Failed to get working area of parent monitor.")?
- .delta(&monitor.to_rect()?);
-
- let is_single_window = self.tiling_children().nth(1).is_none();
-
- let gaps = if is_single_window {
- gaps_config
- .single_window_outer_gap
- .as_ref()
- .unwrap_or(&gaps_config.outer_gap)
- } else {
- &gaps_config.outer_gap
- };
-
- Ok(
- monitor
- .to_rect()?
- // Scale the gaps if `scale_with_dpi` is enabled.
- .apply_inverse_delta(gaps, Some(scale_factor))
- .apply_delta(&working_delta, None),
- )
+ self.workspace_rect_with_gap_config(&self.outer_gaps())
}
}
diff --git a/packages/wm/src/models/workspace_target.rs b/packages/wm/src/models/workspace_target.rs
index dbfd62b1..dfede281 100644
--- a/packages/wm/src/models/workspace_target.rs
+++ b/packages/wm/src/models/workspace_target.rs
@@ -1,4 +1,4 @@
-use wm_common::Direction;
+use wm_platform::Direction;
pub enum WorkspaceTarget {
Name(String),
diff --git a/packages/wm/src/pending_sync.rs b/packages/wm/src/pending_sync.rs
index 8687e011..a6966784 100644
--- a/packages/wm/src/pending_sync.rs
+++ b/packages/wm/src/pending_sync.rs
@@ -7,7 +7,7 @@ use crate::{
traits::CommonGetters,
};
-#[derive(Default)]
+#[derive(Debug, Default)]
#[allow(clippy::struct_excessive_bools)]
pub struct PendingSync {
/// Containers (and their descendants) that have a pending redraw.
diff --git a/packages/wm/src/sys_tray.rs b/packages/wm/src/sys_tray.rs
index bc61f6c9..5bacf928 100644
--- a/packages/wm/src/sys_tray.rs
+++ b/packages/wm/src/sys_tray.rs
@@ -1,142 +1,281 @@
-use std::{path::Path, thread::JoinHandle, time::Duration};
+use std::{
+ fmt::{self, Display},
+ path::Path,
+ str::FromStr,
+ sync::{Arc, Mutex},
+};
use anyhow::Context;
+use auto_launch::AutoLaunch;
use tokio::sync::mpsc;
-use tracing::{info, warn};
use tray_icon::{
menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem},
- Icon, TrayIconBuilder,
+ Icon, TrayIcon, TrayIconBuilder,
};
-use wm_platform::Platform;
+#[cfg(target_os = "windows")]
+use wm_platform::DispatcherExtWindows;
+use wm_platform::{Dispatcher, ThreadBound};
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+enum TrayMenuId {
+ ReloadConfig,
+ ShowConfigFolder,
+ #[cfg(target_os = "windows")]
+ ToggleWindowAnimations,
+ RunOnStartup,
+ Exit,
+}
+
+impl Display for TrayMenuId {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ TrayMenuId::ReloadConfig => write!(f, "reload_config"),
+ TrayMenuId::ShowConfigFolder => write!(f, "show_config_folder"),
+ #[cfg(target_os = "windows")]
+ TrayMenuId::ToggleWindowAnimations => {
+ write!(f, "toggle_window_animations")
+ }
+ TrayMenuId::RunOnStartup => write!(f, "run_on_startup"),
+ TrayMenuId::Exit => write!(f, "exit"),
+ }
+ }
+}
+
+impl FromStr for TrayMenuId {
+ type Err = anyhow::Error;
-/// Ordinal to `IDI_ICON` definition in embedded resource file.
-const IDI_ICON: u16 = 32512;
+ fn from_str(event: &str) -> Result<Self, Self::Err> {
+ match event {
+ "show_config_folder" => Ok(Self::ShowConfigFolder),
+ "reload_config" => Ok(Self::ReloadConfig),
+ #[cfg(target_os = "windows")]
+ "toggle_window_animations" => Ok(Self::ToggleWindowAnimations),
+ "exit" => Ok(Self::Exit),
+ _ => anyhow::bail!("Invalid tray menu event: {}", event),
+ }
+ }
+}
pub struct SystemTray {
pub config_reload_rx: mpsc::UnboundedReceiver<()>,
pub exit_rx: mpsc::UnboundedReceiver<()>,
- icon_thread: Option<JoinHandle<anyhow::Result<()>>>,
+ _icon_thread: Option<std::thread::JoinHandle<()>>,
+ _tray_icon: ThreadBound<TrayIcon>,
}
impl SystemTray {
- pub fn new(config_path: &Path) -> anyhow::Result<Self> {
+ /// Install the system tray on the main thread after the run loop starts.
+ pub fn new(
+ config_path: &Path,
+ dispatcher: Dispatcher,
+ ) -> anyhow::Result<Self> {
let (exit_tx, exit_rx) = mpsc::unbounded_channel();
let (config_reload_tx, config_reload_rx) = mpsc::unbounded_channel();
- let config_dir = config_path
- .parent()
- .context("Invalid config path.")?
- .to_owned();
- let icon_thread = std::thread::spawn(move || {
- let reload_config_item = MenuItem::new("Reload config", true, None);
-
- let config_dir_item =
- MenuItem::new("Show config folder", true, None);
-
- let mut animations_enabled =
- Platform::window_animations_enabled().unwrap_or(true);
-
- let animations_item = CheckMenuItem::new(
- "Window animations",
- true,
- animations_enabled,
- None,
- );
-
- let mut start_with_windows_enabled =
- Platform::is_auto_launch_enabled().unwrap_or(false);
-
- let start_with_windows_item = CheckMenuItem::new(
- "Start with Windows",
- true,
- start_with_windows_enabled,
- None,
- );
-
- let exit_item = MenuItem::new("Exit", true, None);
-
- let tray_menu = Menu::new();
- tray_menu.append_items(&[
- &reload_config_item,
- &config_dir_item,
- &animations_item,
- &start_with_windows_item,
- &PredefinedMenuItem::separator(),
- &exit_item,
- ])?;
-
- let icon = Icon::from_resource(IDI_ICON, None)?;
- let _tray_icon = TrayIconBuilder::new()
- .with_menu(Box::new(tray_menu))
- .with_tooltip(format!("GlazeWM v{}", env!("VERSION_NUMBER")))
- .with_icon(icon)
- .build()?;
+ let animations_enabled = Arc::new(Mutex::new({
+ #[cfg(target_os = "windows")]
+ {
+ dispatcher.window_animations_enabled().unwrap_or(false)
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ false
+ }
+ }));
+ let run_on_startup_enabled = Arc::new(Mutex::new(
+ auto_launch_instance()
+ .and_then(|auto_launch| {
+ auto_launch.is_enabled().map_err(Into::into)
+ })
+ .unwrap_or(false),
+ ));
+
+ let tray_icon = dispatcher.dispatch_sync(|| {
+ let tray_icon = Self::create_tray_icon(
+ *animations_enabled.lock().unwrap(),
+ *run_on_startup_enabled.lock().unwrap(),
+ )
+ .unwrap();
+ ThreadBound::new(tray_icon, dispatcher.clone())
+ })?;
+
+ // Spawn thread to handle tray menu events.
+ let config_path = config_path.to_owned();
+ let icon_thread = std::thread::spawn(move || {
let menu_event_rx = MenuEvent::receiver();
- loop {
- if let Ok(event) = menu_event_rx.try_recv() {
- if event.id == reload_config_item.id() {
- config_reload_tx.send(())?;
- } else if event.id == config_dir_item.id() {
- // Open config directory in File Explorer.
- let _ = Platform::open_file_explorer(&config_dir);
- } else if event.id == animations_item.id() {
- // Toggle window animations globally.
- let _ =
- Platform::set_window_animations_enabled(!animations_enabled);
-
- animations_enabled = !animations_enabled;
- } else if event.id == start_with_windows_item.id() {
- // Toggle auto-launch on Windows startup.
- let _ =
- Platform::set_auto_launch_enabled(!start_with_windows_enabled);
-
- start_with_windows_enabled = !start_with_windows_enabled;
- } else if event.id == exit_item.id() {
- exit_tx.send(())?;
+ while let Ok(event) = menu_event_rx.recv() {
+ if let Ok(menu_event) = TrayMenuId::from_str(event.id.as_ref()) {
+ if let Err(err) = Self::handle_menu_event(
+ &menu_event,
+ &dispatcher,
+ &config_path,
+ &config_reload_tx,
+ &exit_tx,
+ &animations_enabled,
+ &run_on_startup_enabled,
+ ) {
+ tracing::warn!("Failed to handle tray menu event: {}", err);
}
}
-
- // Run message loop with a delay of 16ms (60fps).
- if Platform::run_message_cycle().is_err() {
- break;
- }
-
- std::thread::sleep(Duration::from_millis(16));
}
-
- Ok(())
});
Ok(Self {
config_reload_rx,
exit_rx,
- icon_thread: Some(icon_thread),
+ _icon_thread: Some(icon_thread),
+ _tray_icon: tray_icon,
})
}
- /// Destroys the system tray icon and stops its associated message loop.
- pub fn destroy(&mut self) -> anyhow::Result<()> {
- info!("Shutting down system tray.");
+ fn create_tray_icon(
+ // LINT: `animations_enabled` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
+ animations_enabled: bool,
+ run_on_startup_enabled: bool,
+ ) -> anyhow::Result<TrayIcon> {
+ let reload_config_item = MenuItem::with_id(
+ TrayMenuId::ReloadConfig,
+ "Reload config",
+ true,
+ None,
+ );
- // Wait for the spawned thread to finish.
- if let Some(icon_thread) = self.icon_thread.take() {
- Platform::kill_message_loop(&icon_thread)?;
+ let config_dir_item = MenuItem::with_id(
+ TrayMenuId::ShowConfigFolder,
+ "Show config folder",
+ true,
+ None,
+ );
- icon_thread
- .join()
- .map_err(|_| anyhow::anyhow!("Thread join failed."))??;
- }
+ #[cfg(target_os = "windows")]
+ let toggle_animations_item = CheckMenuItem::with_id(
+ TrayMenuId::ToggleWindowAnimations,
+ "Window animations",
+ true,
+ animations_enabled,
+ None,
+ );
+
+ let run_on_startup_item = CheckMenuItem::with_id(
+ TrayMenuId::RunOnStartup,
+ "Run on system startup",
+ true,
+ run_on_startup_enabled,
+ None,
+ );
- Ok(())
+ let exit_item =
+ MenuItem::with_id(TrayMenuId::Exit, "Exit", true, None);
+
+ let tray_menu = Menu::new();
+ tray_menu.append_items(&[
+ &reload_config_item,
+ &config_dir_item,
+ #[cfg(target_os = "windows")]
+ &toggle_animations_item,
+ &run_on_startup_item,
+ &PredefinedMenuItem::separator(),
+ &exit_item,
+ ])?;
+
+ let icon = Self::load_icon(include_bytes!(
+ "../../../resources/assets/icon.png"
+ ))?;
+
+ let tray_icon = TrayIconBuilder::new()
+ .with_menu(Box::new(tray_menu))
+ .with_tooltip(format!("GlazeWM v{}", env!("VERSION_NUMBER")))
+ .with_icon(icon)
+ .build()?;
+
+ Ok(tray_icon)
}
-}
-impl Drop for SystemTray {
- fn drop(&mut self) {
- if let Err(err) = self.destroy() {
- warn!("Failed to gracefully shut down system tray: {}", err);
+ fn load_icon(bytes: &[u8]) -> anyhow::Result<Icon> {
+ let (icon_rgba, icon_width, icon_height) = {
+ let image = image::load_from_memory(bytes)
+ .context("Failed to to create tray icon image from resource.")?
+ .into_rgba8();
+
+ let (width, height) = image.dimensions();
+ let rgba = image.into_raw();
+ (rgba, width, height)
+ };
+
+ Ok(tray_icon::Icon::from_rgba(
+ icon_rgba,
+ icon_width,
+ icon_height,
+ )?)
+ }
+
+ fn handle_menu_event(
+ menu_id: &TrayMenuId,
+ dispatcher: &Dispatcher,
+ config_path: &Path,
+ config_reload_tx: &mpsc::UnboundedSender<()>,
+ exit_tx: &mpsc::UnboundedSender<()>,
+ // LINT: `animations_enabled` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
+ animations_enabled: &Arc<Mutex<bool>>,
+ run_on_startup_enabled: &Arc<Mutex<bool>>,
+ ) -> anyhow::Result<()> {
+ tracing::info!("Processing tray menu event: {:?}", menu_id);
+
+ match menu_id {
+ TrayMenuId::ShowConfigFolder => {
+ dispatcher.open_file_explorer(config_path)?;
+ Ok(())
+ }
+ TrayMenuId::ReloadConfig => {
+ config_reload_tx.send(())?;
+ Ok(())
+ }
+ #[cfg(target_os = "windows")]
+ TrayMenuId::ToggleWindowAnimations => {
+ let mut animations_enabled = animations_enabled.lock().unwrap();
+ dispatcher.set_window_animations_enabled(!*animations_enabled)?;
+ *animations_enabled = !*animations_enabled;
+ Ok(())
+ }
+ TrayMenuId::RunOnStartup => {
+ let mut run_on_startup_enabled =
+ run_on_startup_enabled.lock().unwrap();
+
+ if *run_on_startup_enabled {
+ auto_launch_instance()?.disable()?;
+ } else {
+ auto_launch_instance()?.enable()?;
+ }
+
+ *run_on_startup_enabled = !*run_on_startup_enabled;
+ Ok(())
+ }
+ TrayMenuId::Exit => {
+ exit_tx.send(())?;
+ Ok(())
+ }
}
}
}
+
+/// Creates a new [`AutoLaunch`] instance for managing auto-launch at
+/// system startup.
+fn auto_launch_instance() -> anyhow::Result<AutoLaunch> {
+ // TODO: Is wrapping the exe path in quotes necessary?
+ let formatted_exe_path =
+ format!("\"{}\"", std::env::current_exe()?.to_string_lossy());
+ let args: [&str; 0] = [];
+
+ #[cfg(target_os = "windows")]
+ let instance = AutoLaunch::new("GlazeWM", &formatted_exe_path, &args);
+
+ #[cfg(target_os = "macos")]
+ let instance =
+ AutoLaunch::new("GlazeWM", &formatted_exe_path, false, &args);
+
+ Ok(instance)
+}
diff --git a/packages/wm/src/traits/position_getters.rs b/packages/wm/src/traits/position_getters.rs
index 725667b9..6052c5ce 100644
--- a/packages/wm/src/traits/position_getters.rs
+++ b/packages/wm/src/traits/position_getters.rs
@@ -1,5 +1,5 @@
use ambassador::delegatable_trait;
-use wm_common::Rect;
+use wm_platform::Rect;
#[delegatable_trait]
pub trait PositionGetters {
diff --git a/packages/wm/src/traits/tiling_direction_getters.rs b/packages/wm/src/traits/tiling_direction_getters.rs
index b06cf534..ee1b8d3f 100644
--- a/packages/wm/src/traits/tiling_direction_getters.rs
+++ b/packages/wm/src/traits/tiling_direction_getters.rs
@@ -1,5 +1,6 @@
use ambassador::delegatable_trait;
-use wm_common::{Direction, TilingDirection};
+use wm_common::TilingDirection;
+use wm_platform::Direction;
use super::CommonGetters;
use crate::models::{TilingContainer, TilingWindow};
diff --git a/packages/wm/src/traits/tiling_size_getters.rs b/packages/wm/src/traits/tiling_size_getters.rs
index df4144e0..226d887d 100644
--- a/packages/wm/src/traits/tiling_size_getters.rs
+++ b/packages/wm/src/traits/tiling_size_getters.rs
@@ -4,7 +4,7 @@ use ambassador::delegatable_trait;
use anyhow::Context;
use wm_common::{GapsConfig, TilingDirection};
-use super::{CommonGetters, PositionGetters, TilingDirectionGetters};
+use super::{CommonGetters, TilingDirectionGetters};
use crate::models::{Container, DirectionContainer, TilingContainer};
pub const MIN_TILING_SIZE: f32 = 0.01;
@@ -22,11 +22,11 @@ pub trait TilingSizeGetters: CommonGetters {
/// Gets the horizontal and vertical gaps between windows in pixels.
fn inner_gaps(&self) -> anyhow::Result<(i32, i32)> {
let monitor = self.monitor().context("No monitor.")?;
- let monitor_rect = monitor.to_rect()?;
+ let monitor_rect = monitor.native_properties().bounds;
let gaps_config = self.gaps_config();
let scale_factor = if gaps_config.scale_with_dpi {
- monitor.native().scale_factor()?
+ monitor.native_properties().scale_factor
} else {
1.
};
diff --git a/packages/wm/src/traits/window_getters.rs b/packages/wm/src/traits/window_getters.rs
index 1850f6ed..a8e1020c 100644
--- a/packages/wm/src/traits/window_getters.rs
+++ b/packages/wm/src/traits/window_getters.rs
@@ -1,16 +1,19 @@
use std::cell::Ref;
use ambassador::delegatable_trait;
-use wm_common::{
- ActiveDrag, DisplayState, LengthValue, Rect, RectDelta,
- WindowRuleConfig, WindowState,
+use wm_common::{ActiveDrag, DisplayState, WindowRuleConfig, WindowState};
+#[cfg(target_os = "windows")]
+use wm_platform::NativeWindowWindowsExt;
+use wm_platform::{LengthValue, NativeWindow, Rect, RectDelta};
+
+use crate::{
+ models::{NativeWindowProperties, Workspace},
+ traits::CommonGetters,
+ user_config::UserConfig,
};
-use wm_platform::NativeWindow;
-
-use crate::user_config::UserConfig;
#[delegatable_trait]
-pub trait WindowGetters {
+pub trait WindowGetters: CommonGetters {
fn state(&self) -> WindowState;
fn set_state(&self, state: WindowState);
@@ -65,7 +68,18 @@ pub trait WindowGetters {
fn total_border_delta(&self) -> anyhow::Result<RectDelta> {
let border_delta = self.border_delta();
- let shadow_border_delta = self.native().shadow_border_delta()?;
+
+ let shadow_border_delta = {
+ #[cfg(target_os = "windows")]
+ {
+ // TODO: Avoid re-querying for shadow borders.
+ self.native().shadow_borders()?
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ RectDelta::zero()
+ }
+ };
// TODO: Allow percentage length values.
Ok(RectDelta {
@@ -88,10 +102,38 @@ pub trait WindowGetters {
})
}
+ /// Gets whether the window should be fullscreen for the given workspace.
+ ///
+ /// A window is considered fullscreen if its frame covers or exceeds the
+ /// workspace bounds, meaning all sides extend into the outer gaps.
+ ///
+ /// NOTE: The OS can be off by up to 1px when positioning windows.
+ fn should_fullscreen(
+ &self,
+ workspace: &Workspace,
+ ) -> anyhow::Result<bool> {
+ let frame = self.native_properties().frame;
+ let workspace_rect = workspace.max_workspace_rect()?;
+
+ // Check if the window frame covers the workspace bounds (with 1px of
+ // leeway).
+ let is_covering = frame.contains_rect(&workspace_rect.inset(1));
+
+ // A workspace with one tiling window will have that window cover the
+ // workspace bounds, but it should not be considered fullscreen.
+ let is_single_tiling_window = self.state() == WindowState::Tiling
+ && self.tiling_siblings().count() == 0
+ && workspace_rect.inset(-1).contains_rect(&frame);
+
+ Ok(is_covering && !is_single_tiling_window)
+ }
+
fn display_state(&self) -> DisplayState;
fn set_display_state(&self, display_state: DisplayState);
+ // LINT: `has_pending_dpi_adjustment` is only used on Windows.
+ #[allow(unused)]
fn has_pending_dpi_adjustment(&self) -> bool;
fn set_has_pending_dpi_adjustment(
@@ -120,6 +162,14 @@ pub trait WindowGetters {
fn active_drag(&self) -> Option<ActiveDrag>;
fn set_active_drag(&self, active_drag: Option<ActiveDrag>);
+
+ /// Gets the cached native window properties.
+ fn native_properties(&self) -> NativeWindowProperties;
+
+ /// Updates the cached native window properties using a closure.
+ fn update_native_properties<F>(&self, updater: F)
+ where
+ F: FnOnce(&mut NativeWindowProperties);
}
/// Implements the `WindowGetters` trait for a given struct.
@@ -167,6 +217,8 @@ macro_rules! impl_window_getters {
self.0.borrow_mut().display_state = display_state;
}
+ // LINT: `has_pending_dpi_adjustment` is only used on Windows.
+ #[allow(unused)]
fn has_pending_dpi_adjustment(&self) -> bool {
self.0.borrow().has_pending_dpi_adjustment
}
@@ -217,6 +269,17 @@ macro_rules! impl_window_getters {
fn set_active_drag(&self, active_drag: Option<ActiveDrag>) {
self.0.borrow_mut().active_drag = active_drag;
}
+
+ fn native_properties(&self) -> NativeWindowProperties {
+ self.0.borrow().native_properties.clone()
+ }
+
+ fn update_native_properties<F>(&self, updater: F)
+ where
+ F: FnOnce(&mut NativeWindowProperties),
+ {
+ updater(&mut self.0.borrow_mut().native_properties);
+ }
}
};
}
diff --git a/packages/wm/src/user_config.rs b/packages/wm/src/user_config.rs
index 50ea81c1..f9506742 100644
--- a/packages/wm/src/user_config.rs
+++ b/packages/wm/src/user_config.rs
@@ -2,8 +2,8 @@ use std::{collections::HashMap, env, fs, path::PathBuf};
use anyhow::{Context, Result};
use wm_common::{
- InvokeCommand, MatchType, ParsedConfig, WindowMatchConfig,
- WindowRuleConfig, WindowRuleEvent, WorkspaceConfig,
+ InvokeCommand, KeybindingConfig, MatchType, ParsedConfig,
+ WindowMatchConfig, WindowRuleConfig, WindowRuleEvent, WorkspaceConfig,
};
use crate::{
@@ -223,10 +223,11 @@ impl UserConfig {
&self,
window: &WindowContainer,
event: &WindowRuleEvent,
- ) -> anyhow::Result<Vec<WindowRuleConfig>> {
- let window_title = window.native().title()?;
- let window_class = window.native().class_name()?;
- let window_process = window.native().process_name()?;
+ ) -> Vec<WindowRuleConfig> {
+ let window_title = window.native_properties().title;
+ #[cfg(target_os = "windows")]
+ let window_class = window.native_properties().class_name;
+ let window_process = window.native_properties().process_name;
let pending_window_rules = self
.window_rules_by_event
@@ -246,10 +247,18 @@ impl UserConfig {
.as_ref()
.is_none_or(|match_type| match_type.is_match(&window_process));
- let is_class_match = match_config
- .window_class
- .as_ref()
- .is_none_or(|match_type| match_type.is_match(&window_class));
+ let is_class_match = {
+ #[cfg(target_os = "windows")]
+ {
+ match_config.window_class.as_ref().is_none_or(|match_type| {
+ match_type.is_match(&window_class)
+ })
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ match_config.window_class.is_none()
+ }
+ };
let is_title_match = match_config
.window_title
@@ -262,7 +271,7 @@ impl UserConfig {
.cloned()
.collect::<Vec<_>>();
- Ok(pending_window_rules)
+ pending_window_rules
}
pub fn inactive_workspace_configs(
@@ -332,21 +341,30 @@ impl UserConfig {
});
}
- pub fn outer_gaps_for_workspace(
+ /// Keybinding configs that should be active for the current binding mode
+ /// and pause state.
+ ///
+ /// When paused, only the configs with `InvokeCommand::WmTogglePause` are
+ /// returned so that unpausing remains possible.
+ pub fn active_keybinding_configs(
&self,
- workspace: &Workspace,
- ) -> &wm_common::RectDelta {
- let is_single_window = workspace.tiling_children().nth(1).is_none();
-
- if is_single_window {
- self
- .value
- .gaps
- .single_window_outer_gap
- .as_ref()
- .unwrap_or(&self.value.gaps.outer_gap)
+ binding_modes: &[wm_common::BindingModeConfig],
+ is_paused: bool,
+ ) -> impl Iterator<Item = KeybindingConfig> {
+ let source_configs = if let Some(first_mode) = binding_modes.first() {
+ &first_mode.keybindings
} else {
- &self.value.gaps.outer_gap
+ &self.value.keybindings
}
+ .clone();
+
+ source_configs.into_iter().filter(move |kb| {
+ if is_paused {
+ kb.commands
+ .contains(&wm_common::InvokeCommand::WmTogglePause)
+ } else {
+ true
+ }
+ })
}
}
diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rs
index 7ef0f432..7e58d8d1 100644
--- a/packages/wm/src/wm.rs
+++ b/packages/wm/src/wm.rs
@@ -2,11 +2,17 @@ use anyhow::{bail, Context};
use tokio::sync::mpsc::{self};
use tracing::warn;
use uuid::Uuid;
+#[cfg(target_os = "windows")]
+use wm_common::TitleBarVisibility;
use wm_common::{
- FloatingStateConfig, FullscreenStateConfig, InvokeCommand, LengthValue,
- RectDelta, TitleBarVisibility, WindowState, WmEvent,
+ FloatingStateConfig, FullscreenStateConfig, InvokeCommand, WindowState,
+ WmEvent,
+};
+#[cfg(target_os = "windows")]
+use wm_platform::NativeWindowWindowsExt;
+use wm_platform::{
+ Dispatcher, LengthValue, PlatformEvent, RectDelta, WindowEvent,
};
-use wm_platform::PlatformEvent;
use crate::{
commands::{
@@ -32,11 +38,11 @@ use crate::{
events::{
handle_display_settings_changed, handle_mouse_move,
handle_window_destroyed, handle_window_focused, handle_window_hidden,
- handle_window_location_changed, handle_window_minimize_ended,
- handle_window_minimized, handle_window_moved_or_resized_end,
- handle_window_moved_or_resized_start, handle_window_shown,
+ handle_window_minimize_ended, handle_window_minimized,
+ handle_window_moved_or_resized, handle_window_shown,
handle_window_title_changed,
},
+ ipc_server::IpcServer,
models::{Container, WorkspaceTarget},
traits::{CommonGetters, WindowGetters},
user_config::UserConfig,
@@ -50,11 +56,14 @@ pub struct WindowManager {
}
impl WindowManager {
- pub fn new(config: &mut UserConfig) -> anyhow::Result<Self> {
+ pub fn new(
+ config: &mut UserConfig,
+ dispatcher: Dispatcher,
+ ) -> anyhow::Result<Self> {
let (event_tx, event_rx) = mpsc::unbounded_channel();
let (exit_tx, exit_rx) = mpsc::unbounded_channel();
- let mut state = WmState::new(event_tx, exit_tx);
+ let mut state = WmState::new(dispatcher, event_tx, exit_tx);
state.populate(config)?;
Ok(Self {
@@ -75,46 +84,63 @@ impl WindowManager {
PlatformEvent::DisplaySettingsChanged => {
handle_display_settings_changed(state, config)
}
- PlatformEvent::KeybindingTriggered(kb_config) => {
- self.process_commands(&kb_config.commands, None, config)?;
+ PlatformEvent::Keybinding(keybinding_event) => {
+ // Find the keybinding config that matches this keybinding.
+ let commands = config
+ .active_keybinding_configs(
+ &self.state.binding_modes,
+ self.state.is_paused,
+ )
+ .find(|kb_config| {
+ kb_config.bindings.contains(&keybinding_event.0)
+ })
+ .map(|kb_config| kb_config.commands.clone());
+
+ if let Some(commands) = commands {
+ self.process_commands(&commands, None, config)?;
+ }
// Return early since we don't want to redraw twice.
return Ok(());
}
- PlatformEvent::MouseMove(event) => {
+ PlatformEvent::Mouse(event) => {
handle_mouse_move(&event, state, config)
}
- PlatformEvent::WindowDestroyed(window) => {
- handle_window_destroyed(&window, state)
- }
- PlatformEvent::WindowFocused(window) => {
- handle_window_focused(&window, state, config)
- }
- PlatformEvent::WindowHidden(window) => {
- handle_window_hidden(&window, state)
- }
- PlatformEvent::WindowLocationChanged(window) => {
- handle_window_location_changed(&window, state, config)
- }
- PlatformEvent::WindowMinimized(window) => {
- handle_window_minimized(&window, state, config)
- }
- PlatformEvent::WindowMinimizeEnded(window) => {
- handle_window_minimize_ended(&window, state, config)
- }
- PlatformEvent::WindowMovedOrResizedEnd(window) => {
- handle_window_moved_or_resized_end(&window, state, config)
- }
- PlatformEvent::WindowMovedOrResizedStart(window) => {
- handle_window_moved_or_resized_start(&window, state);
- Ok(())
- }
- PlatformEvent::WindowShown(window) => {
- handle_window_shown(window, state, config)
- }
- PlatformEvent::WindowTitleChanged(window) => {
- handle_window_title_changed(&window, state, config)
- }
+ PlatformEvent::Window(window_event) => match window_event {
+ WindowEvent::Focused { window, .. } => {
+ handle_window_focused(&window, state, config)
+ }
+ WindowEvent::Shown { window, .. } => {
+ handle_window_shown(window, state, config)
+ }
+ WindowEvent::Hidden { window, .. } => {
+ handle_window_hidden(&window, state, config)
+ }
+ WindowEvent::MovedOrResized {
+ window,
+ is_interactive_start,
+ is_interactive_end,
+ ..
+ } => handle_window_moved_or_resized(
+ &window,
+ is_interactive_start,
+ is_interactive_end,
+ state,
+ config,
+ ),
+ WindowEvent::Minimized { window, .. } => {
+ handle_window_minimized(&window, state, config)
+ }
+ WindowEvent::MinimizeEnded { window, .. } => {
+ handle_window_minimize_ended(&window, state, config)
+ }
+ WindowEvent::TitleChanged { window, .. } => {
+ handle_window_title_changed(&window, state, config)
+ }
+ WindowEvent::Destroyed { window_id, .. } => {
+ handle_window_destroyed(window_id, state)
+ }
+ },
}?;
if !state.is_paused && state.pending_sync.has_changes() {
@@ -567,19 +593,25 @@ impl WindowManager {
_ => Ok(()),
}
}
- InvokeCommand::SetTitleBarVisibility { visibility } => {
- match subject_container.as_window_container() {
- Ok(window) => {
- _ = window.native().set_title_bar_visibility(
- *visibility == TitleBarVisibility::Shown,
- );
- Ok(())
- }
- _ => Ok(()),
+ InvokeCommand::SetTitleBarVisibility {
+ // LINT: `visibility` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
+ visibility,
+ } => match subject_container.as_window_container() {
+ #[cfg(target_os = "windows")]
+ Ok(window) => {
+ _ = window.native().set_title_bar_visibility(
+ *visibility == TitleBarVisibility::Shown,
+ );
+ Ok(())
}
- }
+ _ => Ok(()),
+ },
+ // LINT: `args` is only used on Windows.
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
InvokeCommand::SetTransparency(args) => {
match subject_container.as_window_container() {
+ #[cfg(target_os = "windows")]
Ok(window) => {
if let Some(opacity) = &args.opacity {
_ = window.native().set_transparency(opacity);
@@ -597,7 +629,7 @@ impl WindowManager {
InvokeCommand::ShellExec {
hide_window,
command,
- } => shell_exec(&command.join(" "), *hide_window),
+ } => shell_exec(&command.join(" "), *hide_window, state),
InvokeCommand::Size(args) => {
match subject_container.as_window_container() {
Ok(window) => set_window_size(
@@ -746,4 +778,38 @@ impl WindowManager {
}
}
}
+
+ /// Runs cleanup tasks when the WM is exiting.
+ pub(crate) fn cleanup(
+ &mut self,
+ config: &mut UserConfig,
+ ipc_server: &mut IpcServer,
+ ) {
+ self.state.emit_event(WmEvent::ApplicationExiting);
+
+ // Ensure that the WM is unpaused, otherwise, shutdown commands won't
+ // get executed.
+ self.state.is_paused = false;
+
+ // Run user's shutdown commands.
+ if let Err(err) = self.process_commands(
+ &config.value.general.shutdown_commands.clone(),
+ None,
+ config,
+ ) {
+ tracing::warn!("Failed to run shutdown commands: {:?}", err);
+ }
+
+ // Emit remaining WM events before exiting.
+ while let Ok(wm_event) = self.event_rx.try_recv() {
+ tracing::info!(
+ "Emitting WM event before shutting down: {:?}",
+ wm_event
+ );
+
+ if let Err(err) = ipc_server.process_event(wm_event) {
+ tracing::warn!("{:?}", err);
+ }
+ }
+ }
}
diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rs
index 3d46d48a..81c63f61 100644
--- a/packages/wm/src/wm_state.rs
+++ b/packages/wm/src/wm_state.rs
@@ -4,37 +4,36 @@ use anyhow::Context;
use tokio::sync::mpsc::{self};
use tracing::warn;
use uuid::Uuid;
-use wm_common::{
- BindingModeConfig, Direction, Point, WindowState, WmEvent,
+use wm_common::{BindingModeConfig, HideCorner, WindowState, WmEvent};
+use wm_platform::{
+ Direction, Dispatcher, Display, NativeWindow, Point, Rect,
};
-use wm_platform::{NativeMonitor, NativeWindow, Platform};
+#[cfg(target_os = "windows")]
+use wm_platform::{NativeWindowWindowsExt, OpacityValue};
-use crate::commands::window::unmanage_window;
use crate::{
commands::{
container::set_focused_descendant,
general::platform_sync,
monitor::{add_monitor, move_bounded_workspaces_to_new_monitor},
- window::manage_window,
+ window::{manage_window, unmanage_window},
},
models::{
- Container, Monitor, RootContainer, WindowContainer, Workspace,
- WorkspaceTarget,
+ Container, Monitor, NativeMonitorProperties, RootContainer,
+ WindowContainer, Workspace, WorkspaceTarget,
},
pending_sync::PendingSync,
traits::{CommonGetters, PositionGetters, WindowGetters},
user_config::UserConfig,
};
-/// Interval in seconds for cleaning up invalid/ghost windows.
-/// Set to 5 seconds to balance between responsiveness and performance.
-pub const WINDOW_CLEANUP_INTERVAL_SECS: u64 = 5;
-
pub struct WmState {
/// Root node of the container tree. Monitors are the children of the
/// root node, followed by workspaces, then split containers/windows.
pub root_container: RootContainer,
+ pub dispatcher: Dispatcher,
+
pub pending_sync: PendingSync,
/// Name of the most recently focused workspace.
@@ -80,11 +79,13 @@ pub struct WmState {
impl WmState {
pub fn new(
+ dispatcher: Dispatcher,
event_tx: mpsc::UnboundedSender<WmEvent>,
exit_tx: mpsc::UnboundedSender<()>,
) -> Self {
Self {
root_container: RootContainer::new(),
+ dispatcher,
pending_sync: PendingSync::default(),
prev_effects_window: None,
recent_workspace_name: None,
@@ -106,18 +107,24 @@ impl WmState {
config: &mut UserConfig,
) -> anyhow::Result<()> {
// Get the originally focused window when the WM was started.
- let foreground_window = Platform::foreground_window();
+ let focused_window = self.dispatcher.focused_window().ok();
// Create a monitor, and consequently a workspace, for each detected
// native monitor.
- for native_monitor in Platform::sorted_monitors()? {
- let monitor = add_monitor(native_monitor, self)?;
- move_bounded_workspaces_to_new_monitor(&monitor, self, config)?;
+ for native_display in self.dispatcher.sorted_displays()? {
+ if let Ok(native_properties) =
+ NativeMonitorProperties::try_from(&native_display)
+ {
+ let monitor =
+ add_monitor(native_display, native_properties, self)?;
+ move_bounded_workspaces_to_new_monitor(&monitor, self, config)?;
+ }
}
// Manage windows in reverse z-order (bottom to top). This helps to
// preserve the original stacking order.
- for native_window in Platform::manageable_windows()?.into_iter().rev()
+ for native_window in
+ self.dispatcher.visible_windows()?.into_iter().rev()
{
let nearest_workspace = self
.nearest_monitor(&native_window)
@@ -133,11 +140,12 @@ impl WmState {
}
}
- let container_to_focus = self
- .window_from_native(&foreground_window)
- .map(|c| c.as_container())
- .or(self.windows().pop().map(Into::into))
- .or(self.workspaces().pop().map(Into::into))
+ let container_to_focus = focused_window
+ .and_then(|focused_window| {
+ self.window_from_native(&focused_window).map(Into::into)
+ })
+ .or_else(|| self.windows().pop().map(Into::into))
+ .or_else(|| self.workspaces().pop().map(Into::into))
.context("Failed to get container to focus.")?;
set_focused_descendant(&container_to_focus, None);
@@ -194,19 +202,21 @@ impl WmState {
native_window: &NativeWindow,
) -> Option<Monitor> {
self
- .monitor_from_native(&Platform::nearest_monitor(native_window))
+ .monitor_from_native(
+ &self.dispatcher.nearest_display(native_window).ok()?,
+ )
.or(self.monitors().first().cloned())
}
- /// Gets monitor that corresponds to the given `NativeMonitor`.
+ /// Gets monitor that corresponds to the given `Display`.
pub fn monitor_from_native(
&self,
- native_monitor: &NativeMonitor,
+ native_display: &Display,
) -> Option<Monitor> {
self
.monitors()
.into_iter()
- .find(|monitor| monitor.native() == *native_monitor)
+ .find(|monitor| monitor.native() == *native_display)
}
/// Gets the closest monitor in a given direction.
@@ -217,14 +227,14 @@ impl WmState {
origin_monitor: &Monitor,
direction: &Direction,
) -> anyhow::Result<Option<Monitor>> {
- let origin_rect = origin_monitor.native().rect()?.clone();
+ let origin_rect = origin_monitor.native_properties().bounds;
// Create a tuple of monitors and their rect.
let monitors_with_rect = self
.monitors()
.into_iter()
.map(|monitor| {
- let rect = monitor.native().rect()?.clone();
+ let rect = monitor.native_properties().bounds;
anyhow::Ok((monitor, rect))
})
.try_collect::<Vec<_>>()?;
@@ -233,16 +243,16 @@ impl WmState {
.into_iter()
.filter(|(_, rect)| match direction {
Direction::Right => {
- rect.x() > origin_rect.x() && rect.has_overlap_y(&origin_rect)
+ rect.x() > origin_rect.x() && rect.y_overlap(&origin_rect) > 0
}
Direction::Left => {
- rect.x() < origin_rect.x() && rect.has_overlap_y(&origin_rect)
+ rect.x() < origin_rect.x() && rect.y_overlap(&origin_rect) > 0
}
Direction::Down => {
- rect.y() > origin_rect.y() && rect.has_overlap_x(&origin_rect)
+ rect.y() > origin_rect.y() && rect.x_overlap(&origin_rect) > 0
}
Direction::Up => {
- rect.y() < origin_rect.y() && rect.has_overlap_x(&origin_rect)
+ rect.y() < origin_rect.y() && rect.x_overlap(&origin_rect) > 0
}
})
.min_by(|(_, rect_a), (_, rect_b)| match direction {
@@ -256,6 +266,67 @@ impl WmState {
Ok(closest_monitor)
}
+ /// Determines the preferred hide corner for each monitor. Used for
+ /// [`HideMethod::PlaceInCorner`].
+ ///
+ /// The corner is chosen by simulating a 400x400 window frame in the
+ /// bottom-left and bottom-right of the monitor's working area, then
+ /// picking the side that overlaps the least with other monitors'
+ /// working areas (ties favor bottom-right).
+ pub fn monitors_by_hide_corner(&self) -> Vec<(Monitor, HideCorner)> {
+ const TEST_FRAME_SIZE: i32 = 400;
+ const VISIBLE_SLIVER: i32 = 1;
+
+ let monitors = self.monitors();
+ let working_areas = monitors
+ .iter()
+ .map(|monitor| monitor.native_properties().working_area)
+ .collect::<Vec<_>>();
+
+ monitors
+ .into_iter()
+ .enumerate()
+ .map(|(idx, monitor)| {
+ let monitor_rect = &working_areas[idx];
+ let test_frame_y = monitor_rect.bottom - TEST_FRAME_SIZE;
+
+ let left_test_frame = Rect::from_xy(
+ monitor_rect.left - TEST_FRAME_SIZE + VISIBLE_SLIVER,
+ test_frame_y,
+ TEST_FRAME_SIZE,
+ TEST_FRAME_SIZE,
+ );
+
+ let right_test_frame = Rect::from_xy(
+ monitor_rect.right - VISIBLE_SLIVER,
+ test_frame_y,
+ TEST_FRAME_SIZE,
+ TEST_FRAME_SIZE,
+ );
+
+ let overlap_area = |test_frame: &Rect| -> i32 {
+ working_areas
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| *i != idx)
+ .map(|(_, rect)| test_frame.intersection_area(rect))
+ .sum()
+ };
+
+ let left_overlap = overlap_area(&left_test_frame);
+ let right_overlap = overlap_area(&right_test_frame);
+
+ let corner = if left_overlap < right_overlap {
+ HideCorner::BottomLeft
+ } else {
+ HideCorner::BottomRight
+ };
+
+ (monitor, corner)
+ })
+ .collect()
+ }
+
/// Gets window that corresponds to the given `NativeWindow`.
pub fn window_from_native(
&self,
@@ -585,20 +656,21 @@ impl WmState {
.cloned()
}
- /// Cleans up invalid window handles that may have become stale.
+ /// Cleans up windows that are no longer alive.
///
- /// This addresses the "ghost window" issue where applications terminate
- /// without properly sending window destroy events, leaving invalid
- /// window references in GlazeWM's state.
+ /// This addresses the "ghost window" issue where applications may
+ /// terminate without sending window destroy events, leaving invalid
+ /// windows in WM state.
+ ///
+ /// See: <https://github.com/glzr-io/glazewm/issues/1219>
pub fn cleanup_invalid_windows(&mut self) -> anyhow::Result<()> {
let invalid_windows = self
.windows()
.into_iter()
.filter(|window| !window.native().is_valid());
- // Remove each invalid window from the window tree
for window in invalid_windows {
- tracing::debug!("Removing invalid window: {}", window);
+ tracing::info!("Removing invalid window: {}", window);
unmanage_window(window, self)?;
}
@@ -608,14 +680,30 @@ impl WmState {
impl Drop for WmState {
fn drop(&mut self) {
- let managed_windows = self
- .windows()
- .into_iter()
- .map(|window| window.native().clone())
- .collect::<Vec<_>>();
+ let managed_windows = self.windows();
+
+ for window in &managed_windows {
+ // Redraw windows to their intended positions. On macOS, this will
+ // unhide windows that are on other workspaces.
+ if let Ok(rect) = window.to_rect() {
+ if let Err(err) = window.native().set_frame(&rect) {
+ warn!("Failed to redraw window on cleanup: {:?}", err);
+ }
+ }
- for window in managed_windows {
- window.cleanup();
+ // Reset any effects on Windows.
+ #[cfg(target_os = "windows")]
+ {
+ if let Err(err) = window.native().show() {
+ warn!("Failed to show window: {:?}", err);
+ }
+
+ let _ = window.native().set_taskbar_visibility(true);
+ let _ = window.native().set_border_color(None);
+ let _ = window
+ .native()
+ .set_transparency(&OpacityValue::from_alpha(u8::MAX));
+ }
}
}
}
diff --git a/resources/Info.plist b/resources/Info.plist
new file mode 100644
index 00000000..f7b4a1d4
--- /dev/null
+++ b/resources/Info.plist
@@ -0,0 +1,61 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleName</key>
+ <string>GlazeWM</string>
+
+ <key>CFBundleDisplayName</key>
+ <string>GlazeWM</string>
+
+ <key>CFBundleIdentifier</key>
+ <string>io.glzr.glazewm</string>
+
+ <key>CFBundleVersion</key>
+ <string>${VERSION}</string>
+
+ <key>CFBundleShortVersionString</key>
+ <string>${VERSION}</string>
+
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+
+ <key>CFBundleSignature</key>
+ <string>????</string>
+
+ <key>CFBundleExecutable</key>
+ <string>glazewm</string>
+
+ <key>CFBundleIconFile</key>
+ <string>icon</string>
+
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+
+ <key>LSMinimumSystemVersion</key>
+ <string>10.13</string>
+
+ <key>NSHighResolutionCapable</key>
+ <true/>
+
+ <key>LSApplicationCategoryType</key>
+ <string>public.app-category.utilities</string>
+
+ <key>NSHumanReadableCopyright</key>
+ <string>Copyright © glzr-io. All rights reserved.</string>
+
+ <!-- Run as background/agent app (no dock icon). -->
+ <key>LSUIElement</key>
+ <true/>
+
+ <!-- Description for why accessibility permissions are needed. -->
+ <key>NSAccessibilityUsageDescription</key>
+ <string>GlazeWM requires accessibility permissions to manage and arrange windows.</string>
+
+ <key>LSArchitecturePriority</key>
+ <array>
+ <string>arm64</string>
+ <string>x86_64</string>
+ </array>
+</dict>
+</plist>
diff --git a/resources/assets/icon.png b/resources/assets/icon.png
new file mode 100644
index 00000000..cd62db4f
Binary files /dev/null and b/resources/assets/icon.png differ
diff --git a/resources/assets/sample-config.yaml b/resources/assets/sample-config.yaml
index abda410c..7d6bc513 100644
--- a/resources/assets/sample-config.yaml
+++ b/resources/assets/sample-config.yaml
@@ -28,9 +28,10 @@ general:
trigger: 'monitor_focus'
# How windows should be hidden when switching workspaces.
- # - 'cloak': Recommended. Hides windows with no animation.
- # - 'hide': Legacy method (v3.5 and earlier) that has a brief animation,
- # but has stability issues with some apps.
+ # - 'cloak': (Windows-only) Recommended option for Windows.
+ # - 'hide': (Windows-only) Legacy option for Windows. Has stability issues with some apps.
+ # - 'place_in_corner': Artifically hides the window by placing it in the corner of the
+ # monitor. On macOS, this is always used instead of cloak/hide.
hide_method: 'cloak'
# Affects which windows get shown in the native Windows taskbar. Has no