فهرست منبع

Initial commit

Johannes Zellner 1 ماه پیش
کامیت
cde8d79d2a
34فایلهای تغییر یافته به همراه15987 افزوده شده و 0 حذف شده
  1. 5 0
      .gitignore
  2. 3382 0
      Cargo.lock
  3. 58 0
      Cargo.toml
  4. 21 0
      LICENSE
  5. 21 0
      LICENSE-Smithay.txt
  6. 55 0
      Makefile
  7. 182 0
      README.md
  8. 17 0
      config.example.toml
  9. 6 0
      data/compositron.desktop
  10. BIN
      resources/cursor.rgba
  11. BIN
      resources/numbers.png
  12. 475 0
      src/apps.rs
  13. 69 0
      src/config.rs
  14. 96 0
      src/cursor.rs
  15. 259 0
      src/drawing.rs
  16. 629 0
      src/focus.rs
  17. 214 0
      src/icons.rs
  18. 1778 0
      src/input_handler.rs
  19. 22 0
      src/lib.rs
  20. 75 0
      src/main.rs
  21. 222 0
      src/overview/layout.rs
  22. 498 0
      src/overview/mod.rs
  23. 548 0
      src/overview/render.rs
  24. 222 0
      src/render.rs
  25. 475 0
      src/shell/element.rs
  26. 896 0
      src/shell/grabs.rs
  27. 482 0
      src/shell/mod.rs
  28. 309 0
      src/shell/ssd.rs
  29. 691 0
      src/shell/xdg.rs
  30. 1583 0
      src/state.rs
  31. 203 0
      src/text.rs
  32. 1783 0
      src/udev.rs
  33. 513 0
      src/winit.rs
  34. 198 0
      src/workspaces.rs

+ 5 - 0
.gitignore

@@ -0,0 +1,5 @@
+/target
+*.png
+!assets/**/*.png
+!resources/*.png
+!/assets/**/*.png

+ 3382 - 0
Cargo.lock

@@ -0,0 +1,3382 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "ahash"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
+dependencies = [
+ "cfg-if",
+ "getrandom 0.3.4",
+ "once_cell",
+ "version_check",
+ "zerocopy",
+]
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "aliasable"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd"
+
+[[package]]
+name = "android-activity"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd"
+dependencies = [
+ "android-properties",
+ "bitflags 2.13.2",
+ "cc",
+ "jni",
+ "libc",
+ "log",
+ "ndk",
+ "ndk-context",
+ "ndk-sys",
+ "num_enum",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "android-properties"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"
+
+[[package]]
+name = "appendlist"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e149dc73cd30538307e7ffa2acd3d2221148eaeed4871f246657b1c3eaa1cbd2"
+
+[[package]]
+name = "approx"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f2a05fd1bd10b2527e20a2cd32d8873d115b8b39fe219ee25f42a8aca6ba278"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "arrayref"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
+
+[[package]]
+name = "arrayvec"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
+
+[[package]]
+name = "as-raw-xcb-connection"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "atomic_float"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "628d228f918ac3b82fe590352cc719d30664a0c13ca3a60266fe02c7132d480a"
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "block"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "block2"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
+dependencies = [
+ "objc2",
+]
+
+[[package]]
+name = "bstr"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"
+dependencies = [
+ "memchr",
+ "regex-automata",
+ "serde_core",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+dependencies = [
+ "bytemuck_derive",
+]
+
+[[package]]
+name = "bytemuck_derive"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[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.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+
+[[package]]
+name = "calloop"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec"
+dependencies = [
+ "bitflags 2.13.2",
+ "log",
+ "polling",
+ "rustix 0.38.44",
+ "slab",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "calloop"
+version = "0.14.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e"
+dependencies = [
+ "bitflags 2.13.2",
+ "polling",
+ "rustix 1.1.5",
+ "tracing",
+]
+
+[[package]]
+name = "calloop-wayland-source"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"
+dependencies = [
+ "calloop 0.13.0",
+ "rustix 0.38.44",
+ "wayland-backend",
+ "wayland-client",
+]
+
+[[package]]
+name = "cc"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838"
+dependencies = [
+ "find-msvc-tools",
+ "jobserver",
+ "libc",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
+[[package]]
+name = "cgmath"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a98d30140e3296250832bbaaff83b27dcd6fa3cc70fb6f1f3e5c9c0023b5317"
+dependencies = [
+ "approx",
+ "num-traits",
+]
+
+[[package]]
+name = "color_quant"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
+
+[[package]]
+name = "combine"
+version = "4.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"
+dependencies = [
+ "bytes",
+ "memchr",
+]
+
+[[package]]
+name = "compositron"
+version = "0.1.0"
+dependencies = [
+ "bitflags 2.13.2",
+ "cosmic-text",
+ "fps_ticker",
+ "freedesktop-desktop-entry",
+ "freedesktop-icons",
+ "image",
+ "profiling",
+ "renderdoc",
+ "resvg",
+ "serde",
+ "smithay",
+ "smithay-drm-extras",
+ "thiserror 1.0.69",
+ "tiny-skia",
+ "toml",
+ "tracing",
+ "tracing-subscriber",
+ "usvg",
+ "xcursor",
+ "xkbcommon",
+]
+
+[[package]]
+name = "concurrent-queue"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "core-graphics"
+version = "0.23.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
+dependencies = [
+ "bitflags 1.3.2",
+ "core-foundation",
+ "core-graphics-types",
+ "foreign-types",
+ "libc",
+]
+
+[[package]]
+name = "core-graphics-types"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
+dependencies = [
+ "bitflags 1.3.2",
+ "core-foundation",
+ "libc",
+]
+
+[[package]]
+name = "core_maths"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
+dependencies = [
+ "libm",
+]
+
+[[package]]
+name = "cosmic-text"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be17b688510d934ce13f48a2beba700e11583e281e0fda99c22bb256a14eda73"
+dependencies = [
+ "bitflags 2.13.2",
+ "fontdb 0.23.0",
+ "harfrust 0.5.2",
+ "linebender_resource_handle",
+ "log",
+ "rangemap",
+ "rustc-hash",
+ "self_cell",
+ "skrifa 0.40.0",
+ "smol_str 0.3.6",
+ "swash",
+ "sys-locale",
+ "unicode-bidi",
+ "unicode-linebreak",
+ "unicode-script",
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "cursor-icon"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
+
+[[package]]
+name = "data-url"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "dirs"
+version = "5.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
+dependencies = [
+ "dirs-sys",
+]
+
+[[package]]
+name = "dirs-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
+dependencies = [
+ "libc",
+ "option-ext",
+ "redox_users",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "dispatch"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"
+
+[[package]]
+name = "dlib"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"
+dependencies = [
+ "libloading 0.8.9",
+]
+
+[[package]]
+name = "downcast-rs"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
+
+[[package]]
+name = "dpi"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
+
+[[package]]
+name = "drm"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytemuck",
+ "drm-ffi",
+ "drm-fourcc",
+ "libc",
+ "rustix 0.38.44",
+]
+
+[[package]]
+name = "drm-ffi"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690"
+dependencies = [
+ "drm-sys",
+ "rustix 1.1.5",
+]
+
+[[package]]
+name = "drm-fourcc"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4"
+
+[[package]]
+name = "drm-sys"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8"
+dependencies = [
+ "libc",
+ "linux-raw-sys 0.9.4",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "euclid"
+version = "0.22.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "fdeflate"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
+dependencies = [
+ "simd-adler32",
+]
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
+
+[[package]]
+name = "flate2"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide 0.9.1",
+ "zlib-rs",
+]
+
+[[package]]
+name = "float-cmp"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "font-types"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "font-types"
+version = "0.12.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "fontconfig-parser"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
+dependencies = [
+ "roxmltree 0.20.0",
+]
+
+[[package]]
+name = "fontdb"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
+dependencies = [
+ "fontconfig-parser",
+ "log",
+ "memmap2",
+ "slotmap",
+ "tinyvec",
+ "ttf-parser",
+]
+
+[[package]]
+name = "fontdb"
+version = "0.24.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f"
+dependencies = [
+ "fontconfig-parser",
+ "log",
+ "memmap2",
+ "slotmap",
+ "tinyvec",
+]
+
+[[package]]
+name = "foreign-types"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
+dependencies = [
+ "foreign-types-macros",
+ "foreign-types-shared",
+]
+
+[[package]]
+name = "foreign-types-macros"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "foreign-types-shared"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
+
+[[package]]
+name = "fps_ticker"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe164905ff69757d4bdc4c61d7df2930e47e2f5b4a132895a8f995990b2b9219"
+
+[[package]]
+name = "freedesktop-desktop-entry"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9cfa09933e03f1ced380ad639822d65cb59a1914217da6c72aa8db3563e94214"
+dependencies = [
+ "bstr",
+ "gettext-rs",
+ "log",
+ "memchr",
+ "thiserror 2.0.21",
+ "unicase",
+ "xdg 3.0.0",
+]
+
+[[package]]
+name = "freedesktop-icons"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95f87364ea709292a3b3f74014ce3ee78412c89807eea75a358c8e029b000994"
+dependencies = [
+ "dirs",
+ "ini_core",
+ "once_cell",
+ "thiserror 1.0.69",
+ "tracing",
+ "xdg 2.5.2",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "gbm"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a"
+dependencies = [
+ "bitflags 2.13.2",
+ "drm",
+ "drm-fourcc",
+ "gbm-sys",
+ "libc",
+ "wayland-backend",
+ "wayland-server",
+]
+
+[[package]]
+name = "gbm-sys"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "gethostname"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
+dependencies = [
+ "rustix 1.1.5",
+ "windows-link",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 6.0.0",
+]
+
+[[package]]
+name = "gettext-rs"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9df5e3fa8c077b15fdfa8ce130e2bc73d663b8aaa6d51b71421b8659980b1d80"
+dependencies = [
+ "gettext-sys",
+ "locale_config",
+]
+
+[[package]]
+name = "gettext-sys"
+version = "0.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4caa7e4460b196107cc1bb2629488e8b6dbb7f34f6683ea6753c4ac22f590785"
+dependencies = [
+ "cc",
+ "temp-dir",
+]
+
+[[package]]
+name = "gif"
+version = "0.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
+dependencies = [
+ "color_quant",
+ "weezl",
+]
+
+[[package]]
+name = "gl_generator"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"
+dependencies = [
+ "khronos_api",
+ "log",
+ "xml-rs",
+]
+
+[[package]]
+name = "harfrust"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9da2e5ae821f6e96664977bf974d6d6a2d6682f9ccee23e62ec1d134246845f9"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytemuck",
+ "core_maths",
+ "read-fonts 0.37.0",
+ "smallvec",
+]
+
+[[package]]
+name = "harfrust"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytemuck",
+ "read-fonts 0.41.0",
+ "smallvec",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "hermit-abi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
+
+[[package]]
+name = "hermit-abi"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
+
+[[package]]
+name = "image"
+version = "0.25.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "moxcms",
+ "num-traits",
+ "png",
+ "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 = "imagesize"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a"
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "ini_core"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a467a31a9f439b5262fa99c17084537bff57f24703d5a09a2b5c9657ec73a61"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "input"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fbdc09524a91f9cacd26f16734ff63d7dc650daffadd2b6f84d17a285bd875a9"
+dependencies = [
+ "bitflags 2.13.2",
+ "input-sys",
+ "libc",
+ "udev",
+]
+
+[[package]]
+name = "input-sys"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "36eee07d8e02bd95bf52b2e642cf13d33701b94c6e4b04fbf1d1fb07e9cb19e7"
+
+[[package]]
+name = "io-lifetimes"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2"
+dependencies = [
+ "hermit-abi 0.3.9",
+ "libc",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "jni"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
+dependencies = [
+ "cfg-if",
+ "combine",
+ "jni-macros",
+ "jni-sys 0.4.1",
+ "log",
+ "simd_cesu8",
+ "thiserror 2.0.21",
+ "walkdir",
+ "windows-link",
+]
+
+[[package]]
+name = "jni-macros"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "simd_cesu8",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
+dependencies = [
+ "jni-sys 0.4.1",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
+dependencies = [
+ "jni-sys-macros",
+]
+
+[[package]]
+name = "jni-sys-macros"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "jobserver"
+version = "0.1.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
+dependencies = [
+ "getrandom 0.4.3",
+ "libc",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "khronos_api"
+version = "3.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
+
+[[package]]
+name = "kurbo"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
+dependencies = [
+ "arrayvec",
+ "euclid",
+ "polycool",
+ "smallvec",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "libloading"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"
+dependencies = [
+ "cfg-if",
+ "winapi",
+]
+
+[[package]]
+name = "libloading"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
+[[package]]
+name = "libredox"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
+dependencies = [
+ "bitflags 2.13.2",
+ "libc",
+ "plain",
+ "redox_syscall 0.9.4",
+]
+
+[[package]]
+name = "libseat"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6656c69b6e0366ffb83faa232f3e4fda5fc91161722d140f2c95ce2e90b1ef31"
+dependencies = [
+ "errno",
+ "libseat-sys",
+ "log",
+]
+
+[[package]]
+name = "libseat-sys"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8a484fa48be5f62a8d3ffed767779d0ab808cfead91de98ef4362d469097dfb"
+dependencies = [
+ "pkg-config",
+]
+
+[[package]]
+name = "libudev-sys"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324"
+dependencies = [
+ "libc",
+ "pkg-config",
+]
+
+[[package]]
+name = "linebender_resource_handle"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "locale_config"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08d2c35b16f4483f6c26f0e4e9550717a2f6575bcd6f12a53ff0c490a94a6934"
+dependencies = [
+ "lazy_static",
+ "objc",
+ "objc-foundation",
+ "regex",
+ "winapi",
+]
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "malloc_buf"
+version = "0.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "matchers"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
+dependencies = [
+ "regex-automata",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "memmap2"
+version = "0.9.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "miniz_oxide"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "moxcms"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
+[[package]]
+name = "ndk"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
+dependencies = [
+ "bitflags 2.13.2",
+ "jni-sys 0.3.1",
+ "log",
+ "ndk-sys",
+ "num_enum",
+ "raw-window-handle",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "ndk-context"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
+
+[[package]]
+name = "ndk-sys"
+version = "0.6.0+11769913"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
+dependencies = [
+ "jni-sys 0.3.1",
+]
+
+[[package]]
+name = "nu-ansi-term"
+version = "0.50.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "num_enum"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"
+dependencies = [
+ "num_enum_derive",
+ "rustversion",
+]
+
+[[package]]
+name = "num_enum_derive"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "objc"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
+dependencies = [
+ "malloc_buf",
+]
+
+[[package]]
+name = "objc-foundation"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9"
+dependencies = [
+ "block",
+ "objc",
+ "objc_id",
+]
+
+[[package]]
+name = "objc-sys"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
+
+[[package]]
+name = "objc2"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b"
+dependencies = [
+ "objc-sys",
+ "objc2-encode",
+]
+
+[[package]]
+name = "objc2-app-kit"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "libc",
+ "objc2",
+ "objc2-core-data",
+ "objc2-core-image",
+ "objc2-foundation",
+ "objc2-quartz-core",
+]
+
+[[package]]
+name = "objc2-cloud-kit"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "objc2",
+ "objc2-core-location",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-contacts"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889"
+dependencies = [
+ "block2",
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-data"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-image"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80"
+dependencies = [
+ "block2",
+ "objc2",
+ "objc2-foundation",
+ "objc2-metal",
+]
+
+[[package]]
+name = "objc2-core-location"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781"
+dependencies = [
+ "block2",
+ "objc2",
+ "objc2-contacts",
+ "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"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "dispatch",
+ "libc",
+ "objc2",
+]
+
+[[package]]
+name = "objc2-link-presentation"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398"
+dependencies = [
+ "block2",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-metal"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-quartz-core"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "objc2",
+ "objc2-foundation",
+ "objc2-metal",
+]
+
+[[package]]
+name = "objc2-symbols"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-ui-kit"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "objc2",
+ "objc2-cloud-kit",
+ "objc2-core-data",
+ "objc2-core-image",
+ "objc2-core-location",
+ "objc2-foundation",
+ "objc2-link-presentation",
+ "objc2-quartz-core",
+ "objc2-symbols",
+ "objc2-uniform-type-identifiers",
+ "objc2-user-notifications",
+]
+
+[[package]]
+name = "objc2-uniform-type-identifiers"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe"
+dependencies = [
+ "block2",
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-user-notifications"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "objc2",
+ "objc2-core-location",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc_id"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b"
+dependencies = [
+ "objc",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "option-ext"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+
+[[package]]
+name = "orbclient"
+version = "0.3.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747"
+dependencies = [
+ "libc",
+ "libredox",
+]
+
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "pico-args"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
+
+[[package]]
+name = "pin-project"
+version = "1.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"
+dependencies = [
+ "pin-project-internal",
+]
+
+[[package]]
+name = "pin-project-internal"
+version = "1.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "pixman"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cea217d496c19ac0a8e502b37078e1f683d16344adee9eb247a5d57c165e1edf"
+dependencies = [
+ "drm-fourcc",
+ "paste",
+ "pixman-sys",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "pixman-sys"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1a0483e89e81d7915defe83c51f23f6800594d64f6f4a21253ce87fd8444ada"
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "plain"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+
+[[package]]
+name = "png"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
+dependencies = [
+ "bitflags 2.13.2",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide 0.8.9",
+]
+
+[[package]]
+name = "polling"
+version = "3.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
+dependencies = [
+ "cfg-if",
+ "concurrent-queue",
+ "hermit-abi 0.5.3",
+ "pin-project-lite",
+ "rustix 1.1.5",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "polycool"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"
+dependencies = [
+ "arrayvec",
+]
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "proc-macro-crate"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
+dependencies = [
+ "toml_edit",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "profiling"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
+dependencies = [
+ "profiling-procmacros",
+]
+
+[[package]]
+name = "profiling-procmacros"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "pxfm"
+version = "0.1.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
+
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
+[[package]]
+name = "quick-xml"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
+dependencies = [
+ "rand_chacha",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
+[[package]]
+name = "rangemap"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d"
+
+[[package]]
+name = "raw-window-handle"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+
+[[package]]
+name = "read-fonts"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b634fabf032fab15307ffd272149b622260f55974d9fad689292a5d33df02e5"
+dependencies = [
+ "bytemuck",
+ "core_maths",
+ "font-types 0.11.3",
+]
+
+[[package]]
+name = "read-fonts"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
+dependencies = [
+ "bytemuck",
+ "font-types 0.12.7",
+ "once_cell",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
+dependencies = [
+ "bitflags 1.3.2",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "737970939a87c6fa31e7acad13307bccbb017a073b695b6089a2c484f929e20e"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "redox_users"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
+dependencies = [
+ "getrandom 0.2.17",
+ "libredox",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "renderdoc"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "272da9ec1e28b0ef17df4dcefad820b13f098ebe9c82697111fc57ccff621e12"
+dependencies = [
+ "bitflags 1.3.2",
+ "float-cmp",
+ "libloading 0.7.4",
+ "once_cell",
+ "renderdoc-sys",
+ "winapi",
+ "wio",
+]
+
+[[package]]
+name = "renderdoc-sys"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+
+[[package]]
+name = "resvg"
+version = "0.48.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd"
+dependencies = [
+ "bytemuck",
+ "gif",
+ "image-webp",
+ "log",
+ "pico-args",
+ "rgb",
+ "svgtypes",
+ "tiny-skia",
+ "usvg",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "rgb"
+version = "0.8.53"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "roxmltree"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
+
+[[package]]
+name = "roxmltree"
+version = "0.21.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "0.38.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
+dependencies = [
+ "bitflags 2.13.2",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.4.15",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
+dependencies = [
+ "bitflags 2.13.2",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.12.1",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "scoped-tls"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
+
+[[package]]
+name = "self_cell"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "sharded-slab"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
+dependencies = [
+ "lazy_static",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
+[[package]]
+name = "simd_cesu8"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
+dependencies = [
+ "rustc_version",
+ "simdutf8",
+]
+
+[[package]]
+name = "simdutf8"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
+
+[[package]]
+name = "simplecss"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"
+dependencies = [
+ "log",
+]
+
+[[package]]
+name = "siphasher"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
+
+[[package]]
+name = "skrifa"
+version = "0.40.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7fbdfe3d2475fbd7ddd1f3e5cf8288a30eb3e5f95832829570cd88115a7434ac"
+dependencies = [
+ "bytemuck",
+ "read-fonts 0.37.0",
+]
+
+[[package]]
+name = "skrifa"
+version = "0.44.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
+dependencies = [
+ "bytemuck",
+ "read-fonts 0.41.0",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "slotmap"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
+dependencies = [
+ "version_check",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.16.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
+
+[[package]]
+name = "smithay"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "740cea6927892bc182d5bf70c8f79806c8bc9f68f2fb96e55a30be171b63af98"
+dependencies = [
+ "aliasable",
+ "appendlist",
+ "atomic_float",
+ "bitflags 2.13.2",
+ "calloop 0.14.5",
+ "cc",
+ "cgmath",
+ "cursor-icon",
+ "downcast-rs",
+ "drm",
+ "drm-ffi",
+ "drm-fourcc",
+ "errno",
+ "gbm",
+ "gl_generator",
+ "indexmap",
+ "input",
+ "libc",
+ "libloading 0.8.9",
+ "libseat",
+ "pixman",
+ "pkg-config",
+ "profiling",
+ "rand",
+ "rustix 1.1.5",
+ "sha2",
+ "smallvec",
+ "tempfile",
+ "thiserror 2.0.21",
+ "tracing",
+ "udev",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-cursor",
+ "wayland-egl",
+ "wayland-protocols",
+ "wayland-protocols-misc",
+ "wayland-protocols-wlr",
+ "wayland-server",
+ "wayland-sys",
+ "winit",
+ "xkbcommon",
+]
+
+[[package]]
+name = "smithay-client-toolkit"
+version = "0.19.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016"
+dependencies = [
+ "bitflags 2.13.2",
+ "calloop 0.13.0",
+ "calloop-wayland-source",
+ "cursor-icon",
+ "libc",
+ "log",
+ "memmap2",
+ "rustix 0.38.44",
+ "thiserror 1.0.69",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-csd-frame",
+ "wayland-cursor",
+ "wayland-protocols",
+ "wayland-protocols-wlr",
+ "wayland-scanner",
+ "xkeysym",
+]
+
+[[package]]
+name = "smithay-drm-extras"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa68109eb23955c216dadb780b0a82e5b0d1dd4b649d4a52b59100eb83a30e96"
+dependencies = [
+ "drm",
+]
+
+[[package]]
+name = "smol_str"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "smol_str"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4aaa7368fcf4852a4c2dd92df0cace6a71f2091ca0a23391ce7f3a31833f1523"
+
+[[package]]
+name = "strict-num"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
+dependencies = [
+ "float-cmp",
+]
+
+[[package]]
+name = "svgtypes"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "695b5790b3131dafa99b3bbfd25a216edb3d216dad9ca208d4657bfb8f2abc3d"
+dependencies = [
+ "kurbo",
+ "siphasher",
+]
+
+[[package]]
+name = "swash"
+version = "0.2.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e"
+dependencies = [
+ "skrifa 0.44.0",
+ "yazi",
+ "zeno",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sys-locale"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "temp-dir"
+version = "0.1.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83176759e9416cf81ee66cb6508dbfe9c96f20b8b56265a39917551c23c70964"
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.3",
+ "once_cell",
+ "rustix 1.1.5",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl 1.0.69",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl 2.0.21",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "thread_local"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "tiny-skia"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"
+dependencies = [
+ "arrayref",
+ "arrayvec",
+ "bytemuck",
+ "cfg-if",
+ "log",
+ "png",
+ "tiny-skia-path",
+]
+
+[[package]]
+name = "tiny-skia-path"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"
+dependencies = [
+ "arrayref",
+ "bytemuck",
+ "strict-num",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
+
+[[package]]
+name = "tokio"
+version = "1.53.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"
+dependencies = [
+ "pin-project-lite",
+]
+
+[[package]]
+name = "toml"
+version = "0.9.12+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
+dependencies = [
+ "indexmap",
+ "serde_core",
+ "serde_spanned",
+ "toml_datetime 0.7.5+spec-1.1.0",
+ "toml_parser",
+ "toml_writer",
+ "winnow 0.7.15",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.7.5+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.25.17+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
+dependencies = [
+ "indexmap",
+ "toml_datetime 1.1.2+spec-1.1.0",
+ "toml_parser",
+ "winnow 1.0.4",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.1.5+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
+dependencies = [
+ "winnow 1.0.4",
+]
+
+[[package]]
+name = "toml_writer"
+version = "1.1.3+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "log",
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+ "valuable",
+]
+
+[[package]]
+name = "tracing-log"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
+dependencies = [
+ "log",
+ "once_cell",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-subscriber"
+version = "0.3.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
+dependencies = [
+ "matchers",
+ "nu-ansi-term",
+ "once_cell",
+ "regex-automata",
+ "sharded-slab",
+ "smallvec",
+ "thread_local",
+ "tracing",
+ "tracing-core",
+ "tracing-log",
+]
+
+[[package]]
+name = "ttf-parser"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
+dependencies = [
+ "core_maths",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "udev"
+version = "0.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af4e37e9ea4401fc841ff54b9ddfc9be1079b1e89434c1a6a865dd68980f7e9f"
+dependencies = [
+ "io-lifetimes",
+ "libc",
+ "libudev-sys",
+ "pkg-config",
+]
+
+[[package]]
+name = "unicase"
+version = "2.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
+
+[[package]]
+name = "unicode-bidi"
+version = "0.3.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "unicode-linebreak"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"
+
+[[package]]
+name = "unicode-script"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
+[[package]]
+name = "unicode-vo"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"
+
+[[package]]
+name = "usvg"
+version = "0.48.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91"
+dependencies = [
+ "base64",
+ "data-url",
+ "flate2",
+ "fontdb 0.24.0",
+ "harfrust 0.12.0",
+ "imagesize",
+ "kurbo",
+ "log",
+ "pico-args",
+ "roxmltree 0.21.1",
+ "simplecss",
+ "siphasher",
+ "skrifa 0.44.0",
+ "strict-num",
+ "svgtypes",
+ "tiny-skia-path",
+ "unicode-bidi",
+ "unicode-script",
+ "unicode-vo",
+ "xmlwriter",
+]
+
+[[package]]
+name = "valuable"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasip2"
+version = "1.0.4+wasi-0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.79"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"
+dependencies = [
+ "js-sys",
+ "tokio",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "wayland-backend"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
+dependencies = [
+ "cc",
+ "downcast-rs",
+ "rustix 1.1.5",
+ "scoped-tls",
+ "smallvec",
+ "wayland-sys",
+]
+
+[[package]]
+name = "wayland-client"
+version = "0.31.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"
+dependencies = [
+ "bitflags 2.13.2",
+ "rustix 1.1.5",
+ "wayland-backend",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-csd-frame"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e"
+dependencies = [
+ "bitflags 2.13.2",
+ "cursor-icon",
+ "wayland-backend",
+]
+
+[[package]]
+name = "wayland-cursor"
+version = "0.31.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"
+dependencies = [
+ "rustix 1.1.5",
+ "wayland-client",
+ "xcursor",
+]
+
+[[package]]
+name = "wayland-egl"
+version = "0.32.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b97bdb7c49e5bd9b7562f38ff84f0dad47079fdc9e926f691a787f6dbc05451"
+dependencies = [
+ "wayland-backend",
+ "wayland-sys",
+]
+
+[[package]]
+name = "wayland-protocols"
+version = "0.32.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-scanner",
+ "wayland-server",
+]
+
+[[package]]
+name = "wayland-protocols-misc"
+version = "0.3.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-protocols",
+ "wayland-scanner",
+ "wayland-server",
+]
+
+[[package]]
+name = "wayland-protocols-plasma"
+version = "0.3.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-protocols-wlr"
+version = "0.3.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
+ "wayland-server",
+]
+
+[[package]]
+name = "wayland-scanner"
+version = "0.31.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
+dependencies = [
+ "proc-macro2",
+ "quick-xml",
+ "quote",
+]
+
+[[package]]
+name = "wayland-server"
+version = "0.31.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75"
+dependencies = [
+ "bitflags 2.13.2",
+ "downcast-rs",
+ "rustix 1.1.5",
+ "wayland-backend",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-sys"
+version = "0.31.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"
+dependencies = [
+ "dlib",
+ "libc",
+ "log",
+ "memoffset",
+ "once_cell",
+ "pkg-config",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
+dependencies = [
+ "windows-targets 0.48.5",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
+dependencies = [
+ "windows_aarch64_gnullvm 0.48.5",
+ "windows_aarch64_msvc 0.48.5",
+ "windows_i686_gnu 0.48.5",
+ "windows_i686_msvc 0.48.5",
+ "windows_x86_64_gnu 0.48.5",
+ "windows_x86_64_gnullvm 0.48.5",
+ "windows_x86_64_msvc 0.48.5",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm",
+ "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_aarch64_gnullvm"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[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_msvc"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "winit"
+version = "0.30.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"
+dependencies = [
+ "ahash",
+ "android-activity",
+ "atomic-waker",
+ "bitflags 2.13.2",
+ "block2",
+ "bytemuck",
+ "calloop 0.13.0",
+ "cfg_aliases",
+ "concurrent-queue",
+ "core-foundation",
+ "core-graphics",
+ "cursor-icon",
+ "dpi",
+ "js-sys",
+ "libc",
+ "memmap2",
+ "ndk",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-foundation",
+ "objc2-ui-kit",
+ "orbclient",
+ "percent-encoding",
+ "pin-project",
+ "raw-window-handle",
+ "redox_syscall 0.4.1",
+ "rustix 0.38.44",
+ "smithay-client-toolkit",
+ "smol_str 0.2.2",
+ "tracing",
+ "unicode-segmentation",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-protocols-plasma",
+ "web-sys",
+ "web-time",
+ "windows-sys 0.52.0",
+ "x11-dl",
+ "x11rb",
+ "xkbcommon-dl",
+]
+
+[[package]]
+name = "winnow"
+version = "0.7.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
+
+[[package]]
+name = "winnow"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "wio"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
+[[package]]
+name = "x11-dl"
+version = "2.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"
+dependencies = [
+ "libc",
+ "once_cell",
+ "pkg-config",
+]
+
+[[package]]
+name = "x11rb"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
+dependencies = [
+ "as-raw-xcb-connection",
+ "gethostname",
+ "libc",
+ "libloading 0.8.9",
+ "once_cell",
+ "rustix 1.1.5",
+ "x11rb-protocol",
+]
+
+[[package]]
+name = "x11rb-protocol"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+
+[[package]]
+name = "xcursor"
+version = "0.3.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"
+
+[[package]]
+name = "xdg"
+version = "2.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "213b7324336b53d2414b2db8537e56544d981803139155afa84f76eeebb7a546"
+
+[[package]]
+name = "xdg"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2fb433233f2df9344722454bc7e96465c9d03bff9d77c248f9e7523fe79585b5"
+
+[[package]]
+name = "xkbcommon"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d66ca9352cbd4eecbbc40871d8a11b4ac8107cfc528a6e14d7c19c69d0e1ac9"
+dependencies = [
+ "libc",
+ "memmap2",
+ "xkeysym",
+]
+
+[[package]]
+name = "xkbcommon-dl"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5"
+dependencies = [
+ "bitflags 2.13.2",
+ "dlib",
+ "log",
+ "once_cell",
+ "xkeysym",
+]
+
+[[package]]
+name = "xkeysym"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
+
+[[package]]
+name = "xml-rs"
+version = "0.8.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
+
+[[package]]
+name = "xmlwriter"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
+
+[[package]]
+name = "yazi"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5"
+
+[[package]]
+name = "zeno"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524"
+
+[[package]]
+name = "zerocopy"
+version = "0.8.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
+
+[[package]]
+name = "zune-core"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]

+ 58 - 0
Cargo.toml

@@ -0,0 +1,58 @@
+[package]
+name = "compositron"
+version = "0.1.0"
+edition = "2021"
+license = "MIT"
+description = "A small Wayland compositor with a searchable application overview"
+
+[features]
+default = ["udev", "winit", "egl"]
+# These features gate internal modules and backend-specific code.
+udev = []
+winit = []
+egl = []
+debug = ["dep:fps_ticker", "dep:renderdoc"]
+# Kept defined so that disabled upstream reference code has valid cfg gates.
+xwayland = []
+x11 = []
+renderer_sync = []
+
+[dependencies]
+smithay = { version = "0.7.0", default-features = false, features = [
+    "backend_drm",
+    "backend_gbm",
+    "backend_libinput",
+    "backend_session_libseat",
+    "backend_udev",
+    "backend_winit",
+    "desktop",
+    "renderer_gl",
+    "renderer_pixman",
+    "renderer_multi",
+    "use_system_lib",
+    "wayland_frontend",
+] }
+smithay-drm-extras = { version = "0.1.0", default-features = false }
+
+bitflags = "2"
+cosmic-text = "0.19"
+freedesktop-desktop-entry = "0.8.3"
+freedesktop-icons = "0.4"
+image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
+profiling = "1"
+resvg = "0.48"
+serde = { version = "1", features = ["derive"] }
+thiserror = "1"
+tiny-skia = "0.12"
+toml = "0.9"
+tracing = { version = "0.1", features = ["max_level_trace", "release_max_level_debug"] }
+tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+usvg = "0.48"
+xkbcommon = "0.8"
+xcursor = "0.3"
+
+fps_ticker = { version = "1.0", optional = true }
+renderdoc = { version = "0.11", optional = true }
+
+[profile.release]
+strip = true

+ 21 - 0
LICENSE

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Compositron contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 21 - 0
LICENSE-Smithay.txt

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Victor Berger and Victoria Brekenfeld
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 55 - 0
Makefile

@@ -0,0 +1,55 @@
+SHELL := /bin/sh
+
+CARGO ?= cargo
+PREFIX ?= /usr/local
+BINDIR ?= $(PREFIX)/bin
+DATADIR ?= $(PREFIX)/share
+WAYLAND_SESSIONS_DIR ?= /usr/share/wayland-sessions
+
+BIN := target/release/compositron
+DESKTOP_FILE := data/compositron.desktop
+
+.PHONY: all build run test fmt clippy install uninstall clean
+
+all: build
+
+build:
+	$(CARGO) build --release
+
+# Run nested inside the current GNOME/Wayland session. This does not take
+# over the seat or the display; it opens Compositron in a normal window.
+run: build
+	@test -n "$$WAYLAND_DISPLAY" || { \
+		echo "No Wayland session detected. Run this from a GNOME Wayland session." >&2; \
+		exit 1; \
+	}
+	@echo "Starting Compositron nested via WAYLAND_DISPLAY=$$WAYLAND_DISPLAY"
+	@echo "The overview opens automatically. In GNOME use Ctrl+Alt+Space to reopen it."
+	exec $(BIN) --winit
+
+test:
+	$(CARGO) test
+
+fmt:
+	$(CARGO) fmt
+
+clippy:
+	$(CARGO) clippy --all-targets -- -D warnings
+
+# Build first, then run "sudo make install".
+install:
+	@test -x $(BIN) || { \
+		echo "$(BIN) is missing; run 'make build' first." >&2; \
+		exit 1; \
+	}
+	install -Dm755 $(BIN) $(DESTDIR)$(BINDIR)/compositron
+	install -Dm644 $(DESKTOP_FILE) $(DESTDIR)$(WAYLAND_SESSIONS_DIR)/compositron.desktop
+	@echo "Installed compositron and its session file."
+
+uninstall:
+	rm -f $(DESTDIR)$(BINDIR)/compositron
+	rm -f $(DESTDIR)$(WAYLAND_SESSIONS_DIR)/compositron.desktop
+	@echo "Removed compositron."
+
+clean:
+	$(CARGO) clean

+ 182 - 0
README.md

@@ -0,0 +1,182 @@
+# Compositron
+
+A small Wayland compositor with a fullscreen, searchable application overview.
+
+Compositron is built on [Smithay](https://github.com/Smithay/smithay) and draws
+its overview directly in the compositor (tiny-skia and cosmic-text), so the
+launcher is not a separate Wayland client.
+
+## Features
+
+- Six fixed virtual desktops.
+- Fullscreen application overview with live filtering.
+- Application catalog from XDG `.desktop` files (including Flatpak exports).
+- Icon theme lookup, SVG/PNG rasterization, and generated fallback icons.
+- Click or press Enter to launch an application.
+- Floating windows with client- or server-side decorations.
+- Move and resize windows by dragging title bars and edges.
+- Focus, raise, maximize, fullscreen, close, and simple window cycling.
+- Layer-shell support for bars, notification daemons, and wallpaper clients.
+- Clipboard, drag and drop, xdg-activation, fractional scale, and popups.
+- Nested `--winit` backend for development inside an existing Wayland session.
+- DRM/libseat/libinput backend for a real session.
+- HiDPI-aware UI: automatic scale detection in the nested backend, and
+  configurable `output_scale` for DRM outputs.
+
+## Requirements
+
+A Wayland-capable Linux system with EGL/GBM, libinput, libseat, and Mesa. On
+Arch Linux:
+
+```sh
+sudo pacman -S --needed base-devel rust pkgconf wayland mesa libinput libseat gbm
+make build
+```
+
+## Running
+
+Development, nested in your current GNOME/Wayland session:
+
+```sh
+make run
+```
+
+This opens Compositron in a normal window and does not take over the seat or
+display. The nested window needs keyboard focus. If it appears on the screen
+but the first frame is missing, click inside it once; this is a
+winit/nested-backend quirk.
+
+GNOME consumes Super and Alt+Tab, so they do not reach a nested compositor.
+Compositron opens with the overview visible in `--winit` mode; after closing
+it, use **Ctrl+Alt+Space** or **Ctrl+Alt+O** to reopen it. GNOME-safe window
+shortcuts are **Ctrl+Shift+Left/Right** (snap), **Ctrl+Shift+Up/Down**
+(maximize/restore), **Ctrl+Shift+1…6** (workspace), and
+**Ctrl+Shift+Alt+1…6** (move window to workspace). Mouse dragging and resizing
+also work normally.
+
+Real session from a TTY:
+
+```sh
+dbus-run-session -- ./target/release/compositron
+```
+
+Or install it as a session so GDM/SDDM can start it:
+
+```sh
+make build
+sudo make install
+```
+
+This installs `/usr/local/bin/compositron` and
+`/usr/share/wayland-sessions/compositron.desktop`. Then log out and choose
+**Compositron** in the display manager.
+
+A wallpaper or bar can be provided by any layer-shell client, for example:
+
+```sh
+swaybg -c '#1b2430'
+```
+
+## Keybindings
+
+| Shortcut | Action |
+|---|---|
+| Super (tap) or Super+Space | Toggle the application overview |
+| Ctrl+Alt+Space / Ctrl+Alt+O | Toggle the overview (nested-mode fallback) |
+| Type / Backspace / Left / Right | Filter and edit the search query |
+| Up / Down / Page Up / Page Down | Move through the app grid |
+| Enter | Launch the selected app |
+| Escape | Close the overview |
+| Wheel | Scroll the app grid |
+| Super+1 … Super+6 | Switch to workspace 1–6 |
+| Super+Shift+1 … Super+Shift+6 | Move the focused window to that workspace |
+| Super+Page Up / Page Down | Previous / next workspace |
+| Super+Left / Right | Snap the focused window to the left/right half |
+| Super+Up | Maximize the focused window |
+| Super+Down | Restore from maximize/fullscreen |
+| Super+F | Toggle fullscreen |
+| Super+Q | Close the focused window |
+| Super+Return | Open the configured terminal |
+| Alt+Tab / Alt+Shift+Tab | Cycle windows |
+| Ctrl+Alt+Left/Right/Up/Down | Alternative snap/maximize/restore shortcuts |
+| Ctrl+Shift+Left/Right | GNOME-safe snap shortcuts |
+| Ctrl+Shift+Up/Down | GNOME-safe maximize/restore shortcuts |
+| Ctrl+Shift+1 … 6 | GNOME-safe workspace shortcuts |
+| Ctrl+Shift+Alt+1 … 6 | GNOME-safe move-window-to-workspace shortcuts |
+| Ctrl+Alt+F | Alternative fullscreen shortcut |
+| Ctrl+Alt+1 … 6 | Alternative workspace shortcuts |
+| Ctrl+Alt+Shift+1 … 6 | Alternative move-window-to-workspace shortcuts |
+| Ctrl+Alt+W | Alternative close-window shortcut |
+| Ctrl+Alt+Return | Alternative terminal shortcut |
+| Ctrl+Alt+Backspace, Super+Shift+Q | Quit the compositor |
+
+A Super tap is detected on release and does not require holding Super. The
+Ctrl+Alt alternatives exist for environments where Super is grabbed by another
+compositor during nested development.
+
+## Configuration
+
+Compositron reads `~/.config/compositron/config.toml` (or
+`$XDG_CONFIG_HOME/compositron/config.toml`). All keys are optional:
+
+```toml
+terminal = "kgx"
+icon_theme = "Adwaita"
+font = "Cantarell"
+output_scale = 2.0
+```
+
+`output_scale` applies to the DRM backend; the nested `--winit` backend uses
+the scale factor reported by GNOME automatically. Scaling is implemented at
+both the output/UI level and through the fractional-scale protocol for apps.
+
+See `config.example.toml`. If no terminal is configured, Compositron tries
+`foot`, `alacritty`, `kgx`, `kitty`, `gnome-terminal`, `xterm`, then
+`weston-terminal`. A terminal must support executing a command for launcher
+entries with `Terminal=true`.
+
+## How the overview works
+
+- `.desktop` files are rescanned every time the overview opens.
+- Visibility follows `NoDisplay`, `Hidden`, `TryExec`, `OnlyShowIn`, and
+  `NotShowIn`. Duplicate visible names are kept only once.
+- `Exec` field codes are expanded; `gio launch` is used as a fallback for
+  D-Bus-activatable entries.
+- Icons are resolved through the configured freedesktop icon theme with a
+  fallback to hicolor, then rasterized and cached in memory.
+- The overview is rendered into a fullscreen premultiplied ARGB buffer and
+  composited above windows but below the cursor.
+
+## Current limitations
+
+- Single output. Hotplug of additional outputs is not supported yet.
+- No XWayland, so X11-only applications will not run.
+- No overview animations or window-preview thumbnails.
+- No lock screen, idle/DPMS management, screenshots, or portal integration.
+- No IME or accessibility support in the search field.
+- Keyboard shortcuts are fixed in this version.
+- The DRM/udev backend must be tested by logging into a real session; the
+  nested `--winit` backend is the supported development path.
+
+## Project layout
+
+```
+src/
+  apps.rs            XDG desktop-entry catalog, filtering, launching
+  config.rs          Optional TOML configuration
+  icons.rs           Icon theme lookup and rasterization
+  text.rs            cosmic-text rendering into tiny-skia pixmaps
+  overview/          Overview layout, rendering, input state
+  workspaces.rs      Six spaces and output mapping
+  shell/             xdg-shell, layer-shell, decorations, grabs
+  render.rs          Output element composition
+  input_handler.rs   Seat input, shortcuts, overview routing
+  state.rs           Global compositor state and protocol handlers
+  winit.rs, udev.rs  Backends
+```
+
+## Credits
+
+The compositor skeleton is adapted from Smithay's MIT-licensed `anvil`
+reference compositor. See `LICENSE-Smithay.txt`. Compositron itself is MIT
+licensed; see `LICENSE`.

+ 17 - 0
config.example.toml

@@ -0,0 +1,17 @@
+# Compositron configuration
+# Copy to ~/.config/compositron/config.toml and uncomment what you need.
+
+# Terminal used for Super+Return and for launcher entries with Terminal=true.
+# If omitted, Compositron auto-detects foot, alacritty, kgx, kitty,
+# gnome-terminal, xterm or weston-terminal.
+#terminal = "kgx"
+
+# Icon theme used by the application overview.
+#icon_theme = "Adwaita"
+
+# Preferred font family for the overview UI.
+#font = "Cantarell"
+
+# DRM output scale. Use 2.0 on HiDPI displays. The nested winit backend
+# detects GNOME's scale factor automatically.
+#output_scale = 2.0

+ 6 - 0
data/compositron.desktop

@@ -0,0 +1,6 @@
+[Desktop Entry]
+Name=Compositron
+Comment=A small Wayland compositor with a searchable application overview
+Exec=dbus-run-session -- compositron
+TryExec=compositron
+Type=Application

BIN
resources/cursor.rgba


BIN
resources/numbers.png


+ 475 - 0
src/apps.rs

@@ -0,0 +1,475 @@
+//! Application catalog built from freedesktop `.desktop` entries.
+
+use std::{
+    collections::HashSet,
+    env,
+    path::{Path, PathBuf},
+    process::Command,
+};
+
+use freedesktop_desktop_entry::{get_languages_from_env, DesktopEntry, Iter};
+use tracing::debug;
+
+/// A runnable application from a desktop entry.
+#[derive(Debug, Clone)]
+pub struct AppEntry {
+    pub id: String,
+    pub name: String,
+    pub generic_name: Option<String>,
+    pub keywords: Vec<String>,
+    pub comment: Option<String>,
+    pub icon: Option<String>,
+    pub desktop_path: PathBuf,
+    pub exec: Option<Vec<String>>,
+    pub terminal: bool,
+    pub dbus_activatable: bool,
+    pub working_dir: Option<PathBuf>,
+}
+
+impl AppEntry {
+    fn searchable_name(&self) -> String {
+        self.name.to_lowercase()
+    }
+}
+
+#[derive(Debug, Default)]
+pub struct AppCatalog {
+    apps: Vec<AppEntry>,
+}
+
+impl AppCatalog {
+    /// Load all visible applications from XDG data directories.
+    pub fn load() -> Self {
+        let locales = get_languages_from_env();
+        let mut entries = freedesktop_desktop_entry::desktop_entries(&locales);
+
+        // `xdg` only includes Flatpak exports when they are present in
+        // XDG_DATA_DIRS, which is not guaranteed for hand-started sessions.
+        let mut extra_dirs = Vec::new();
+        if let Some(home) = env::var_os("HOME") {
+            extra_dirs
+                .push(PathBuf::from(home).join(".local/share/flatpak/exports/share/applications"));
+        }
+        extra_dirs.push(PathBuf::from("/var/lib/flatpak/exports/share/applications"));
+        entries.extend(Iter::new(extra_dirs.into_iter()).entries(Some(&locales)));
+
+        let desktops = current_desktops();
+        let mut seen_ids = HashSet::new();
+        let mut seen_names = HashSet::new();
+        let mut apps = Vec::new();
+
+        for entry in entries {
+            if !is_visible(&entry, &desktops) {
+                continue;
+            }
+
+            let Some(name) = entry
+                .name(&locales)
+                .map(|name| name.trim().to_string())
+                .filter(|name| !name.is_empty())
+            else {
+                continue;
+            };
+
+            let id = entry.id().to_string();
+            if id.is_empty() || !seen_ids.insert(id.clone()) {
+                continue;
+            }
+            // Some desktops ship two entries with the same visible name
+            // (for example GNOME and KDE variants). A launcher grid cannot
+            // distinguish them, so keep the first one.
+            if !seen_names.insert(name.to_lowercase()) {
+                continue;
+            }
+
+            let exec = entry
+                .parse_exec_with_uris(&[], &locales)
+                .ok()
+                .filter(|argv| !argv.is_empty());
+            if exec.is_none() && !entry.dbus_activatable() {
+                debug!(id, "skipping entry without a runnable Exec line");
+                continue;
+            }
+
+            let keywords = entry
+                .keywords(&locales)
+                .unwrap_or_default()
+                .into_iter()
+                .map(|word| word.to_string())
+                .collect();
+
+            apps.push(AppEntry {
+                id,
+                name,
+                generic_name: entry.generic_name(&locales).map(|name| name.to_string()),
+                keywords,
+                comment: entry.comment(&locales).map(|comment| comment.to_string()),
+                icon: entry.icon().map(str::to_string),
+                desktop_path: entry.path.clone(),
+                exec,
+                terminal: entry.terminal(),
+                dbus_activatable: entry.dbus_activatable(),
+                working_dir: entry.path().map(PathBuf::from),
+            });
+        }
+
+        apps.sort_by(|a, b| {
+            a.searchable_name()
+                .cmp(&b.searchable_name())
+                .then_with(|| a.id.cmp(&b.id))
+        });
+
+        debug!(count = apps.len(), "loaded application catalog");
+        Self { apps }
+    }
+
+    pub fn apps(&self) -> &[AppEntry] {
+        &self.apps
+    }
+
+    pub fn len(&self) -> usize {
+        self.apps.len()
+    }
+
+    pub fn is_empty(&self) -> bool {
+        self.apps.is_empty()
+    }
+
+    pub fn get(&self, index: usize) -> Option<&AppEntry> {
+        self.apps.get(index)
+    }
+
+    /// Return indices into the catalog, ordered by match quality and name.
+    pub fn filter(&self, query: &str) -> Vec<usize> {
+        let query = query.trim().to_lowercase();
+        if query.is_empty() {
+            return (0..self.apps.len()).collect();
+        }
+
+        let mut matches = Vec::new();
+        for (index, app) in self.apps.iter().enumerate() {
+            if let Some(score) = match_score(app, &query) {
+                matches.push((score, index));
+            }
+        }
+
+        // Only fall back to fuzzy matching when nothing matches normally.
+        // Otherwise a short query like "fir" shows most of the catalog.
+        if matches.is_empty() && query.chars().count() >= 3 {
+            for (index, app) in self.apps.iter().enumerate() {
+                if fuzzy_match(&app.searchable_name(), &query) {
+                    matches.push((6, index));
+                }
+            }
+        }
+
+        matches.sort_by(|(score_a, index_a), (score_b, index_b)| {
+            score_a
+                .cmp(score_b)
+                .then_with(|| self.apps[*index_a].id.cmp(&self.apps[*index_b].id))
+        });
+        matches.into_iter().map(|(_, index)| index).collect()
+    }
+}
+
+fn current_desktops() -> Vec<String> {
+    let mut desktops = vec!["Compositron".to_string()];
+    if let Ok(value) = env::var("XDG_CURRENT_DESKTOP") {
+        for desktop in value.split(':') {
+            let desktop = desktop.trim();
+            if !desktop.is_empty() && !desktops.iter().any(|known| known == desktop) {
+                desktops.push(desktop.to_string());
+            }
+        }
+    }
+    desktops
+}
+
+fn is_visible(entry: &DesktopEntry, desktops: &[String]) -> bool {
+    if entry.no_display() || entry.hidden() {
+        return false;
+    }
+    if let Some(kind) = entry.type_() {
+        if kind != "Application" {
+            return false;
+        }
+    }
+
+    let matches_desktop = |list: &[&str]| {
+        list.iter()
+            .any(|item| desktops.iter().any(|desktop| desktop == item))
+    };
+
+    if let Some(only) = entry.only_show_in() {
+        if !only.is_empty() && !matches_desktop(&only) {
+            return false;
+        }
+    }
+    if let Some(not) = entry.not_show_in() {
+        if matches_desktop(&not) {
+            return false;
+        }
+    }
+
+    if let Some(try_exec) = entry.try_exec() {
+        let try_exec = try_exec.trim();
+        if !try_exec.is_empty() && !executable_in_path(try_exec) {
+            return false;
+        }
+    }
+
+    true
+}
+
+fn executable_in_path(program: &str) -> bool {
+    let path = Path::new(program);
+    if path.is_absolute() || program.contains('/') {
+        return path.is_file();
+    }
+    env::var_os("PATH")
+        .map(|paths| {
+            env::split_paths(&paths).any(|dir| {
+                let candidate = dir.join(program);
+                candidate.is_file()
+            })
+        })
+        .unwrap_or(false)
+}
+
+fn match_score(app: &AppEntry, query: &str) -> Option<u8> {
+    let name = app.searchable_name();
+    if name == query {
+        return Some(0);
+    }
+    if name.starts_with(query) {
+        return Some(1);
+    }
+    if name
+        .split(|character: char| !character.is_alphanumeric())
+        .any(|word| word.starts_with(query))
+    {
+        return Some(2);
+    }
+    if name.contains(query) {
+        return Some(3);
+    }
+
+    let metadata_match = app
+        .generic_name
+        .as_deref()
+        .map(str::to_lowercase)
+        .into_iter()
+        .chain(app.comment.as_deref().map(str::to_lowercase))
+        .chain(app.keywords.iter().map(|keyword| keyword.to_lowercase()))
+        .any(|text| text.contains(query));
+    if metadata_match {
+        return Some(4);
+    }
+
+    if app
+        .exec
+        .as_ref()
+        .map(|argv| argv.iter().any(|arg| arg.to_lowercase().contains(query)))
+        .unwrap_or(false)
+    {
+        return Some(5);
+    }
+
+    None
+}
+
+fn fuzzy_match(name: &str, query: &str) -> bool {
+    let mut chars = name.chars();
+    query
+        .chars()
+        .all(|query_char| chars.any(|name_char| name_char == query_char))
+}
+
+/// A terminal command that can run a command inside a pty.
+#[derive(Debug, Clone)]
+pub struct Terminal {
+    /// The command used to open an interactive terminal.
+    pub command: Vec<String>,
+    /// Arguments used before the command to execute, if supported.
+    pub exec_prefix: Vec<String>,
+}
+
+impl Terminal {
+    pub fn detect(preferred: Option<&str>) -> Self {
+        if let Some(preferred) = preferred {
+            let command = split_command(preferred);
+            if !command.is_empty() {
+                let exec_prefix = terminal_exec_prefix(&command[0]);
+                return Self {
+                    command,
+                    exec_prefix,
+                };
+            }
+        }
+
+        for candidate in [
+            "foot",
+            "alacritty",
+            "kgx",
+            "kitty",
+            "gnome-terminal",
+            "xterm",
+            "weston-terminal",
+        ] {
+            if executable_in_path(candidate) {
+                return Self {
+                    command: vec![candidate.to_string()],
+                    exec_prefix: terminal_exec_prefix(candidate),
+                };
+            }
+        }
+
+        Self {
+            command: vec!["weston-terminal".to_string()],
+            exec_prefix: Vec::new(),
+        }
+    }
+
+    /// Build argv for launching `command` in this terminal.
+    pub fn wrap(&self, command: &[String]) -> Option<Vec<String>> {
+        if command.is_empty() || self.exec_prefix.is_empty() {
+            return None;
+        }
+        let mut argv = self.command.clone();
+        argv.extend(self.exec_prefix.iter().cloned());
+        argv.extend(command.iter().cloned());
+        Some(argv)
+    }
+}
+
+fn terminal_exec_prefix(program: &str) -> Vec<String> {
+    match program {
+        "foot" | "alacritty" | "xterm" => vec!["-e".into()],
+        "kgx" => vec!["-e".into()],
+        "gnome-terminal" => vec!["--".into()],
+        // weston-terminal has no execute-command option.
+        _ => Vec::new(),
+    }
+}
+
+fn split_command(command: &str) -> Vec<String> {
+    command
+        .split_ascii_whitespace()
+        .map(str::to_string)
+        .collect()
+}
+
+pub fn launch(
+    app: &AppEntry,
+    terminal: &Terminal,
+    wayland_display: Option<&str>,
+) -> Result<(), String> {
+    if app.terminal {
+        let Some(command) = app.exec.as_ref() else {
+            return Err("This application needs a terminal, but has no Exec line".into());
+        };
+        let Some(argv) = terminal.wrap(command) else {
+            return Err(format!(
+                "This application needs a terminal that can execute commands, but '{}' cannot",
+                terminal.command.first().cloned().unwrap_or_default()
+            ));
+        };
+        spawn(&argv, app.working_dir.as_deref(), wayland_display).map_err(|err| err.to_string())
+    } else if let Some(command) = app.exec.as_ref() {
+        spawn(command, app.working_dir.as_deref(), wayland_display).map_err(|err| err.to_string())
+    } else if app.dbus_activatable {
+        let status = launch_command("gio", wayland_display)
+            .arg("launch")
+            .arg(&app.desktop_path)
+            .spawn()
+            .map_err(|err| format!("Could not start gio: {err}"))?;
+        debug!(id = app.id, pid = status.id(), "launched via gio");
+        Ok(())
+    } else {
+        Err("No Exec line or D-Bus activation method available".into())
+    }
+}
+
+fn launch_command(program: &str, wayland_display: Option<&str>) -> Command {
+    let mut command = Command::new(program);
+    command
+        .env("XDG_SESSION_TYPE", "wayland")
+        .env("XDG_CURRENT_DESKTOP", "Compositron")
+        .env_remove("DISPLAY");
+    if let Some(display) = wayland_display {
+        command.env("WAYLAND_DISPLAY", display);
+    }
+    command
+}
+
+fn spawn(
+    argv: &[String],
+    working_dir: Option<&Path>,
+    wayland_display: Option<&str>,
+) -> std::io::Result<()> {
+    let Some(program) = argv.first() else {
+        return Err(std::io::Error::new(
+            std::io::ErrorKind::InvalidInput,
+            "empty command",
+        ));
+    };
+    let mut command = launch_command(program, wayland_display);
+    command.args(&argv[1..]);
+    if let Some(dir) = working_dir {
+        command.current_dir(dir);
+    }
+    let mut child = command.spawn()?;
+    debug!(program, pid = child.id(), "launched application");
+    // Reap later without blocking the compositor. Short-lived launchers like
+    // `gio` exit immediately, so this avoids zombies without an async runtime.
+    std::thread::spawn(move || {
+        let _ = child.wait();
+    });
+    Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn app(name: &str) -> AppEntry {
+        AppEntry {
+            id: name.to_lowercase(),
+            name: name.into(),
+            generic_name: None,
+            keywords: Vec::new(),
+            comment: None,
+            icon: None,
+            desktop_path: PathBuf::new(),
+            exec: Some(vec!["true".into()]),
+            terminal: false,
+            dbus_activatable: false,
+            working_dir: None,
+        }
+    }
+
+    #[test]
+    fn filter_ranks_prefix_before_substring() {
+        let catalog = AppCatalog {
+            apps: vec![app("Files"), app("Firefox"), app("Profile Editor")],
+        };
+        let matches = catalog.filter("fi");
+        assert_eq!(matches, vec![0, 1, 2]);
+    }
+
+    #[test]
+    fn fuzzy_filter_matches_typo() {
+        let catalog = AppCatalog {
+            apps: vec![app("Firefox"), app("Terminal")],
+        };
+        assert_eq!(catalog.filter("firfox"), vec![0]);
+    }
+
+    #[test]
+    fn empty_query_returns_everything() {
+        let catalog = AppCatalog {
+            apps: vec![app("A"), app("B")],
+        };
+        assert_eq!(catalog.filter(""), vec![0, 1]);
+    }
+}

+ 69 - 0
src/config.rs

@@ -0,0 +1,69 @@
+//! Minimal configuration file support.
+
+use std::{env, fs, path::PathBuf};
+
+use serde::Deserialize;
+use tracing::{info, warn};
+
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(default)]
+pub struct Config {
+    /// Terminal used for `Terminal=true` desktop entries and Super+Return.
+    pub terminal: Option<String>,
+    /// Icon theme name, for example "Adwaita".
+    pub icon_theme: Option<String>,
+    /// Preferred font family for the overview UI.
+    pub font: Option<String>,
+    /// Scale factor for DRM outputs (1.0 = normal, 2.0 = HiDPI).
+    pub output_scale: Option<f64>,
+}
+
+impl Config {
+    pub fn load() -> Self {
+        let Some(path) = config_path() else {
+            return Self::default();
+        };
+        match fs::read_to_string(&path) {
+            Ok(contents) => match toml::from_str::<Config>(&contents) {
+                Ok(config) => {
+                    info!(?path, "loaded configuration");
+                    config
+                }
+                Err(err) => {
+                    warn!(?path, %err, "invalid configuration; using defaults");
+                    Self::default()
+                }
+            },
+            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Self::default(),
+            Err(err) => {
+                warn!(?path, %err, "could not read configuration; using defaults");
+                Self::default()
+            }
+        }
+    }
+
+    pub fn icon_theme(&self) -> String {
+        self.icon_theme
+            .clone()
+            .unwrap_or_else(|| "Adwaita".to_string())
+    }
+
+    pub fn font(&self) -> Option<String> {
+        self.font.clone()
+    }
+
+    pub fn terminal(&self) -> Option<&str> {
+        self.terminal.as_deref()
+    }
+
+    pub fn output_scale(&self) -> f64 {
+        self.output_scale.unwrap_or(1.0).clamp(1.0, 4.0)
+    }
+}
+
+fn config_path() -> Option<PathBuf> {
+    if let Some(config_home) = env::var_os("XDG_CONFIG_HOME") {
+        return Some(PathBuf::from(config_home).join("compositron/config.toml"));
+    }
+    env::var_os("HOME").map(|home| PathBuf::from(home).join(".config/compositron/config.toml"))
+}

+ 96 - 0
src/cursor.rs

@@ -0,0 +1,96 @@
+use std::{io::Read, time::Duration};
+
+use tracing::warn;
+use xcursor::{
+    parser::{parse_xcursor, Image},
+    CursorTheme,
+};
+
+static FALLBACK_CURSOR_DATA: &[u8] = include_bytes!("../resources/cursor.rgba");
+
+pub struct Cursor {
+    icons: Vec<Image>,
+    size: u32,
+}
+
+impl Cursor {
+    pub fn load() -> Cursor {
+        let name = std::env::var("XCURSOR_THEME")
+            .ok()
+            .unwrap_or_else(|| "default".into());
+        let size = std::env::var("XCURSOR_SIZE")
+            .ok()
+            .and_then(|s| s.parse().ok())
+            .unwrap_or(24);
+
+        let theme = CursorTheme::load(&name);
+        let icons = load_icon(&theme)
+            .map_err(|err| warn!("Unable to load xcursor: {}, using fallback cursor", err))
+            .unwrap_or_else(|_| {
+                vec![Image {
+                    size: 32,
+                    width: 64,
+                    height: 64,
+                    xhot: 1,
+                    yhot: 1,
+                    delay: 1,
+                    pixels_rgba: Vec::from(FALLBACK_CURSOR_DATA),
+                    pixels_argb: vec![], //unused
+                }]
+            });
+
+        Cursor { icons, size }
+    }
+
+    pub fn get_image(&self, scale: u32, time: Duration) -> Image {
+        let size = self.size * scale;
+        frame(time.as_millis() as u32, size, &self.icons)
+    }
+}
+
+fn nearest_images(size: u32, images: &[Image]) -> impl Iterator<Item = &Image> {
+    // Follow the nominal size of the cursor to choose the nearest
+    let nearest_image = images
+        .iter()
+        .min_by_key(|image| (size as i32 - image.size as i32).abs())
+        .unwrap();
+
+    images.iter().filter(move |image| {
+        image.width == nearest_image.width && image.height == nearest_image.height
+    })
+}
+
+fn frame(mut millis: u32, size: u32, images: &[Image]) -> Image {
+    let total = nearest_images(size, images).fold(0, |acc, image| acc + image.delay);
+    if total == 0 {
+        return nearest_images(size, images).next().unwrap().clone();
+    }
+    millis %= total;
+
+    for img in nearest_images(size, images) {
+        if millis < img.delay {
+            return img.clone();
+        }
+        millis -= img.delay;
+    }
+
+    unreachable!()
+}
+
+#[derive(thiserror::Error, Debug)]
+enum Error {
+    #[error("Theme has no default cursor")]
+    NoDefaultCursor,
+    #[error("Error opening xcursor file: {0}")]
+    File(#[from] std::io::Error),
+    #[error("Failed to parse XCursor file")]
+    Parse,
+}
+
+fn load_icon(theme: &CursorTheme) -> Result<Vec<Image>, Error> {
+    let icon_path = theme.load_icon("default").ok_or(Error::NoDefaultCursor)?;
+    let mut cursor_file = std::fs::File::open(icon_path)?;
+    let mut cursor_data = Vec::new();
+    cursor_file.read_to_end(&mut cursor_data)?;
+    parse_xcursor(&cursor_data).ok_or(Error::Parse)
+}

+ 259 - 0
src/drawing.rs

@@ -0,0 +1,259 @@
+#![allow(clippy::too_many_arguments)]
+
+use smithay::{
+    backend::renderer::{
+        element::{
+            memory::{MemoryRenderBuffer, MemoryRenderBufferRenderElement},
+            surface::WaylandSurfaceRenderElement,
+            AsRenderElements, Kind,
+        },
+        Color32F, ImportAll, ImportMem, Renderer, Texture,
+    },
+    input::pointer::CursorImageStatus,
+    render_elements,
+    utils::{Physical, Point, Scale},
+};
+#[cfg(feature = "debug")]
+use smithay::{
+    backend::renderer::{
+        element::{Element, Id, RenderElement},
+        utils::CommitCounter,
+        Frame,
+    },
+    utils::{Buffer, Logical, Rectangle, Size, Transform},
+};
+
+pub static CLEAR_COLOR: Color32F = Color32F::new(0.045, 0.05, 0.065, 1.0);
+pub static CLEAR_COLOR_FULLSCREEN: Color32F = Color32F::new(0.0, 0.0, 0.0, 0.0);
+
+pub struct PointerElement {
+    buffer: Option<MemoryRenderBuffer>,
+    status: CursorImageStatus,
+}
+
+impl Default for PointerElement {
+    fn default() -> Self {
+        Self {
+            buffer: Default::default(),
+            status: CursorImageStatus::default_named(),
+        }
+    }
+}
+
+impl PointerElement {
+    pub fn set_status(&mut self, status: CursorImageStatus) {
+        self.status = status;
+    }
+
+    pub fn set_buffer(&mut self, buffer: MemoryRenderBuffer) {
+        self.buffer = Some(buffer);
+    }
+}
+
+render_elements! {
+    pub PointerRenderElement<R> where R: ImportAll + ImportMem;
+    Surface=WaylandSurfaceRenderElement<R>,
+    Memory=MemoryRenderBufferRenderElement<R>,
+}
+
+impl<R: Renderer> std::fmt::Debug for PointerRenderElement<R> {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            Self::Surface(arg0) => f.debug_tuple("Surface").field(arg0).finish(),
+            Self::Memory(arg0) => f.debug_tuple("Memory").field(arg0).finish(),
+            Self::_GenericCatcher(arg0) => f.debug_tuple("_GenericCatcher").field(arg0).finish(),
+        }
+    }
+}
+
+impl<T: Texture + Clone + Send + 'static, R> AsRenderElements<R> for PointerElement
+where
+    R: Renderer<TextureId = T> + ImportAll + ImportMem,
+{
+    type RenderElement = PointerRenderElement<R>;
+    fn render_elements<E>(
+        &self,
+        renderer: &mut R,
+        location: Point<i32, Physical>,
+        scale: Scale<f64>,
+        alpha: f32,
+    ) -> Vec<E>
+    where
+        E: From<PointerRenderElement<R>>,
+    {
+        match &self.status {
+            CursorImageStatus::Hidden => vec![],
+            // Always render `Default` for a named shape.
+            CursorImageStatus::Named(_) => {
+                if let Some(buffer) = self.buffer.as_ref() {
+                    vec![PointerRenderElement::<R>::from(
+                        MemoryRenderBufferRenderElement::from_buffer(
+                            renderer,
+                            location.to_f64(),
+                            buffer,
+                            None,
+                            None,
+                            None,
+                            Kind::Cursor,
+                        )
+                        .expect("Lost system pointer buffer"),
+                    )
+                    .into()]
+                } else {
+                    vec![]
+                }
+            }
+            CursorImageStatus::Surface(surface) => {
+                let elements: Vec<PointerRenderElement<R>> =
+                    smithay::backend::renderer::element::surface::render_elements_from_surface_tree(
+                        renderer,
+                        surface,
+                        location,
+                        scale,
+                        alpha,
+                        Kind::Cursor,
+                    );
+                elements.into_iter().map(E::from).collect()
+            }
+        }
+    }
+}
+
+#[cfg(feature = "debug")]
+pub static FPS_NUMBERS_PNG: &[u8] = include_bytes!("../resources/numbers.png");
+
+#[cfg(feature = "debug")]
+#[derive(Debug, Clone)]
+pub struct FpsElement<T: Texture> {
+    id: Id,
+    value: u32,
+    texture: T,
+    commit_counter: CommitCounter,
+}
+
+#[cfg(feature = "debug")]
+impl<T: Texture> FpsElement<T> {
+    pub fn new(texture: T) -> Self {
+        FpsElement {
+            id: Id::new(),
+            texture,
+            value: 0,
+            commit_counter: CommitCounter::default(),
+        }
+    }
+
+    pub fn update_fps(&mut self, fps: u32) {
+        if self.value != fps {
+            self.value = fps;
+            self.commit_counter.increment();
+        }
+    }
+}
+
+#[cfg(feature = "debug")]
+impl<T> Element for FpsElement<T>
+where
+    T: Texture + 'static,
+{
+    fn id(&self) -> &Id {
+        &self.id
+    }
+
+    fn location(&self, _scale: Scale<f64>) -> Point<i32, Physical> {
+        (0, 0).into()
+    }
+
+    fn src(&self) -> Rectangle<f64, Buffer> {
+        let digits = if self.value < 10 {
+            1
+        } else if self.value < 100 {
+            2
+        } else {
+            3
+        };
+        Rectangle::from_size((24 * digits, 35).into()).to_f64()
+    }
+
+    fn geometry(&self, scale: Scale<f64>) -> Rectangle<i32, Physical> {
+        let digits = if self.value < 10 {
+            1
+        } else if self.value < 100 {
+            2
+        } else {
+            3
+        };
+        Rectangle::from_size((24 * digits, 35).into()).to_physical_precise_round(scale)
+    }
+
+    fn current_commit(&self) -> CommitCounter {
+        self.commit_counter
+    }
+}
+
+#[cfg(feature = "debug")]
+impl<R> RenderElement<R> for FpsElement<R::TextureId>
+where
+    R: Renderer + ImportAll,
+    R::TextureId: 'static,
+{
+    fn draw(
+        &self,
+        frame: &mut R::Frame<'_, '_>,
+        _src: Rectangle<f64, Buffer>,
+        dst: Rectangle<i32, Physical>,
+        damage: &[Rectangle<i32, Physical>],
+        _opaque_regions: &[Rectangle<i32, Physical>],
+    ) -> Result<(), R::Error> {
+        // FIXME: respect the src for cropping
+        let scale = dst.size.to_f64() / self.src().size;
+        let value_str = std::cmp::min(self.value, 999).to_string();
+        let mut offset: Point<f64, Physical> = Point::from((0.0, 0.0));
+        for digit in value_str.chars().map(|d| d.to_digit(10).unwrap()) {
+            let digit_location = dst.loc.to_f64() + offset;
+            let digit_size = Size::<i32, Logical>::from((22, 35))
+                .to_f64()
+                .to_physical(scale);
+            let dst = Rectangle::new(
+                digit_location.to_i32_round(),
+                ((digit_size.to_point() + digit_location).to_i32_round()
+                    - digit_location.to_i32_round())
+                .to_size(),
+            );
+            let damage = damage
+                .iter()
+                .cloned()
+                .flat_map(|x| x.intersection(dst))
+                .map(|mut x| {
+                    x.loc -= dst.loc;
+                    x
+                })
+                .collect::<Vec<_>>();
+            let texture_src: Rectangle<i32, Buffer> = match digit {
+                9 => Rectangle::from_size((22, 35).into()),
+                6 => Rectangle::new((22, 0).into(), (22, 35).into()),
+                3 => Rectangle::new((44, 0).into(), (22, 35).into()),
+                1 => Rectangle::new((66, 0).into(), (22, 35).into()),
+                8 => Rectangle::new((0, 35).into(), (22, 35).into()),
+                0 => Rectangle::new((22, 35).into(), (22, 35).into()),
+                2 => Rectangle::new((44, 35).into(), (22, 35).into()),
+                7 => Rectangle::new((0, 70).into(), (22, 35).into()),
+                4 => Rectangle::new((22, 70).into(), (22, 35).into()),
+                5 => Rectangle::new((44, 70).into(), (22, 35).into()),
+                _ => unreachable!(),
+            };
+
+            frame.render_texture_from_to(
+                &self.texture,
+                texture_src.to_f64(),
+                dst,
+                &damage,
+                &[],
+                Transform::Normal,
+                1.0,
+            )?;
+            offset += Point::from((24.0, 0.0)).to_physical(scale);
+        }
+
+        Ok(())
+    }
+}

+ 629 - 0
src/focus.rs

@@ -0,0 +1,629 @@
+use std::borrow::Cow;
+
+#[cfg(feature = "xwayland")]
+use smithay::xwayland::X11Surface;
+pub use smithay::{
+    backend::input::KeyState,
+    desktop::{LayerSurface, PopupKind},
+    input::{
+        keyboard::{KeyboardTarget, KeysymHandle, ModifiersState},
+        pointer::{AxisFrame, ButtonEvent, MotionEvent, PointerTarget, RelativeMotionEvent},
+        Seat,
+    },
+    reexports::wayland_server::{backend::ObjectId, protocol::wl_surface::WlSurface, Resource},
+    utils::{IsAlive, Serial},
+    wayland::seat::WaylandFocus,
+};
+use smithay::{
+    desktop::{Window, WindowSurface},
+    input::{
+        pointer::{
+            GestureHoldBeginEvent, GestureHoldEndEvent, GesturePinchBeginEvent,
+            GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent,
+            GestureSwipeEndEvent, GestureSwipeUpdateEvent,
+        },
+        touch::TouchTarget,
+    },
+};
+
+use crate::{
+    shell::{WindowElement, SSD},
+    state::{Backend, CompositronState},
+};
+
+#[derive(Debug, Clone, PartialEq)]
+#[allow(clippy::large_enum_variant)]
+pub enum KeyboardFocusTarget {
+    Window(Window),
+    LayerSurface(LayerSurface),
+    Popup(PopupKind),
+}
+
+impl IsAlive for KeyboardFocusTarget {
+    #[inline]
+    fn alive(&self) -> bool {
+        match self {
+            KeyboardFocusTarget::Window(w) => w.alive(),
+            KeyboardFocusTarget::LayerSurface(l) => l.alive(),
+            KeyboardFocusTarget::Popup(p) => p.alive(),
+        }
+    }
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum PointerFocusTarget {
+    WlSurface(WlSurface),
+    #[cfg(feature = "xwayland")]
+    X11Surface(X11Surface),
+    SSD(SSD),
+}
+
+impl IsAlive for PointerFocusTarget {
+    #[inline]
+    fn alive(&self) -> bool {
+        match self {
+            PointerFocusTarget::WlSurface(w) => w.alive(),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => w.alive(),
+            PointerFocusTarget::SSD(x) => x.alive(),
+        }
+    }
+}
+
+impl From<PointerFocusTarget> for WlSurface {
+    #[inline]
+    fn from(target: PointerFocusTarget) -> Self {
+        target.wl_surface().unwrap().into_owned()
+    }
+}
+
+impl<BackendData: Backend> PointerTarget<CompositronState<BackendData>> for PointerFocusTarget {
+    fn enter(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &MotionEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => PointerTarget::enter(w, seat, data, event),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => PointerTarget::enter(w, seat, data, event),
+            PointerFocusTarget::SSD(w) => PointerTarget::enter(w, seat, data, event),
+        }
+    }
+    fn motion(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &MotionEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => PointerTarget::motion(w, seat, data, event),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => PointerTarget::motion(w, seat, data, event),
+            PointerFocusTarget::SSD(w) => PointerTarget::motion(w, seat, data, event),
+        }
+    }
+    fn relative_motion(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &RelativeMotionEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => {
+                PointerTarget::relative_motion(w, seat, data, event)
+            }
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => {
+                PointerTarget::relative_motion(w, seat, data, event)
+            }
+            PointerFocusTarget::SSD(w) => PointerTarget::relative_motion(w, seat, data, event),
+        }
+    }
+    fn button(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &ButtonEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => PointerTarget::button(w, seat, data, event),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => PointerTarget::button(w, seat, data, event),
+            PointerFocusTarget::SSD(w) => PointerTarget::button(w, seat, data, event),
+        }
+    }
+    fn axis(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        frame: AxisFrame,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => PointerTarget::axis(w, seat, data, frame),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => PointerTarget::axis(w, seat, data, frame),
+            PointerFocusTarget::SSD(w) => PointerTarget::axis(w, seat, data, frame),
+        }
+    }
+    fn frame(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => PointerTarget::frame(w, seat, data),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => PointerTarget::frame(w, seat, data),
+            PointerFocusTarget::SSD(w) => PointerTarget::frame(w, seat, data),
+        }
+    }
+    fn leave(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        serial: Serial,
+        time: u32,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => PointerTarget::leave(w, seat, data, serial, time),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => PointerTarget::leave(w, seat, data, serial, time),
+            PointerFocusTarget::SSD(w) => PointerTarget::leave(w, seat, data, serial, time),
+        }
+    }
+    fn gesture_swipe_begin(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &GestureSwipeBeginEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => {
+                PointerTarget::gesture_swipe_begin(w, seat, data, event)
+            }
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => {
+                PointerTarget::gesture_swipe_begin(w, seat, data, event)
+            }
+            PointerFocusTarget::SSD(w) => PointerTarget::gesture_swipe_begin(w, seat, data, event),
+        }
+    }
+    fn gesture_swipe_update(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &GestureSwipeUpdateEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => {
+                PointerTarget::gesture_swipe_update(w, seat, data, event)
+            }
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => {
+                PointerTarget::gesture_swipe_update(w, seat, data, event)
+            }
+            PointerFocusTarget::SSD(w) => PointerTarget::gesture_swipe_update(w, seat, data, event),
+        }
+    }
+    fn gesture_swipe_end(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &GestureSwipeEndEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => {
+                PointerTarget::gesture_swipe_end(w, seat, data, event)
+            }
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => {
+                PointerTarget::gesture_swipe_end(w, seat, data, event)
+            }
+            PointerFocusTarget::SSD(w) => PointerTarget::gesture_swipe_end(w, seat, data, event),
+        }
+    }
+    fn gesture_pinch_begin(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &GesturePinchBeginEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => {
+                PointerTarget::gesture_pinch_begin(w, seat, data, event)
+            }
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => {
+                PointerTarget::gesture_pinch_begin(w, seat, data, event)
+            }
+            PointerFocusTarget::SSD(w) => PointerTarget::gesture_pinch_begin(w, seat, data, event),
+        }
+    }
+    fn gesture_pinch_update(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &GesturePinchUpdateEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => {
+                PointerTarget::gesture_pinch_update(w, seat, data, event)
+            }
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => {
+                PointerTarget::gesture_pinch_update(w, seat, data, event)
+            }
+            PointerFocusTarget::SSD(w) => PointerTarget::gesture_pinch_update(w, seat, data, event),
+        }
+    }
+    fn gesture_pinch_end(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &GesturePinchEndEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => {
+                PointerTarget::gesture_pinch_end(w, seat, data, event)
+            }
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => {
+                PointerTarget::gesture_pinch_end(w, seat, data, event)
+            }
+            PointerFocusTarget::SSD(w) => PointerTarget::gesture_pinch_end(w, seat, data, event),
+        }
+    }
+    fn gesture_hold_begin(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &GestureHoldBeginEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => {
+                PointerTarget::gesture_hold_begin(w, seat, data, event)
+            }
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => {
+                PointerTarget::gesture_hold_begin(w, seat, data, event)
+            }
+            PointerFocusTarget::SSD(w) => PointerTarget::gesture_hold_begin(w, seat, data, event),
+        }
+    }
+    fn gesture_hold_end(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &GestureHoldEndEvent,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => {
+                PointerTarget::gesture_hold_end(w, seat, data, event)
+            }
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => {
+                PointerTarget::gesture_hold_end(w, seat, data, event)
+            }
+            PointerFocusTarget::SSD(w) => PointerTarget::gesture_hold_end(w, seat, data, event),
+        }
+    }
+}
+
+impl<BackendData: Backend> KeyboardTarget<CompositronState<BackendData>> for KeyboardFocusTarget {
+    fn enter(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        keys: Vec<KeysymHandle<'_>>,
+        serial: Serial,
+    ) {
+        match self {
+            KeyboardFocusTarget::Window(w) => match w.underlying_surface() {
+                WindowSurface::Wayland(w) => {
+                    KeyboardTarget::enter(w.wl_surface(), seat, data, keys, serial)
+                }
+                #[cfg(feature = "xwayland")]
+                WindowSurface::X11(s) => KeyboardTarget::enter(s, seat, data, keys, serial),
+            },
+            KeyboardFocusTarget::LayerSurface(l) => {
+                KeyboardTarget::enter(l.wl_surface(), seat, data, keys, serial)
+            }
+            KeyboardFocusTarget::Popup(p) => {
+                KeyboardTarget::enter(p.wl_surface(), seat, data, keys, serial)
+            }
+        }
+    }
+    fn leave(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        serial: Serial,
+    ) {
+        match self {
+            KeyboardFocusTarget::Window(w) => match w.underlying_surface() {
+                WindowSurface::Wayland(w) => {
+                    KeyboardTarget::leave(w.wl_surface(), seat, data, serial)
+                }
+                #[cfg(feature = "xwayland")]
+                WindowSurface::X11(s) => KeyboardTarget::leave(s, seat, data, serial),
+            },
+            KeyboardFocusTarget::LayerSurface(l) => {
+                KeyboardTarget::leave(l.wl_surface(), seat, data, serial)
+            }
+            KeyboardFocusTarget::Popup(p) => {
+                KeyboardTarget::leave(p.wl_surface(), seat, data, serial)
+            }
+        }
+    }
+    fn key(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        key: KeysymHandle<'_>,
+        state: KeyState,
+        serial: Serial,
+        time: u32,
+    ) {
+        match self {
+            KeyboardFocusTarget::Window(w) => match w.underlying_surface() {
+                WindowSurface::Wayland(w) => {
+                    KeyboardTarget::key(w.wl_surface(), seat, data, key, state, serial, time)
+                }
+                #[cfg(feature = "xwayland")]
+                WindowSurface::X11(s) => {
+                    KeyboardTarget::key(s, seat, data, key, state, serial, time)
+                }
+            },
+            KeyboardFocusTarget::LayerSurface(l) => {
+                KeyboardTarget::key(l.wl_surface(), seat, data, key, state, serial, time)
+            }
+            KeyboardFocusTarget::Popup(p) => {
+                KeyboardTarget::key(p.wl_surface(), seat, data, key, state, serial, time)
+            }
+        }
+    }
+    fn modifiers(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        modifiers: ModifiersState,
+        serial: Serial,
+    ) {
+        match self {
+            KeyboardFocusTarget::Window(w) => match w.underlying_surface() {
+                WindowSurface::Wayland(w) => {
+                    KeyboardTarget::modifiers(w.wl_surface(), seat, data, modifiers, serial)
+                }
+                #[cfg(feature = "xwayland")]
+                WindowSurface::X11(s) => {
+                    KeyboardTarget::modifiers(s, seat, data, modifiers, serial)
+                }
+            },
+            KeyboardFocusTarget::LayerSurface(l) => {
+                KeyboardTarget::modifiers(l.wl_surface(), seat, data, modifiers, serial)
+            }
+            KeyboardFocusTarget::Popup(p) => {
+                KeyboardTarget::modifiers(p.wl_surface(), seat, data, modifiers, serial)
+            }
+        }
+    }
+}
+
+impl<BackendData: Backend> TouchTarget<CompositronState<BackendData>> for PointerFocusTarget {
+    fn down(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &smithay::input::touch::DownEvent,
+        seq: Serial,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => TouchTarget::down(w, seat, data, event, seq),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => TouchTarget::down(w, seat, data, event, seq),
+            PointerFocusTarget::SSD(w) => TouchTarget::down(w, seat, data, event, seq),
+        }
+    }
+
+    fn up(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &smithay::input::touch::UpEvent,
+        seq: Serial,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => TouchTarget::up(w, seat, data, event, seq),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => TouchTarget::up(w, seat, data, event, seq),
+            PointerFocusTarget::SSD(w) => TouchTarget::up(w, seat, data, event, seq),
+        }
+    }
+
+    fn motion(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &smithay::input::touch::MotionEvent,
+        seq: Serial,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => TouchTarget::motion(w, seat, data, event, seq),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => TouchTarget::motion(w, seat, data, event, seq),
+            PointerFocusTarget::SSD(w) => TouchTarget::motion(w, seat, data, event, seq),
+        }
+    }
+
+    fn frame(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        seq: Serial,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => TouchTarget::frame(w, seat, data, seq),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => TouchTarget::frame(w, seat, data, seq),
+            PointerFocusTarget::SSD(w) => TouchTarget::frame(w, seat, data, seq),
+        }
+    }
+
+    fn cancel(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        seq: Serial,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => TouchTarget::cancel(w, seat, data, seq),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => TouchTarget::cancel(w, seat, data, seq),
+            PointerFocusTarget::SSD(w) => TouchTarget::cancel(w, seat, data, seq),
+        }
+    }
+
+    fn shape(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &smithay::input::touch::ShapeEvent,
+        seq: Serial,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => TouchTarget::shape(w, seat, data, event, seq),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => TouchTarget::shape(w, seat, data, event, seq),
+            PointerFocusTarget::SSD(w) => TouchTarget::shape(w, seat, data, event, seq),
+        }
+    }
+
+    fn orientation(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &smithay::input::touch::OrientationEvent,
+        seq: Serial,
+    ) {
+        match self {
+            PointerFocusTarget::WlSurface(w) => TouchTarget::orientation(w, seat, data, event, seq),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => {
+                TouchTarget::orientation(w, seat, data, event, seq)
+            }
+            PointerFocusTarget::SSD(w) => TouchTarget::orientation(w, seat, data, event, seq),
+        }
+    }
+}
+
+impl WaylandFocus for PointerFocusTarget {
+    #[inline]
+    fn wl_surface(&self) -> Option<Cow<'_, WlSurface>> {
+        match self {
+            PointerFocusTarget::WlSurface(w) => w.wl_surface(),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => w.wl_surface().map(Cow::Owned),
+            PointerFocusTarget::SSD(_) => None,
+        }
+    }
+    #[inline]
+    fn same_client_as(&self, object_id: &ObjectId) -> bool {
+        match self {
+            PointerFocusTarget::WlSurface(w) => w.same_client_as(object_id),
+            #[cfg(feature = "xwayland")]
+            PointerFocusTarget::X11Surface(w) => w.same_client_as(object_id),
+            PointerFocusTarget::SSD(w) => w
+                .wl_surface()
+                .map(|surface| surface.same_client_as(object_id))
+                .unwrap_or(false),
+        }
+    }
+}
+
+impl WaylandFocus for KeyboardFocusTarget {
+    #[inline]
+    fn wl_surface(&self) -> Option<Cow<'_, WlSurface>> {
+        match self {
+            KeyboardFocusTarget::Window(w) => w.wl_surface(),
+            KeyboardFocusTarget::LayerSurface(l) => Some(Cow::Borrowed(l.wl_surface())),
+            KeyboardFocusTarget::Popup(p) => Some(Cow::Borrowed(p.wl_surface())),
+        }
+    }
+}
+
+impl From<WlSurface> for PointerFocusTarget {
+    #[inline]
+    fn from(value: WlSurface) -> Self {
+        PointerFocusTarget::WlSurface(value)
+    }
+}
+
+impl From<&WlSurface> for PointerFocusTarget {
+    #[inline]
+    fn from(value: &WlSurface) -> Self {
+        PointerFocusTarget::from(value.clone())
+    }
+}
+
+impl From<PopupKind> for PointerFocusTarget {
+    #[inline]
+    fn from(value: PopupKind) -> Self {
+        PointerFocusTarget::from(value.wl_surface())
+    }
+}
+
+#[cfg(feature = "xwayland")]
+impl From<X11Surface> for PointerFocusTarget {
+    #[inline]
+    fn from(value: X11Surface) -> Self {
+        PointerFocusTarget::X11Surface(value)
+    }
+}
+
+#[cfg(feature = "xwayland")]
+impl From<&X11Surface> for PointerFocusTarget {
+    #[inline]
+    fn from(value: &X11Surface) -> Self {
+        PointerFocusTarget::from(value.clone())
+    }
+}
+
+impl From<WindowElement> for KeyboardFocusTarget {
+    #[inline]
+    fn from(w: WindowElement) -> Self {
+        KeyboardFocusTarget::Window(w.0.clone())
+    }
+}
+
+impl From<LayerSurface> for KeyboardFocusTarget {
+    #[inline]
+    fn from(l: LayerSurface) -> Self {
+        KeyboardFocusTarget::LayerSurface(l)
+    }
+}
+
+impl From<PopupKind> for KeyboardFocusTarget {
+    #[inline]
+    fn from(p: PopupKind) -> Self {
+        KeyboardFocusTarget::Popup(p)
+    }
+}
+
+impl From<KeyboardFocusTarget> for PointerFocusTarget {
+    #[inline]
+    fn from(value: KeyboardFocusTarget) -> Self {
+        match value {
+            KeyboardFocusTarget::Window(w) => match w.underlying_surface() {
+                WindowSurface::Wayland(w) => PointerFocusTarget::from(w.wl_surface()),
+                #[cfg(feature = "xwayland")]
+                WindowSurface::X11(s) => PointerFocusTarget::from(s),
+            },
+            KeyboardFocusTarget::LayerSurface(surface) => {
+                PointerFocusTarget::from(surface.wl_surface())
+            }
+            KeyboardFocusTarget::Popup(popup) => PointerFocusTarget::from(popup.wl_surface()),
+        }
+    }
+}

+ 214 - 0
src/icons.rs

@@ -0,0 +1,214 @@
+//! Icon theme lookup and rasterization.
+
+use std::{
+    collections::HashMap,
+    path::{Path, PathBuf},
+    sync::Arc,
+};
+
+use freedesktop_icons::lookup;
+use image::imageops::FilterType;
+use tiny_skia::{IntSize, Pixmap, PixmapPaint, Transform};
+use tracing::{debug, warn};
+
+#[derive(Debug)]
+pub struct IconCache {
+    theme: String,
+    size: u32,
+    icons: HashMap<(String, u32), Option<Arc<Pixmap>>>,
+}
+
+impl IconCache {
+    pub fn new(theme: impl Into<String>, size: u32) -> Self {
+        Self {
+            theme: theme.into(),
+            size,
+            icons: HashMap::new(),
+        }
+    }
+
+    pub fn set_theme(&mut self, theme: impl Into<String>) {
+        let theme = theme.into();
+        if theme != self.theme {
+            self.theme = theme;
+            self.icons.clear();
+        }
+    }
+
+    pub fn size(&self) -> u32 {
+        self.size
+    }
+
+    pub fn set_size(&mut self, size: u32) {
+        if size != self.size {
+            self.size = size;
+            self.icons.clear();
+        }
+    }
+
+    pub fn icon(&mut self, name: &str) -> Option<Arc<Pixmap>> {
+        let size = self.size;
+        let key = (name.to_string(), size);
+        if let Some(cached) = self.icons.get(&key) {
+            return cached.clone();
+        }
+
+        let icon = self.load(name, size).map(Arc::new);
+        self.icons.insert(key, icon.clone());
+        icon
+    }
+
+    fn load(&self, name: &str, size: u32) -> Option<Pixmap> {
+        let path = if Path::new(name).is_absolute() {
+            let path = PathBuf::from(name);
+            path.is_file().then_some(path)
+        } else {
+            lookup(name)
+                .with_theme(&self.theme)
+                .with_size(size.min(u16::MAX as u32) as u16)
+                .with_scale(1)
+                .find()
+                .or_else(|| {
+                    lookup(name)
+                        .with_size(size.min(u16::MAX as u32) as u16)
+                        .find()
+                })
+                .or_else(|| {
+                    lookup("application-x-executable")
+                        .with_theme(&self.theme)
+                        .with_size(size.min(u16::MAX as u32) as u16)
+                        .find()
+                })
+        };
+
+        let Some(path) = path else {
+            debug!(name, "no icon found");
+            return None;
+        };
+
+        match load_pixmap(&path, size) {
+            Ok(pixmap) => Some(pixmap),
+            Err(err) => {
+                warn!(?path, %err, "failed to rasterize icon");
+                None
+            }
+        }
+    }
+}
+
+fn load_pixmap(path: &Path, size: u32) -> Result<Pixmap, String> {
+    let data = std::fs::read(path).map_err(|err| err.to_string())?;
+    let extension = path
+        .extension()
+        .and_then(|extension| extension.to_str())
+        .unwrap_or_default()
+        .to_ascii_lowercase();
+
+    if extension == "svg" || extension == "svgz" {
+        return load_svg(&data, size);
+    }
+    if matches!(extension.as_str(), "png" | "jpg" | "jpeg" | "webp") {
+        return load_raster(&data, size);
+    }
+    Err(format!("unsupported icon format: {extension}"))
+}
+
+fn load_svg(data: &[u8], size: u32) -> Result<Pixmap, String> {
+    let tree = usvg::Tree::from_data(data, &usvg::Options::default())
+        .map_err(|err| format!("invalid svg: {err}"))?;
+    let intrinsic = tree.size();
+    let scale = (size as f32 / intrinsic.width())
+        .min(size as f32 / intrinsic.height())
+        .max(0.001);
+
+    let scaled_width = (intrinsic.width() * scale).round().max(1.0) as u32;
+    let scaled_height = (intrinsic.height() * scale).round().max(1.0) as u32;
+    let mut scaled = Pixmap::new(scaled_width.max(1), scaled_height.max(1))
+        .ok_or_else(|| "invalid icon dimensions".to_string())?;
+    resvg::render(
+        &tree,
+        Transform::from_scale(scale, scale),
+        &mut scaled.as_mut(),
+    );
+
+    let mut canvas = Pixmap::new(size, size).ok_or_else(|| "invalid icon canvas".to_string())?;
+    canvas.draw_pixmap(
+        ((size.saturating_sub(scaled_width)) / 2) as i32,
+        ((size.saturating_sub(scaled_height)) / 2) as i32,
+        scaled.as_ref(),
+        &PixmapPaint::default(),
+        Transform::identity(),
+        None,
+    );
+    Ok(canvas)
+}
+
+fn load_raster(data: &[u8], size: u32) -> Result<Pixmap, String> {
+    let image = image::load_from_memory(data).map_err(|err| format!("invalid image: {err}"))?;
+    let rgba = image.to_rgba8();
+    let (width, height) = (rgba.width(), rgba.height());
+    if width == 0 || height == 0 {
+        return Err("empty image".into());
+    }
+
+    let scale = (size as f32 / width as f32).min(size as f32 / height as f32);
+    let scaled_width = ((width as f32 * scale).round() as u32).max(1);
+    let scaled_height = ((height as f32 * scale).round() as u32).max(1);
+    let scaled = image::imageops::resize(&rgba, scaled_width, scaled_height, FilterType::Lanczos3);
+
+    let mut canvas = Pixmap::new(size, size).ok_or_else(|| "invalid icon canvas".to_string())?;
+    let mut pixels = scaled.into_raw();
+    // tiny-skia expects premultiplied RGBA.
+    for pixel in pixels.chunks_exact_mut(4) {
+        let alpha = pixel[3] as u32;
+        pixel[0] = ((pixel[0] as u32 * alpha) / 255) as u8;
+        pixel[1] = ((pixel[1] as u32 * alpha) / 255) as u8;
+        pixel[2] = ((pixel[2] as u32 * alpha) / 255) as u8;
+    }
+
+    let Some(icon) = Pixmap::from_vec(
+        pixels,
+        IntSize::from_wh(scaled_width, scaled_height)
+            .ok_or_else(|| "invalid icon size".to_string())?,
+    ) else {
+        return Err("invalid icon pixels".into());
+    };
+
+    canvas.draw_pixmap(
+        ((size.saturating_sub(scaled_width)) / 2) as i32,
+        ((size.saturating_sub(scaled_height)) / 2) as i32,
+        icon.as_ref(),
+        &PixmapPaint::default(),
+        Transform::identity(),
+        None,
+    );
+    Ok(canvas)
+}
+
+/// Deterministic fallback color for applications without an icon.
+pub fn fallback_color(name: &str) -> [u8; 4] {
+    const PALETTE: [[u8; 4]; 8] = [
+        [0x3b, 0x6e, 0xa5, 0xff],
+        [0x7a, 0x4f, 0xa5, 0xff],
+        [0xa5, 0x4f, 0x6e, 0xff],
+        [0xa5, 0x74, 0x3b, 0xff],
+        [0x4f, 0xa5, 0x7a, 0xff],
+        [0x3b, 0x8d, 0xa5, 0xff],
+        [0x8d, 0x7a, 0x3b, 0xff],
+        [0x5f, 0x5f, 0xa5, 0xff],
+    ];
+    let hash = name.bytes().fold(0u64, |hash, byte| {
+        hash.wrapping_mul(31).wrapping_add(byte as u64)
+    });
+    PALETTE[(hash as usize) % PALETTE.len()]
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn fallback_color_is_stable() {
+        assert_eq!(fallback_color("Firefox"), fallback_color("Firefox"));
+    }
+}

+ 1778 - 0
src/input_handler.rs

@@ -0,0 +1,1778 @@
+use std::{convert::TryInto, process::Command, sync::atomic::Ordering};
+
+use crate::{
+    focus::PointerFocusTarget, overview::OverviewAction, shell::FullscreenSurface, CompositronState,
+};
+
+#[cfg(feature = "udev")]
+use crate::udev::UdevData;
+#[cfg(feature = "udev")]
+use smithay::backend::renderer::DebugFlags;
+
+use smithay::{
+    backend::input::{
+        self, Axis, AxisSource, Event, InputBackend, InputEvent, KeyState, KeyboardKeyEvent,
+        PointerAxisEvent, PointerButtonEvent,
+    },
+    desktop::{layer_map_for_output, WindowSurfaceType},
+    input::{
+        keyboard::{keysyms as xkb, FilterResult, Keysym, ModifiersState},
+        pointer::{AxisFrame, ButtonEvent, MotionEvent},
+    },
+    output::Scale,
+    reexports::{
+        wayland_protocols::xdg::{
+            decoration::zv1::server::zxdg_toplevel_decoration_v1, shell::server::xdg_toplevel,
+        },
+        wayland_server::protocol::wl_pointer,
+    },
+    utils::{Logical, Point, Serial, Transform, SERIAL_COUNTER as SCOUNTER},
+    wayland::{
+        compositor::with_states,
+        input_method::InputMethodSeat,
+        keyboard_shortcuts_inhibit::KeyboardShortcutsInhibitorSeat,
+        shell::{
+            wlr_layer::{KeyboardInteractivity, Layer as WlrLayer, LayerSurfaceCachedState},
+            xdg::XdgShellHandler,
+        },
+    },
+};
+
+#[cfg(any(feature = "winit", feature = "x11", feature = "udev"))]
+use smithay::backend::input::AbsolutePositionEvent;
+
+#[cfg(any(feature = "winit", feature = "x11"))]
+use smithay::output::Output;
+use tracing::{debug, error, info};
+
+use crate::state::Backend;
+#[cfg(feature = "udev")]
+use smithay::{
+    backend::{
+        input::{
+            Device, DeviceCapability, GestureBeginEvent, GestureEndEvent,
+            GesturePinchUpdateEvent as _, GestureSwipeUpdateEvent as _, PointerMotionEvent,
+            ProximityState, TabletToolButtonEvent, TabletToolEvent, TabletToolProximityEvent,
+            TabletToolTipEvent, TabletToolTipState, TouchEvent,
+        },
+        session::Session,
+    },
+    input::{
+        pointer::{
+            GestureHoldBeginEvent, GestureHoldEndEvent, GesturePinchBeginEvent,
+            GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent,
+            GestureSwipeEndEvent, GestureSwipeUpdateEvent, RelativeMotionEvent,
+        },
+        touch::{DownEvent, UpEvent},
+    },
+    reexports::wayland_server::DisplayHandle,
+    wayland::{
+        pointer_constraints::{with_pointer_constraint, PointerConstraint},
+        seat::WaylandFocus,
+        tablet_manager::{TabletDescriptor, TabletSeatTrait},
+    },
+};
+
+impl<BackendData: Backend> CompositronState<BackendData> {
+    fn process_common_key_action(&mut self, action: KeyAction) {
+        match action {
+            KeyAction::None => (),
+
+            KeyAction::Quit => {
+                info!("Quitting.");
+                self.running.store(false, Ordering::SeqCst);
+            }
+
+            KeyAction::Run(cmd) => {
+                info!(cmd, "Starting program");
+
+                if let Err(e) = Command::new(&cmd)
+                    .envs(
+                        self.socket_name
+                            .clone()
+                            .map(|v| ("WAYLAND_DISPLAY", v))
+                            .into_iter()
+                            .chain(
+                                #[cfg(feature = "xwayland")]
+                                self.xdisplay.map(|v| ("DISPLAY", format!(":{}", v))),
+                                #[cfg(not(feature = "xwayland"))]
+                                None,
+                            ),
+                    )
+                    .spawn()
+                {
+                    error!(cmd, err = %e, "Failed to start program");
+                }
+            }
+
+            KeyAction::RunTerminal => {
+                let terminal = self.overview.terminal();
+                let Some(program) = terminal.command.first() else {
+                    return;
+                };
+                let mut command = Command::new(program);
+                command
+                    .args(&terminal.command[1..])
+                    .env("XDG_SESSION_TYPE", "wayland")
+                    .env("XDG_CURRENT_DESKTOP", "Compositron")
+                    .env_remove("DISPLAY");
+                if let Some(socket) = self.socket_name.as_deref() {
+                    command.env("WAYLAND_DISPLAY", socket);
+                }
+                if let Err(err) = command.spawn() {
+                    error!(program, %err, "Failed to start terminal");
+                }
+            }
+
+            KeyAction::TogglePreview => {
+                self.show_window_preview = !self.show_window_preview;
+            }
+
+            KeyAction::Workspace(index) => {
+                self.switch_workspace(index);
+            }
+
+            KeyAction::MoveToWorkspace(index) => {
+                self.move_focused_window_to_workspace(index);
+            }
+
+            KeyAction::CycleWorkspace(delta) => {
+                self.cycle_workspace(delta);
+            }
+
+            KeyAction::CloseWindow => {
+                self.close_focused_window();
+            }
+
+            KeyAction::MaximizeWindow => {
+                if let Some(window) = self.focused_window() {
+                    if let Some(toplevel) = window.0.toplevel() {
+                        if toplevel
+                            .current_state()
+                            .states
+                            .contains(xdg_toplevel::State::Maximized)
+                        {
+                            self.unmaximize_request(toplevel.clone());
+                        } else {
+                            self.maximize_request(toplevel.clone());
+                        }
+                    }
+                }
+            }
+
+            KeyAction::RestoreWindow => {
+                if let Some(window) = self.focused_window() {
+                    if let Some(toplevel) = window.0.toplevel() {
+                        if toplevel
+                            .current_state()
+                            .states
+                            .contains(xdg_toplevel::State::Fullscreen)
+                        {
+                            self.unfullscreen_request(toplevel.clone());
+                        } else if toplevel
+                            .current_state()
+                            .states
+                            .contains(xdg_toplevel::State::Maximized)
+                        {
+                            self.unmaximize_request(toplevel.clone());
+                        }
+                    }
+                }
+            }
+
+            KeyAction::FullscreenWindow => {
+                if let Some(window) = self.focused_window() {
+                    if let Some(toplevel) = window.0.toplevel() {
+                        if toplevel
+                            .current_state()
+                            .states
+                            .contains(xdg_toplevel::State::Fullscreen)
+                        {
+                            self.unfullscreen_request(toplevel.clone());
+                        } else {
+                            self.fullscreen_request(toplevel.clone(), None);
+                        }
+                    }
+                }
+            }
+
+            KeyAction::SnapWindow(left) => {
+                self.snap_focused_window(left);
+            }
+
+            KeyAction::CycleWindows(forward) => {
+                self.cycle_focused_window(forward);
+            }
+
+            KeyAction::ToggleOverview => {
+                self.toggle_overview();
+            }
+
+            KeyAction::ToggleDecorations => {
+                for element in self.space.elements() {
+                    #[allow(irrefutable_let_patterns)]
+                    if let Some(toplevel) = element.0.toplevel() {
+                        let mode_changed = toplevel.with_pending_state(|state| {
+                            if let Some(current_mode) = state.decoration_mode {
+                                let new_mode = if current_mode
+                                    == zxdg_toplevel_decoration_v1::Mode::ClientSide
+                                {
+                                    zxdg_toplevel_decoration_v1::Mode::ServerSide
+                                } else {
+                                    zxdg_toplevel_decoration_v1::Mode::ClientSide
+                                };
+                                state.decoration_mode = Some(new_mode);
+                                true
+                            } else {
+                                false
+                            }
+                        });
+
+                        if mode_changed && toplevel.is_initial_configure_sent() {
+                            toplevel.send_pending_configure();
+                        }
+                    }
+                }
+            }
+
+            _ => unreachable!(
+                "Common key action handler encountered backend specific action {:?}",
+                action
+            ),
+        }
+    }
+
+    fn keyboard_key_to_action<B: InputBackend>(&mut self, evt: B::KeyboardKeyEvent) -> KeyAction {
+        let keycode = evt.key_code();
+        let state = evt.state();
+        debug!(?keycode, ?state, "key");
+        let serial = SCOUNTER.next_serial();
+        let time = Event::time_msec(&evt);
+        let mut suppressed_keys = self.suppressed_keys.clone();
+        let keyboard = self.seat.get_keyboard().unwrap();
+
+        if self.overview.is_open() {
+            let mut overview_action = OverviewAction::None;
+            keyboard.input::<(), _>(
+                self,
+                keycode,
+                state,
+                serial,
+                time,
+                |app, modifiers, handle| {
+                    let keysym = handle.modified_sym();
+                    if keysym == Keysym::Super_L || keysym == Keysym::Super_R {
+                        if matches!(state, KeyState::Pressed) {
+                            app.super_tap_armed = true;
+                            app.super_tap_used = false;
+                        } else {
+                            if app.super_tap_armed && !app.super_tap_used {
+                                overview_action = OverviewAction::Close;
+                            }
+                            app.super_tap_armed = false;
+                        }
+                        return FilterResult::Intercept(());
+                    }
+                    if matches!(state, KeyState::Pressed) && app.super_tap_armed {
+                        app.super_tap_used = true;
+                    }
+                    let action = app.overview_key_action(state, modifiers, &handle);
+                    if action != OverviewAction::None {
+                        overview_action = action;
+                    }
+                    FilterResult::Intercept(())
+                },
+            );
+            if overview_action != OverviewAction::None {
+                self.handle_overview_action(overview_action);
+            }
+            return KeyAction::None;
+        }
+
+        if !self.overview.is_open() {
+            for layer in self.layer_shell_state.layer_surfaces().rev() {
+                let data = with_states(layer.wl_surface(), |states| {
+                    *states
+                        .cached_state
+                        .get::<LayerSurfaceCachedState>()
+                        .current()
+                });
+                if data.keyboard_interactivity == KeyboardInteractivity::Exclusive
+                    && (data.layer == WlrLayer::Top || data.layer == WlrLayer::Overlay)
+                {
+                    let surface = self.space.outputs().find_map(|o| {
+                        let map = layer_map_for_output(o);
+                        let cloned = map.layers().find(|l| l.layer_surface() == &layer).cloned();
+                        cloned
+                    });
+                    if let Some(surface) = surface {
+                        keyboard.set_focus(self, Some(surface.into()), serial);
+                        keyboard.input::<(), _>(self, keycode, state, serial, time, |_, _, _| {
+                            FilterResult::Forward
+                        });
+                        return KeyAction::None;
+                    };
+                }
+            }
+        }
+
+        let inhibited = self
+            .space
+            .element_under(self.pointer.current_location())
+            .and_then(|(window, _)| {
+                let surface = window.wl_surface()?;
+                self.seat.keyboard_shortcuts_inhibitor_for_surface(&surface)
+            })
+            .map(|inhibitor| inhibitor.is_active())
+            .unwrap_or(false);
+
+        let action = keyboard
+            .input(
+                self,
+                keycode,
+                state,
+                serial,
+                time,
+                |app, modifiers, handle| {
+                    let keysym = handle.modified_sym();
+
+                    debug!(
+                        ?state,
+                        mods = ?modifiers,
+                        keysym = ::xkbcommon::xkb::keysym_get_name(keysym),
+                        "keysym"
+                    );
+
+                    // Super is reserved for compositor shortcuts. Track whether
+                    // it was tapped or used as part of a chord so a bare tap can
+                    // toggle the overview on release.
+                    if keysym == Keysym::Super_L || keysym == Keysym::Super_R {
+                        if matches!(state, KeyState::Pressed) {
+                            app.super_tap_armed = true;
+                            app.super_tap_used = false;
+                        } else {
+                            let toggle = app.super_tap_armed && !app.super_tap_used;
+                            app.super_tap_armed = false;
+                            if toggle {
+                                return FilterResult::Intercept(KeyAction::ToggleOverview);
+                            }
+                        }
+                        return FilterResult::Intercept(KeyAction::None);
+                    }
+                    if matches!(state, KeyState::Pressed) && app.super_tap_armed {
+                        app.super_tap_used = true;
+                    }
+
+                    // If the key is pressed and triggered a action
+                    // we will not forward the key to the client.
+                    // Additionally add the key to the suppressed keys
+                    // so that we can decide on a release if the key
+                    // should be forwarded to the client or not.
+                    if let KeyState::Pressed = state {
+                        if !inhibited {
+                            let action =
+                                process_keyboard_shortcut(*modifiers, keysym, raw_keysym(&handle));
+
+                            if action.is_some() {
+                                suppressed_keys.push(keysym);
+                            }
+
+                            action
+                                .map(FilterResult::Intercept)
+                                .unwrap_or(FilterResult::Forward)
+                        } else {
+                            FilterResult::Forward
+                        }
+                    } else {
+                        let suppressed = suppressed_keys.contains(&keysym);
+                        if suppressed {
+                            suppressed_keys.retain(|k| *k != keysym);
+                            FilterResult::Intercept(KeyAction::None)
+                        } else {
+                            FilterResult::Forward
+                        }
+                    }
+                },
+            )
+            .unwrap_or(KeyAction::None);
+
+        self.suppressed_keys = suppressed_keys;
+        action
+    }
+
+    fn on_pointer_button<B: InputBackend>(&mut self, evt: B::PointerButtonEvent) {
+        let serial = SCOUNTER.next_serial();
+        let button = evt.button_code();
+        let state = wl_pointer::ButtonState::from(evt.state());
+
+        if self.overview.is_open() {
+            if wl_pointer::ButtonState::Pressed == state {
+                let location = self.pointer.current_location();
+                if let Some(local) = self.overview_local(location) {
+                    let action = self.overview.handle_pointer_click(local);
+                    self.handle_overview_action(action);
+                }
+            }
+            return;
+        }
+
+        if self.super_tap_armed {
+            self.super_tap_used = true;
+        }
+
+        if wl_pointer::ButtonState::Pressed == state {
+            self.update_keyboard_focus(self.pointer.current_location(), serial);
+        };
+        let pointer = self.pointer.clone();
+        pointer.button(
+            self,
+            &ButtonEvent {
+                button,
+                state: state.try_into().unwrap(),
+                serial,
+                time: evt.time_msec(),
+            },
+        );
+        pointer.frame(self);
+    }
+
+    fn update_keyboard_focus(&mut self, location: Point<f64, Logical>, serial: Serial) {
+        let keyboard = self.seat.get_keyboard().unwrap();
+        let touch = self.seat.get_touch();
+        let input_method = self.seat.input_method();
+        // change the keyboard focus unless the pointer or keyboard is grabbed
+        // We test for any matching surface type here but always use the root
+        // (in case of a window the toplevel) surface for the focus.
+        // So for example if a user clicks on a subsurface or popup the toplevel
+        // will receive the keyboard focus. Directly assigning the focus to the
+        // matching surface leads to issues with clients dismissing popups and
+        // subsurface menus (for example firefox-wayland).
+        // see here for a discussion about that issue:
+        // https://gitlab.freedesktop.org/wayland/wayland/-/issues/294
+        if !self.pointer.is_grabbed()
+            && (!keyboard.is_grabbed() || input_method.keyboard_grabbed())
+            && !touch.map(|touch| touch.is_grabbed()).unwrap_or(false)
+        {
+            let output = self.space.output_under(location).next().cloned();
+            if let Some(output) = output.as_ref() {
+                let output_geo = self.space.output_geometry(output).unwrap();
+                if let Some(window) = output
+                    .user_data()
+                    .get::<FullscreenSurface>()
+                    .and_then(|f| f.get())
+                {
+                    if let Some((_, _)) = window
+                        .surface_under(location - output_geo.loc.to_f64(), WindowSurfaceType::ALL)
+                    {
+                        #[cfg(feature = "xwayland")]
+                        if let Some(surface) = window.0.x11_surface() {
+                            self.xwm.as_mut().unwrap().raise_window(surface).unwrap();
+                        }
+                        keyboard.set_focus(self, Some(window.into()), serial);
+                        return;
+                    }
+                }
+
+                let layers = layer_map_for_output(output);
+                if let Some(layer) = layers
+                    .layer_under(WlrLayer::Overlay, location - output_geo.loc.to_f64())
+                    .or_else(|| {
+                        layers.layer_under(WlrLayer::Top, location - output_geo.loc.to_f64())
+                    })
+                {
+                    if layer.can_receive_keyboard_focus() {
+                        if let Some((_, _)) = layer.surface_under(
+                            location
+                                - output_geo.loc.to_f64()
+                                - layers.layer_geometry(layer).unwrap().loc.to_f64(),
+                            WindowSurfaceType::ALL,
+                        ) {
+                            keyboard.set_focus(self, Some(layer.clone().into()), serial);
+                            return;
+                        }
+                    }
+                }
+            }
+
+            if let Some((window, _)) = self
+                .space
+                .element_under(location)
+                .map(|(w, p)| (w.clone(), p))
+            {
+                self.space.raise_element(&window, true);
+                #[cfg(feature = "xwayland")]
+                if let Some(surface) = window.0.x11_surface() {
+                    self.xwm.as_mut().unwrap().raise_window(surface).unwrap();
+                }
+                keyboard.set_focus(self, Some(window.into()), serial);
+                return;
+            }
+
+            if let Some(output) = output.as_ref() {
+                let output_geo = self.space.output_geometry(output).unwrap();
+                let layers = layer_map_for_output(output);
+                if let Some(layer) = layers
+                    .layer_under(WlrLayer::Bottom, location - output_geo.loc.to_f64())
+                    .or_else(|| {
+                        layers.layer_under(WlrLayer::Background, location - output_geo.loc.to_f64())
+                    })
+                {
+                    if layer.can_receive_keyboard_focus() {
+                        if let Some((_, _)) = layer.surface_under(
+                            location
+                                - output_geo.loc.to_f64()
+                                - layers.layer_geometry(layer).unwrap().loc.to_f64(),
+                            WindowSurfaceType::ALL,
+                        ) {
+                            keyboard.set_focus(self, Some(layer.clone().into()), serial);
+                        }
+                    }
+                }
+            };
+        }
+    }
+
+    pub fn surface_under(
+        &self,
+        pos: Point<f64, Logical>,
+    ) -> Option<(PointerFocusTarget, Point<f64, Logical>)> {
+        let output = self.space.outputs().find(|o| {
+            let geometry = self.space.output_geometry(o).unwrap();
+            geometry.contains(pos.to_i32_round())
+        })?;
+        let output_geo = self.space.output_geometry(output).unwrap();
+        let layers = layer_map_for_output(output);
+
+        let mut under = None;
+        if let Some((surface, loc)) = output
+            .user_data()
+            .get::<FullscreenSurface>()
+            .and_then(|f| f.get())
+            .and_then(|w| w.surface_under(pos - output_geo.loc.to_f64(), WindowSurfaceType::ALL))
+        {
+            under = Some((surface, loc + output_geo.loc));
+        } else if let Some(focus) = layers
+            .layer_under(WlrLayer::Overlay, pos - output_geo.loc.to_f64())
+            .or_else(|| layers.layer_under(WlrLayer::Top, pos - output_geo.loc.to_f64()))
+            .and_then(|layer| {
+                let layer_loc = layers.layer_geometry(layer).unwrap().loc;
+                layer
+                    .surface_under(
+                        pos - output_geo.loc.to_f64() - layer_loc.to_f64(),
+                        WindowSurfaceType::ALL,
+                    )
+                    .map(|(surface, loc)| {
+                        (
+                            PointerFocusTarget::from(surface),
+                            loc + layer_loc + output_geo.loc,
+                        )
+                    })
+            })
+        {
+            under = Some(focus)
+        } else if let Some(focus) = self.space.element_under(pos).and_then(|(window, loc)| {
+            window
+                .surface_under(pos - loc.to_f64(), WindowSurfaceType::ALL)
+                .map(|(surface, surf_loc)| (surface, surf_loc + loc))
+        }) {
+            under = Some(focus);
+        } else if let Some(focus) = layers
+            .layer_under(WlrLayer::Bottom, pos - output_geo.loc.to_f64())
+            .or_else(|| layers.layer_under(WlrLayer::Background, pos - output_geo.loc.to_f64()))
+            .and_then(|layer| {
+                let layer_loc = layers.layer_geometry(layer).unwrap().loc;
+                layer
+                    .surface_under(
+                        pos - output_geo.loc.to_f64() - layer_loc.to_f64(),
+                        WindowSurfaceType::ALL,
+                    )
+                    .map(|(surface, loc)| {
+                        (
+                            PointerFocusTarget::from(surface),
+                            loc + layer_loc + output_geo.loc,
+                        )
+                    })
+            })
+        {
+            under = Some(focus)
+        };
+        under.map(|(s, l)| (s, l.to_f64()))
+    }
+
+    fn on_pointer_axis<B: InputBackend>(&mut self, evt: B::PointerAxisEvent) {
+        let horizontal_amount = evt.amount(input::Axis::Horizontal).unwrap_or_else(|| {
+            evt.amount_v120(input::Axis::Horizontal).unwrap_or(0.0) * 15.0 / 120.
+        });
+        let vertical_amount = evt
+            .amount(input::Axis::Vertical)
+            .unwrap_or_else(|| evt.amount_v120(input::Axis::Vertical).unwrap_or(0.0) * 15.0 / 120.);
+        let horizontal_amount_discrete = evt.amount_v120(input::Axis::Horizontal);
+        let vertical_amount_discrete = evt.amount_v120(input::Axis::Vertical);
+
+        if self.overview.is_open() {
+            self.overview.handle_axis(vertical_amount);
+            self.repaint_overview();
+            return;
+        }
+
+        {
+            let mut frame = AxisFrame::new(evt.time_msec()).source(evt.source());
+            if horizontal_amount != 0.0 {
+                frame = frame
+                    .relative_direction(Axis::Horizontal, evt.relative_direction(Axis::Horizontal));
+                frame = frame.value(Axis::Horizontal, horizontal_amount);
+                if let Some(discrete) = horizontal_amount_discrete {
+                    frame = frame.v120(Axis::Horizontal, discrete as i32);
+                }
+            }
+            if vertical_amount != 0.0 {
+                frame = frame
+                    .relative_direction(Axis::Vertical, evt.relative_direction(Axis::Vertical));
+                frame = frame.value(Axis::Vertical, vertical_amount);
+                if let Some(discrete) = vertical_amount_discrete {
+                    frame = frame.v120(Axis::Vertical, discrete as i32);
+                }
+            }
+            if evt.source() == AxisSource::Finger {
+                if evt.amount(Axis::Horizontal) == Some(0.0) {
+                    frame = frame.stop(Axis::Horizontal);
+                }
+                if evt.amount(Axis::Vertical) == Some(0.0) {
+                    frame = frame.stop(Axis::Vertical);
+                }
+            }
+            let pointer = self.pointer.clone();
+            pointer.axis(self, frame);
+            pointer.frame(self);
+        }
+    }
+}
+
+#[cfg(any(feature = "winit", feature = "x11"))]
+impl<BackendData: Backend> CompositronState<BackendData> {
+    pub fn process_input_event_windowed<B: InputBackend>(
+        &mut self,
+        event: InputEvent<B>,
+        output_name: &str,
+    ) {
+        match event {
+            InputEvent::Keyboard { event } => match self.keyboard_key_to_action::<B>(event) {
+                KeyAction::ScaleUp => {
+                    let output = self
+                        .space
+                        .outputs()
+                        .find(|o| o.name() == output_name)
+                        .unwrap()
+                        .clone();
+
+                    let current_scale = output.current_scale().fractional_scale();
+                    let new_scale = current_scale + 0.25;
+                    output.change_current_state(
+                        None,
+                        None,
+                        Some(Scale::Fractional(new_scale)),
+                        None,
+                    );
+
+                    crate::shell::fixup_positions(&mut self.space, self.pointer.current_location());
+                    self.backend_data.reset_buffers(&output);
+                }
+
+                KeyAction::ScaleDown => {
+                    let output = self
+                        .space
+                        .outputs()
+                        .find(|o| o.name() == output_name)
+                        .unwrap()
+                        .clone();
+
+                    let current_scale = output.current_scale().fractional_scale();
+                    let new_scale = f64::max(1.0, current_scale - 0.25);
+                    output.change_current_state(
+                        None,
+                        None,
+                        Some(Scale::Fractional(new_scale)),
+                        None,
+                    );
+
+                    crate::shell::fixup_positions(&mut self.space, self.pointer.current_location());
+                    self.backend_data.reset_buffers(&output);
+                }
+
+                KeyAction::RotateOutput => {
+                    let output = self
+                        .space
+                        .outputs()
+                        .find(|o| o.name() == output_name)
+                        .unwrap()
+                        .clone();
+
+                    let current_transform = output.current_transform();
+                    let new_transform = match current_transform {
+                        Transform::Normal => Transform::_90,
+                        Transform::_90 => Transform::_180,
+                        Transform::_180 => Transform::_270,
+                        Transform::_270 => Transform::Flipped,
+                        Transform::Flipped => Transform::Flipped90,
+                        Transform::Flipped90 => Transform::Flipped180,
+                        Transform::Flipped180 => Transform::Flipped270,
+                        Transform::Flipped270 => Transform::Normal,
+                    };
+                    tracing::info!(?current_transform, ?new_transform, output = ?output.name(), "changing output transform");
+                    output.change_current_state(None, Some(new_transform), None, None);
+                    crate::shell::fixup_positions(&mut self.space, self.pointer.current_location());
+                    self.backend_data.reset_buffers(&output);
+                }
+
+                action => match action {
+                    KeyAction::None
+                    | KeyAction::Quit
+                    | KeyAction::Run(_)
+                    | KeyAction::RunTerminal
+                    | KeyAction::TogglePreview
+                    | KeyAction::ToggleDecorations
+                    | KeyAction::ToggleOverview
+                    | KeyAction::Workspace(_)
+                    | KeyAction::MoveToWorkspace(_)
+                    | KeyAction::CycleWorkspace(_)
+                    | KeyAction::CloseWindow
+                    | KeyAction::MaximizeWindow
+                    | KeyAction::RestoreWindow
+                    | KeyAction::FullscreenWindow
+                    | KeyAction::SnapWindow(_)
+                    | KeyAction::CycleWindows(_) => self.process_common_key_action(action),
+
+                    _ => tracing::warn!(
+                        ?action,
+                        output_name,
+                        "Key action unsupported on on output backend.",
+                    ),
+                },
+            },
+
+            InputEvent::PointerMotionAbsolute { event } => {
+                let output = self
+                    .space
+                    .outputs()
+                    .find(|o| o.name() == output_name)
+                    .unwrap()
+                    .clone();
+                self.on_pointer_move_absolute_windowed::<B>(event, &output)
+            }
+            InputEvent::PointerButton { event } => self.on_pointer_button::<B>(event),
+            InputEvent::PointerAxis { event } => self.on_pointer_axis::<B>(event),
+            _ => (), // other events are not handled in Compositron (yet)
+        }
+    }
+
+    fn on_pointer_move_absolute_windowed<B: InputBackend>(
+        &mut self,
+        evt: B::PointerMotionAbsoluteEvent,
+        output: &Output,
+    ) {
+        let output_geo = self.space.output_geometry(output).unwrap();
+
+        let pos = evt.position_transformed(output_geo.size) + output_geo.loc.to_f64();
+        let serial = SCOUNTER.next_serial();
+
+        if self.overview.is_open() {
+            let pointer = self.pointer.clone();
+            pointer.motion(
+                self,
+                None,
+                &MotionEvent {
+                    location: pos,
+                    serial,
+                    time: evt.time_msec(),
+                },
+            );
+            pointer.frame(self);
+            if let Some(local) = self.overview_local(pos) {
+                self.overview.handle_pointer_motion(local);
+            }
+            self.repaint_overview();
+            return;
+        }
+
+        let pointer = self.pointer.clone();
+        let under = self.surface_under(pos);
+        pointer.motion(
+            self,
+            under,
+            &MotionEvent {
+                location: pos,
+                serial,
+                time: evt.time_msec(),
+            },
+        );
+        pointer.frame(self);
+    }
+
+    pub fn release_all_keys(&mut self) {
+        let keyboard = self.seat.get_keyboard().unwrap();
+        for keycode in keyboard.pressed_keys() {
+            keyboard.input(
+                self,
+                keycode,
+                KeyState::Released,
+                SCOUNTER.next_serial(),
+                0,
+                |_, _, _| FilterResult::Forward::<bool>,
+            );
+        }
+    }
+}
+
+#[cfg(feature = "udev")]
+impl CompositronState<UdevData> {
+    pub fn process_input_event<B: InputBackend>(
+        &mut self,
+        dh: &DisplayHandle,
+        event: InputEvent<B>,
+    ) {
+        match event {
+            InputEvent::Keyboard { event, .. } => match self.keyboard_key_to_action::<B>(event) {
+                #[cfg(feature = "udev")]
+                KeyAction::VtSwitch(vt) => {
+                    info!(to = vt, "Trying to switch vt");
+                    if let Err(err) = self.backend_data.session.change_vt(vt) {
+                        error!(vt, "Error switching vt: {}", err);
+                    }
+                }
+                KeyAction::Screen(num) => {
+                    let geometry = self
+                        .space
+                        .outputs()
+                        .nth(num)
+                        .map(|o| self.space.output_geometry(o).unwrap());
+
+                    if let Some(geometry) = geometry {
+                        let x = geometry.loc.x as f64 + geometry.size.w as f64 / 2.0;
+                        let y = geometry.size.h as f64 / 2.0;
+                        let location = (x, y).into();
+                        let pointer = self.pointer.clone();
+                        let under = self.surface_under(location);
+                        pointer.motion(
+                            self,
+                            under,
+                            &MotionEvent {
+                                location,
+                                serial: SCOUNTER.next_serial(),
+                                time: self.clock.now().as_millis(),
+                            },
+                        );
+                        pointer.frame(self);
+                    }
+                }
+                KeyAction::ScaleUp => {
+                    let pos = self.pointer.current_location().to_i32_round();
+                    let output = self
+                        .space
+                        .outputs()
+                        .find(|o| self.space.output_geometry(o).unwrap().contains(pos))
+                        .cloned();
+
+                    if let Some(output) = output {
+                        let (output_location, scale) = (
+                            self.space.output_geometry(&output).unwrap().loc,
+                            output.current_scale().fractional_scale(),
+                        );
+                        let new_scale = scale + 0.25;
+                        output.change_current_state(
+                            None,
+                            None,
+                            Some(Scale::Fractional(new_scale)),
+                            None,
+                        );
+
+                        let rescale = scale / new_scale;
+                        let output_location = output_location.to_f64();
+                        let mut pointer_output_location =
+                            self.pointer.current_location() - output_location;
+                        pointer_output_location.x *= rescale;
+                        pointer_output_location.y *= rescale;
+                        let pointer_location = output_location + pointer_output_location;
+
+                        crate::shell::fixup_positions(&mut self.space, pointer_location);
+                        let pointer = self.pointer.clone();
+                        let under = self.surface_under(pointer_location);
+                        pointer.motion(
+                            self,
+                            under,
+                            &MotionEvent {
+                                location: pointer_location,
+                                serial: SCOUNTER.next_serial(),
+                                time: self.clock.now().as_millis(),
+                            },
+                        );
+                        pointer.frame(self);
+                        self.backend_data.reset_buffers(&output);
+                    }
+                }
+                KeyAction::ScaleDown => {
+                    let pos = self.pointer.current_location().to_i32_round();
+                    let output = self
+                        .space
+                        .outputs()
+                        .find(|o| self.space.output_geometry(o).unwrap().contains(pos))
+                        .cloned();
+
+                    if let Some(output) = output {
+                        let (output_location, scale) = (
+                            self.space.output_geometry(&output).unwrap().loc,
+                            output.current_scale().fractional_scale(),
+                        );
+                        let new_scale = f64::max(1.0, scale - 0.25);
+                        output.change_current_state(
+                            None,
+                            None,
+                            Some(Scale::Fractional(new_scale)),
+                            None,
+                        );
+
+                        let rescale = scale / new_scale;
+                        let output_location = output_location.to_f64();
+                        let mut pointer_output_location =
+                            self.pointer.current_location() - output_location;
+                        pointer_output_location.x *= rescale;
+                        pointer_output_location.y *= rescale;
+                        let pointer_location = output_location + pointer_output_location;
+
+                        crate::shell::fixup_positions(&mut self.space, pointer_location);
+                        let pointer = self.pointer.clone();
+                        let under = self.surface_under(pointer_location);
+                        pointer.motion(
+                            self,
+                            under,
+                            &MotionEvent {
+                                location: pointer_location,
+                                serial: SCOUNTER.next_serial(),
+                                time: self.clock.now().as_millis(),
+                            },
+                        );
+                        pointer.frame(self);
+                        self.backend_data.reset_buffers(&output);
+                    }
+                }
+                KeyAction::RotateOutput => {
+                    let pos = self.pointer.current_location().to_i32_round();
+                    let output = self
+                        .space
+                        .outputs()
+                        .find(|o| self.space.output_geometry(o).unwrap().contains(pos))
+                        .cloned();
+
+                    if let Some(output) = output {
+                        let current_transform = output.current_transform();
+                        let new_transform = match current_transform {
+                            Transform::Normal => Transform::_90,
+                            Transform::_90 => Transform::_180,
+                            Transform::_180 => Transform::_270,
+                            Transform::_270 => Transform::Flipped,
+                            Transform::Flipped => Transform::Flipped90,
+                            Transform::Flipped90 => Transform::Flipped180,
+                            Transform::Flipped180 => Transform::Flipped270,
+                            Transform::Flipped270 => Transform::Normal,
+                        };
+                        output.change_current_state(None, Some(new_transform), None, None);
+                        crate::shell::fixup_positions(
+                            &mut self.space,
+                            self.pointer.current_location(),
+                        );
+                        self.backend_data.reset_buffers(&output);
+                    }
+                }
+                KeyAction::ToggleTint => {
+                    let mut debug_flags = self.backend_data.debug_flags();
+                    debug_flags.toggle(DebugFlags::TINT);
+                    self.backend_data.set_debug_flags(debug_flags);
+                }
+
+                action => match action {
+                    KeyAction::None
+                    | KeyAction::Quit
+                    | KeyAction::Run(_)
+                    | KeyAction::RunTerminal
+                    | KeyAction::TogglePreview
+                    | KeyAction::ToggleDecorations
+                    | KeyAction::ToggleOverview
+                    | KeyAction::Workspace(_)
+                    | KeyAction::MoveToWorkspace(_)
+                    | KeyAction::CycleWorkspace(_)
+                    | KeyAction::CloseWindow
+                    | KeyAction::MaximizeWindow
+                    | KeyAction::RestoreWindow
+                    | KeyAction::FullscreenWindow
+                    | KeyAction::SnapWindow(_)
+                    | KeyAction::CycleWindows(_) => self.process_common_key_action(action),
+
+                    _ => unreachable!(),
+                },
+            },
+            InputEvent::PointerMotion { event, .. } => self.on_pointer_move::<B>(dh, event),
+            InputEvent::PointerMotionAbsolute { event, .. } => {
+                self.on_pointer_move_absolute::<B>(dh, event)
+            }
+            InputEvent::PointerButton { event, .. } => self.on_pointer_button::<B>(event),
+            InputEvent::PointerAxis { event, .. } => self.on_pointer_axis::<B>(event),
+            InputEvent::TabletToolAxis { event, .. } => self.on_tablet_tool_axis::<B>(event),
+            InputEvent::TabletToolProximity { event, .. } => {
+                self.on_tablet_tool_proximity::<B>(dh, event)
+            }
+            InputEvent::TabletToolTip { event, .. } => self.on_tablet_tool_tip::<B>(event),
+            InputEvent::TabletToolButton { event, .. } => self.on_tablet_button::<B>(event),
+            InputEvent::GestureSwipeBegin { event, .. } => self.on_gesture_swipe_begin::<B>(event),
+            InputEvent::GestureSwipeUpdate { event, .. } => {
+                self.on_gesture_swipe_update::<B>(event)
+            }
+            InputEvent::GestureSwipeEnd { event, .. } => self.on_gesture_swipe_end::<B>(event),
+            InputEvent::GesturePinchBegin { event, .. } => self.on_gesture_pinch_begin::<B>(event),
+            InputEvent::GesturePinchUpdate { event, .. } => {
+                self.on_gesture_pinch_update::<B>(event)
+            }
+            InputEvent::GesturePinchEnd { event, .. } => self.on_gesture_pinch_end::<B>(event),
+            InputEvent::GestureHoldBegin { event, .. } => self.on_gesture_hold_begin::<B>(event),
+            InputEvent::GestureHoldEnd { event, .. } => self.on_gesture_hold_end::<B>(event),
+
+            InputEvent::TouchDown { event } => self.on_touch_down::<B>(event),
+            InputEvent::TouchUp { event } => self.on_touch_up::<B>(event),
+            InputEvent::TouchMotion { event } => self.on_touch_motion::<B>(event),
+            InputEvent::TouchFrame { event } => self.on_touch_frame::<B>(event),
+            InputEvent::TouchCancel { event } => self.on_touch_cancel::<B>(event),
+
+            InputEvent::DeviceAdded { device } => {
+                if device.has_capability(DeviceCapability::TabletTool) {
+                    self.seat
+                        .tablet_seat()
+                        .add_tablet::<Self>(dh, &TabletDescriptor::from(&device));
+                }
+                if device.has_capability(DeviceCapability::Touch) && self.seat.get_touch().is_none()
+                {
+                    self.seat.add_touch();
+                }
+            }
+            InputEvent::DeviceRemoved { device }
+                if device.has_capability(DeviceCapability::TabletTool) =>
+            {
+                let tablet_seat = self.seat.tablet_seat();
+
+                tablet_seat.remove_tablet(&TabletDescriptor::from(&device));
+
+                // If there are no tablets in seat we can remove all tools
+                if tablet_seat.count_tablets() == 0 {
+                    tablet_seat.clear_tools();
+                }
+            }
+            InputEvent::DeviceRemoved { .. } => {}
+            _ => {
+                // other events are not handled in Compositron (yet)
+            }
+        }
+    }
+
+    fn on_pointer_move<B: InputBackend>(
+        &mut self,
+        _dh: &DisplayHandle,
+        evt: B::PointerMotionEvent,
+    ) {
+        let mut pointer_location = self.pointer.current_location();
+        let serial = SCOUNTER.next_serial();
+
+        if self.overview.is_open() {
+            pointer_location += evt.delta();
+            pointer_location = self.clamp_coords(pointer_location);
+            let pointer = self.pointer.clone();
+            pointer.motion(
+                self,
+                None,
+                &MotionEvent {
+                    location: pointer_location,
+                    serial,
+                    time: evt.time_msec(),
+                },
+            );
+            pointer.frame(self);
+            if let Some(local) = self.overview_local(pointer_location) {
+                self.overview.handle_pointer_motion(local);
+            }
+            self.repaint_overview();
+            return;
+        }
+
+        let pointer = self.pointer.clone();
+        let under = self.surface_under(pointer_location);
+
+        let mut pointer_locked = false;
+        let mut pointer_confined = false;
+        let mut confine_region = None;
+        if let Some((surface, surface_loc)) = under
+            .as_ref()
+            .and_then(|(target, l)| Some((target.wl_surface()?, l)))
+        {
+            with_pointer_constraint(&surface, &pointer, |constraint| match constraint {
+                Some(constraint) if constraint.is_active() => {
+                    // Constraint does not apply if not within region
+                    if !constraint.region().is_none_or(|x| {
+                        x.contains((pointer_location - *surface_loc).to_i32_round())
+                    }) {
+                        return;
+                    }
+                    match &*constraint {
+                        PointerConstraint::Locked(_locked) => {
+                            pointer_locked = true;
+                        }
+                        PointerConstraint::Confined(confine) => {
+                            pointer_confined = true;
+                            confine_region = confine.region().cloned();
+                        }
+                    }
+                }
+                _ => {}
+            });
+        }
+
+        pointer.relative_motion(
+            self,
+            under.clone(),
+            &RelativeMotionEvent {
+                delta: evt.delta(),
+                delta_unaccel: evt.delta_unaccel(),
+                utime: evt.time(),
+            },
+        );
+
+        // If pointer is locked, only emit relative motion
+        if pointer_locked {
+            pointer.frame(self);
+            return;
+        }
+
+        pointer_location += evt.delta();
+
+        // clamp to screen limits
+        // this event is never generated by winit
+        pointer_location = self.clamp_coords(pointer_location);
+
+        let new_under = self.surface_under(pointer_location);
+
+        // If confined, don't move pointer if it would go outside surface or region
+        if pointer_confined {
+            if let Some((surface, surface_loc)) = &under {
+                if new_under.as_ref().and_then(|(under, _)| under.wl_surface())
+                    != surface.wl_surface()
+                {
+                    pointer.frame(self);
+                    return;
+                }
+                if let Some(region) = confine_region {
+                    if !region.contains((pointer_location - *surface_loc).to_i32_round()) {
+                        pointer.frame(self);
+                        return;
+                    }
+                }
+            }
+        }
+
+        pointer.motion(
+            self,
+            under,
+            &MotionEvent {
+                location: pointer_location,
+                serial,
+                time: evt.time_msec(),
+            },
+        );
+        pointer.frame(self);
+
+        // If pointer is now in a constraint region, activate it
+        // TODO Anywhere else pointer is moved needs to do this
+        if let Some((under, surface_location)) =
+            new_under.and_then(|(target, loc)| Some((target.wl_surface()?.into_owned(), loc)))
+        {
+            with_pointer_constraint(&under, &pointer, |constraint| match constraint {
+                Some(constraint) if !constraint.is_active() => {
+                    let point = (pointer_location - surface_location).to_i32_round();
+                    if constraint
+                        .region()
+                        .is_none_or(|region| region.contains(point))
+                    {
+                        constraint.activate();
+                    }
+                }
+                _ => {}
+            });
+        }
+    }
+
+    fn on_pointer_move_absolute<B: InputBackend>(
+        &mut self,
+        _dh: &DisplayHandle,
+        evt: B::PointerMotionAbsoluteEvent,
+    ) {
+        let serial = SCOUNTER.next_serial();
+
+        let max_x = self.space.outputs().fold(0, |acc, o| {
+            acc + self.space.output_geometry(o).unwrap().size.w
+        });
+
+        let max_h_output = self
+            .space
+            .outputs()
+            .max_by_key(|o| self.space.output_geometry(o).unwrap().size.h)
+            .unwrap();
+
+        let max_y = self.space.output_geometry(max_h_output).unwrap().size.h;
+
+        let mut pointer_location = (evt.x_transformed(max_x), evt.y_transformed(max_y)).into();
+
+        // clamp to screen limits
+        pointer_location = self.clamp_coords(pointer_location);
+
+        if self.overview.is_open() {
+            let pointer = self.pointer.clone();
+            pointer.motion(
+                self,
+                None,
+                &MotionEvent {
+                    location: pointer_location,
+                    serial,
+                    time: evt.time_msec(),
+                },
+            );
+            pointer.frame(self);
+            if let Some(local) = self.overview_local(pointer_location) {
+                self.overview.handle_pointer_motion(local);
+            }
+            self.repaint_overview();
+            return;
+        }
+
+        let pointer = self.pointer.clone();
+        let under = self.surface_under(pointer_location);
+
+        pointer.motion(
+            self,
+            under,
+            &MotionEvent {
+                location: pointer_location,
+                serial,
+                time: evt.time_msec(),
+            },
+        );
+        pointer.frame(self);
+    }
+
+    fn on_tablet_tool_axis<B: InputBackend>(&mut self, evt: B::TabletToolAxisEvent) {
+        let tablet_seat = self.seat.tablet_seat();
+
+        if let Some(pointer_location) = self.touch_location_transformed(&evt) {
+            let pointer = self.pointer.clone();
+            let under = self.surface_under(pointer_location);
+            let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&evt.device()));
+            let tool = tablet_seat.get_tool(&evt.tool());
+
+            pointer.motion(
+                self,
+                under.clone(),
+                &MotionEvent {
+                    location: pointer_location,
+                    serial: SCOUNTER.next_serial(),
+                    time: self.clock.now().as_millis(),
+                },
+            );
+
+            if let (Some(tablet), Some(tool)) = (tablet, tool) {
+                if evt.pressure_has_changed() {
+                    tool.pressure(evt.pressure());
+                }
+                if evt.distance_has_changed() {
+                    tool.distance(evt.distance());
+                }
+                if evt.tilt_has_changed() {
+                    tool.tilt(evt.tilt());
+                }
+                if evt.slider_has_changed() {
+                    tool.slider_position(evt.slider_position());
+                }
+                if evt.rotation_has_changed() {
+                    tool.rotation(evt.rotation());
+                }
+                if evt.wheel_has_changed() {
+                    tool.wheel(evt.wheel_delta(), evt.wheel_delta_discrete());
+                }
+
+                tool.motion(
+                    pointer_location,
+                    under.and_then(|(f, loc)| f.wl_surface().map(|s| (s.into_owned(), loc))),
+                    &tablet,
+                    SCOUNTER.next_serial(),
+                    evt.time_msec(),
+                );
+            }
+
+            pointer.frame(self);
+        }
+    }
+
+    fn on_tablet_tool_proximity<B: InputBackend>(
+        &mut self,
+        dh: &DisplayHandle,
+        evt: B::TabletToolProximityEvent,
+    ) {
+        let tablet_seat = self.seat.tablet_seat();
+
+        if let Some(pointer_location) = self.touch_location_transformed(&evt) {
+            let tool = evt.tool();
+            tablet_seat.add_tool::<Self>(self, dh, &tool);
+
+            let pointer = self.pointer.clone();
+            let under = self.surface_under(pointer_location);
+            let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&evt.device()));
+            let tool = tablet_seat.get_tool(&tool);
+
+            pointer.motion(
+                self,
+                under.clone(),
+                &MotionEvent {
+                    location: pointer_location,
+                    serial: SCOUNTER.next_serial(),
+                    time: evt.time_msec(),
+                },
+            );
+            pointer.frame(self);
+
+            if let (Some(under), Some(tablet), Some(tool)) = (
+                under.and_then(|(f, loc)| f.wl_surface().map(|s| (s.into_owned(), loc))),
+                tablet,
+                tool,
+            ) {
+                match evt.state() {
+                    ProximityState::In => tool.proximity_in(
+                        pointer_location,
+                        under,
+                        &tablet,
+                        SCOUNTER.next_serial(),
+                        evt.time_msec(),
+                    ),
+                    ProximityState::Out => tool.proximity_out(evt.time_msec()),
+                }
+            }
+        }
+    }
+
+    fn on_tablet_tool_tip<B: InputBackend>(&mut self, evt: B::TabletToolTipEvent) {
+        let tool = self.seat.tablet_seat().get_tool(&evt.tool());
+
+        if let Some(tool) = tool {
+            match evt.tip_state() {
+                TabletToolTipState::Down => {
+                    let serial = SCOUNTER.next_serial();
+                    tool.tip_down(serial, evt.time_msec());
+
+                    // change the keyboard focus
+                    self.update_keyboard_focus(self.pointer.current_location(), serial);
+                }
+                TabletToolTipState::Up => {
+                    tool.tip_up(evt.time_msec());
+                }
+            }
+        }
+    }
+
+    fn on_tablet_button<B: InputBackend>(&mut self, evt: B::TabletToolButtonEvent) {
+        let tool = self.seat.tablet_seat().get_tool(&evt.tool());
+
+        if let Some(tool) = tool {
+            tool.button(
+                evt.button(),
+                evt.button_state(),
+                SCOUNTER.next_serial(),
+                evt.time_msec(),
+            );
+        }
+    }
+
+    fn on_gesture_swipe_begin<B: InputBackend>(&mut self, evt: B::GestureSwipeBeginEvent) {
+        let serial = SCOUNTER.next_serial();
+        let pointer = self.pointer.clone();
+        pointer.gesture_swipe_begin(
+            self,
+            &GestureSwipeBeginEvent {
+                serial,
+                time: evt.time_msec(),
+                fingers: evt.fingers(),
+            },
+        );
+    }
+
+    fn on_gesture_swipe_update<B: InputBackend>(&mut self, evt: B::GestureSwipeUpdateEvent) {
+        let pointer = self.pointer.clone();
+        pointer.gesture_swipe_update(
+            self,
+            &GestureSwipeUpdateEvent {
+                time: evt.time_msec(),
+                delta: evt.delta(),
+            },
+        );
+    }
+
+    fn on_gesture_swipe_end<B: InputBackend>(&mut self, evt: B::GestureSwipeEndEvent) {
+        let serial = SCOUNTER.next_serial();
+        let pointer = self.pointer.clone();
+        pointer.gesture_swipe_end(
+            self,
+            &GestureSwipeEndEvent {
+                serial,
+                time: evt.time_msec(),
+                cancelled: evt.cancelled(),
+            },
+        );
+    }
+
+    fn on_gesture_pinch_begin<B: InputBackend>(&mut self, evt: B::GesturePinchBeginEvent) {
+        let serial = SCOUNTER.next_serial();
+        let pointer = self.pointer.clone();
+        pointer.gesture_pinch_begin(
+            self,
+            &GesturePinchBeginEvent {
+                serial,
+                time: evt.time_msec(),
+                fingers: evt.fingers(),
+            },
+        );
+    }
+
+    fn on_gesture_pinch_update<B: InputBackend>(&mut self, evt: B::GesturePinchUpdateEvent) {
+        let pointer = self.pointer.clone();
+        pointer.gesture_pinch_update(
+            self,
+            &GesturePinchUpdateEvent {
+                time: evt.time_msec(),
+                delta: evt.delta(),
+                scale: evt.scale(),
+                rotation: evt.rotation(),
+            },
+        );
+    }
+
+    fn on_gesture_pinch_end<B: InputBackend>(&mut self, evt: B::GesturePinchEndEvent) {
+        let serial = SCOUNTER.next_serial();
+        let pointer = self.pointer.clone();
+        pointer.gesture_pinch_end(
+            self,
+            &GesturePinchEndEvent {
+                serial,
+                time: evt.time_msec(),
+                cancelled: evt.cancelled(),
+            },
+        );
+    }
+
+    fn on_gesture_hold_begin<B: InputBackend>(&mut self, evt: B::GestureHoldBeginEvent) {
+        let serial = SCOUNTER.next_serial();
+        let pointer = self.pointer.clone();
+        pointer.gesture_hold_begin(
+            self,
+            &GestureHoldBeginEvent {
+                serial,
+                time: evt.time_msec(),
+                fingers: evt.fingers(),
+            },
+        );
+    }
+
+    fn on_gesture_hold_end<B: InputBackend>(&mut self, evt: B::GestureHoldEndEvent) {
+        let serial = SCOUNTER.next_serial();
+        let pointer = self.pointer.clone();
+        pointer.gesture_hold_end(
+            self,
+            &GestureHoldEndEvent {
+                serial,
+                time: evt.time_msec(),
+                cancelled: evt.cancelled(),
+            },
+        );
+    }
+
+    fn touch_location_transformed<B: InputBackend, E: AbsolutePositionEvent<B>>(
+        &self,
+        evt: &E,
+    ) -> Option<Point<f64, Logical>> {
+        let output = self
+            .space
+            .outputs()
+            .find(|output| output.name().starts_with("eDP"))
+            .or_else(|| self.space.outputs().next());
+
+        let output = output?;
+        let output_geometry = self.space.output_geometry(output)?;
+
+        let transform = output.current_transform();
+        let size = transform.invert().transform_size(output_geometry.size);
+        Some(
+            transform.transform_point_in(evt.position_transformed(size), &size.to_f64())
+                + output_geometry.loc.to_f64(),
+        )
+    }
+
+    fn on_touch_down<B: InputBackend>(&mut self, evt: B::TouchDownEvent) {
+        let Some(handle) = self.seat.get_touch() else {
+            return;
+        };
+
+        let Some(touch_location) = self.touch_location_transformed(&evt) else {
+            return;
+        };
+
+        let serial = SCOUNTER.next_serial();
+        self.update_keyboard_focus(touch_location, serial);
+
+        let under = self.surface_under(touch_location);
+        handle.down(
+            self,
+            under,
+            &DownEvent {
+                slot: evt.slot(),
+                location: touch_location,
+                serial,
+                time: evt.time_msec(),
+            },
+        );
+    }
+    fn on_touch_up<B: InputBackend>(&mut self, evt: B::TouchUpEvent) {
+        let Some(handle) = self.seat.get_touch() else {
+            return;
+        };
+        let serial = SCOUNTER.next_serial();
+        handle.up(
+            self,
+            &UpEvent {
+                slot: evt.slot(),
+                serial,
+                time: evt.time_msec(),
+            },
+        )
+    }
+    fn on_touch_motion<B: InputBackend>(&mut self, evt: B::TouchMotionEvent) {
+        let Some(handle) = self.seat.get_touch() else {
+            return;
+        };
+        let Some(touch_location) = self.touch_location_transformed(&evt) else {
+            return;
+        };
+
+        let under = self.surface_under(touch_location);
+        handle.motion(
+            self,
+            under,
+            &smithay::input::touch::MotionEvent {
+                slot: evt.slot(),
+                location: touch_location,
+                time: evt.time_msec(),
+            },
+        );
+    }
+    fn on_touch_frame<B: InputBackend>(&mut self, _evt: B::TouchFrameEvent) {
+        let Some(handle) = self.seat.get_touch() else {
+            return;
+        };
+        handle.frame(self);
+    }
+    fn on_touch_cancel<B: InputBackend>(&mut self, _evt: B::TouchCancelEvent) {
+        let Some(handle) = self.seat.get_touch() else {
+            return;
+        };
+        handle.cancel(self);
+    }
+
+    fn clamp_coords(&self, pos: Point<f64, Logical>) -> Point<f64, Logical> {
+        if self.space.outputs().next().is_none() {
+            return pos;
+        }
+
+        let (pos_x, pos_y) = pos.into();
+        let max_x = self.space.outputs().fold(0, |acc, o| {
+            acc + self.space.output_geometry(o).unwrap().size.w
+        });
+        let clamped_x = pos_x.clamp(0.0, max_x as f64);
+        let max_y = self
+            .space
+            .outputs()
+            .find(|o| {
+                let geo = self.space.output_geometry(o).unwrap();
+                geo.contains((clamped_x as i32, 0))
+            })
+            .map(|o| self.space.output_geometry(o).unwrap().size.h);
+
+        if let Some(max_y) = max_y {
+            let clamped_y = pos_y.clamp(0.0, max_y as f64);
+            (clamped_x, clamped_y).into()
+        } else {
+            (clamped_x, pos_y).into()
+        }
+    }
+}
+
+/// Possible results of a keyboard action
+#[allow(dead_code)] // some of these are only read if udev is enabled
+#[derive(Debug)]
+enum KeyAction {
+    /// Quit the compositor
+    Quit,
+    /// Trigger a vt-switch
+    VtSwitch(i32),
+    /// run a command
+    Run(String),
+    /// open the configured terminal
+    RunTerminal,
+    /// Switch the current screen
+    Screen(usize),
+    /// Switch to a workspace
+    Workspace(usize),
+    /// Move the focused window to a workspace
+    MoveToWorkspace(usize),
+    /// Switch to the previous/next workspace
+    CycleWorkspace(isize),
+    /// Close the focused window
+    CloseWindow,
+    /// Toggle maximize on the focused window
+    MaximizeWindow,
+    /// Restore the focused window from maximize/fullscreen
+    RestoreWindow,
+    /// Toggle fullscreen on the focused window
+    FullscreenWindow,
+    /// Snap the focused window to the left/right half
+    SnapWindow(bool),
+    /// Focus the next/previous window
+    CycleWindows(bool),
+    /// Toggle the application overview
+    ToggleOverview,
+    ScaleUp,
+    ScaleDown,
+    TogglePreview,
+    RotateOutput,
+    ToggleTint,
+    ToggleDecorations,
+    /// Do nothing more
+    None,
+}
+
+fn process_keyboard_shortcut(
+    modifiers: ModifiersState,
+    keysym: Keysym,
+    raw_sym: Keysym,
+) -> Option<KeyAction> {
+    let digit = |range_start: u32, range_end: u32, base: u32| {
+        (range_start..=range_end)
+            .contains(&raw_sym.raw())
+            .then(|| (raw_sym.raw() - base) as usize)
+    };
+
+    if (modifiers.ctrl && modifiers.alt && keysym == Keysym::BackSpace)
+        || (modifiers.logo && modifiers.shift && raw_sym == Keysym::q)
+    {
+        // ctrl+alt+backspace = quit
+        // logo + shift + q = quit
+        Some(KeyAction::Quit)
+    } else if (xkb::KEY_XF86Switch_VT_1..=xkb::KEY_XF86Switch_VT_12).contains(&keysym.raw()) {
+        // VTSwitch
+        Some(KeyAction::VtSwitch(
+            (keysym.raw() - xkb::KEY_XF86Switch_VT_1 + 1) as i32,
+        ))
+    } else if modifiers.logo && keysym == Keysym::Return {
+        Some(KeyAction::RunTerminal)
+    } else if modifiers.logo
+        && modifiers.shift
+        && digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).is_some()
+    {
+        Some(KeyAction::MoveToWorkspace(
+            digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).unwrap(),
+        ))
+    } else if modifiers.logo && digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).is_some() {
+        Some(KeyAction::Workspace(
+            digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).unwrap(),
+        ))
+    } else if modifiers.logo && keysym == Keysym::Page_Up {
+        Some(KeyAction::CycleWorkspace(-1))
+    } else if modifiers.logo && keysym == Keysym::Page_Down {
+        Some(KeyAction::CycleWorkspace(1))
+    } else if modifiers.logo && keysym == Keysym::Left {
+        Some(KeyAction::SnapWindow(true))
+    } else if modifiers.logo && keysym == Keysym::Right {
+        Some(KeyAction::SnapWindow(false))
+    } else if modifiers.logo && keysym == Keysym::Up {
+        Some(KeyAction::MaximizeWindow)
+    } else if modifiers.logo && keysym == Keysym::Down {
+        Some(KeyAction::RestoreWindow)
+    } else if modifiers.logo && keysym == Keysym::f {
+        Some(KeyAction::FullscreenWindow)
+    } else if modifiers.logo && keysym == Keysym::q {
+        Some(KeyAction::CloseWindow)
+    } else if modifiers.logo && keysym == Keysym::space {
+        Some(KeyAction::ToggleOverview)
+    } else if modifiers.alt && keysym == Keysym::Tab {
+        Some(KeyAction::CycleWindows(!modifiers.shift))
+    } else if modifiers.ctrl && modifiers.alt && keysym == Keysym::Left {
+        Some(KeyAction::SnapWindow(true))
+    } else if modifiers.ctrl && modifiers.alt && keysym == Keysym::Right {
+        Some(KeyAction::SnapWindow(false))
+    } else if modifiers.ctrl && modifiers.alt && keysym == Keysym::Up {
+        Some(KeyAction::MaximizeWindow)
+    } else if modifiers.ctrl && modifiers.alt && keysym == Keysym::Down {
+        Some(KeyAction::RestoreWindow)
+    } else if modifiers.ctrl && modifiers.alt && keysym == Keysym::Return {
+        Some(KeyAction::RunTerminal)
+    } else if modifiers.ctrl && modifiers.alt && keysym == Keysym::w {
+        Some(KeyAction::CloseWindow)
+    } else if modifiers.ctrl && modifiers.alt && keysym == Keysym::f {
+        Some(KeyAction::FullscreenWindow)
+    } else if modifiers.ctrl && modifiers.alt && (keysym == Keysym::space || keysym == Keysym::o) {
+        Some(KeyAction::ToggleOverview)
+    } else if modifiers.ctrl
+        && modifiers.alt
+        && modifiers.shift
+        && digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).is_some()
+    {
+        Some(KeyAction::MoveToWorkspace(
+            digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).unwrap(),
+        ))
+    } else if modifiers.ctrl && modifiers.alt && digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).is_some()
+    {
+        Some(KeyAction::Workspace(
+            digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).unwrap(),
+        ))
+    } else if modifiers.ctrl
+        && modifiers.shift
+        && modifiers.alt
+        && digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).is_some()
+    {
+        Some(KeyAction::MoveToWorkspace(
+            digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).unwrap(),
+        ))
+    } else if modifiers.ctrl
+        && modifiers.shift
+        && digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).is_some()
+    {
+        Some(KeyAction::Workspace(
+            digit(xkb::KEY_1, xkb::KEY_6, xkb::KEY_1).unwrap(),
+        ))
+    } else if modifiers.ctrl && modifiers.shift && keysym == Keysym::Left {
+        Some(KeyAction::SnapWindow(true))
+    } else if modifiers.ctrl && modifiers.shift && keysym == Keysym::Right {
+        Some(KeyAction::SnapWindow(false))
+    } else if modifiers.ctrl && modifiers.shift && keysym == Keysym::Up {
+        Some(KeyAction::MaximizeWindow)
+    } else if modifiers.ctrl && modifiers.shift && keysym == Keysym::Down {
+        Some(KeyAction::RestoreWindow)
+    } else {
+        None
+    }
+}
+
+fn raw_keysym(handle: &smithay::input::keyboard::KeysymHandle<'_>) -> Keysym {
+    handle
+        .raw_syms()
+        .first()
+        .copied()
+        .unwrap_or(Keysym::NoSymbol)
+}

+ 22 - 0
src/lib.rs

@@ -0,0 +1,22 @@
+#![warn(rust_2018_idioms)]
+
+pub mod apps;
+pub mod config;
+pub mod cursor;
+pub mod drawing;
+pub mod focus;
+pub mod icons;
+pub mod input_handler;
+pub mod overview;
+pub mod render;
+pub mod shell;
+pub mod state;
+pub mod text;
+pub mod workspaces;
+
+#[cfg(feature = "udev")]
+pub mod udev;
+#[cfg(feature = "winit")]
+pub mod winit;
+
+pub use state::{ClientState, CompositronState};

+ 75 - 0
src/main.rs

@@ -0,0 +1,75 @@
+use std::process::ExitCode;
+
+use tracing_subscriber::EnvFilter;
+
+const USAGE: &str = "\
+compositron - a small Wayland compositor
+
+USAGE:
+    compositron [OPTIONS]
+
+OPTIONS:
+    --winit        Run nested in an existing Wayland session (development)
+    --udev         Run on a DRM device using libseat (default)
+    -h, --help     Print this help
+    -V, --version  Print the version
+";
+
+fn main() -> ExitCode {
+    let filter = EnvFilter::try_from_default_env()
+        .unwrap_or_else(|_| EnvFilter::new("compositron=info,smithay=warn"));
+    tracing_subscriber::fmt()
+        .compact()
+        .with_env_filter(filter)
+        .init();
+
+    // Make the session identity visible to clients that we spawn and to
+    // clients that inspect the compositor environment.
+    std::env::set_var("XDG_CURRENT_DESKTOP", "Compositron");
+    std::env::set_var("XDG_SESSION_DESKTOP", "Compositron");
+    if std::env::var_os("XDG_SESSION_TYPE").is_none() {
+        std::env::set_var("XDG_SESSION_TYPE", "wayland");
+    }
+
+    let mut backend = None;
+    for arg in std::env::args().skip(1) {
+        match arg.as_str() {
+            #[cfg(feature = "winit")]
+            "--winit" => backend = Some("winit"),
+            #[cfg(feature = "udev")]
+            "--udev" => backend = Some("udev"),
+            "-h" | "--help" => {
+                print!("{USAGE}");
+                return ExitCode::SUCCESS;
+            }
+            "-V" | "--version" => {
+                println!("compositron {}", env!("CARGO_PKG_VERSION"));
+                return ExitCode::SUCCESS;
+            }
+            other => {
+                eprintln!("compositron: unknown argument '{other}'\n\n{USAGE}");
+                return ExitCode::from(2);
+            }
+        }
+    }
+
+    #[cfg(feature = "udev")]
+    let default_backend = "udev";
+    #[cfg(all(not(feature = "udev"), feature = "winit"))]
+    let default_backend = "winit";
+    #[cfg(not(any(feature = "udev", feature = "winit")))]
+    let default_backend = "none";
+
+    match backend.unwrap_or(default_backend) {
+        #[cfg(feature = "winit")]
+        "winit" => compositron::winit::run_winit(),
+        #[cfg(feature = "udev")]
+        "udev" => compositron::udev::run_udev(),
+        other => {
+            eprintln!("compositron: backend '{other}' is not built in");
+            return ExitCode::from(2);
+        }
+    }
+
+    ExitCode::SUCCESS
+}

+ 222 - 0
src/overview/layout.rs

@@ -0,0 +1,222 @@
+//! Geometry for the fullscreen application overview.
+//!
+//! All values are in logical compositor coordinates. The renderer multiplies
+//! by its integer buffer scale, and input handling converts pointer positions
+//! into these coordinates.
+
+use smithay::utils::{Logical, Size};
+
+#[derive(Debug, Clone, Copy, PartialEq, Default)]
+pub struct Rect {
+    pub x: f64,
+    pub y: f64,
+    pub w: f64,
+    pub h: f64,
+}
+
+impl Rect {
+    pub fn new(x: f64, y: f64, w: f64, h: f64) -> Self {
+        Self { x, y, w, h }
+    }
+
+    pub fn contains(&self, x: f64, y: f64) -> bool {
+        x >= self.x && x < self.x + self.w && y >= self.y && y < self.y + self.h
+    }
+
+    pub fn intersection(&self, other: &Rect) -> Option<Rect> {
+        let x = self.x.max(other.x);
+        let y = self.y.max(other.y);
+        let right = (self.x + self.w).min(other.x + other.w);
+        let bottom = (self.y + self.h).min(other.y + other.h);
+        (right > x && bottom > y).then(|| Rect::new(x, y, right - x, bottom - y))
+    }
+}
+
+#[derive(Debug, Clone)]
+pub struct OverviewLayout {
+    pub width: f64,
+    pub height: f64,
+    pub search: Rect,
+    pub grid: Rect,
+    pub workspace_bar: Rect,
+    pub columns: usize,
+    pub cell_width: f64,
+    pub cell_height: f64,
+    pub icon_size: f64,
+    pub gap: f64,
+    pub header_height: f64,
+}
+
+impl OverviewLayout {
+    pub fn new(size: Size<i32, Logical>) -> Self {
+        let width = size.w as f64;
+        let height = size.h as f64;
+
+        let search_width = (width * 0.42)
+            .clamp(420.0, 720.0)
+            .min((width - 80.0).max(200.0));
+        let search = Rect::new(
+            ((width - search_width) / 2.0).round(),
+            44.0,
+            search_width.round(),
+            56.0,
+        );
+
+        let workspace_bar = Rect::new(
+            (width / 2.0 - 160.0).max(24.0),
+            (height - 72.0).max(search.y + search.h + 40.0),
+            (320.0_f64).min(width - 48.0),
+            40.0,
+        );
+
+        let usable_width = (width - 96.0).clamp(360.0, 1440.0);
+        let gap = 10.0;
+        let min_cell_width = 150.0;
+        let columns =
+            (((usable_width + gap) / (min_cell_width + gap)).floor() as usize).clamp(3, 8);
+        let cell_width = (usable_width - gap * (columns.saturating_sub(1) as f64)) / columns as f64;
+
+        let grid_top = 148.0;
+        let grid_bottom = (workspace_bar.y - 18.0).max(grid_top + 80.0);
+        let grid = Rect::new(
+            ((width - usable_width) / 2.0).round(),
+            grid_top,
+            usable_width.round(),
+            grid_bottom - grid_top,
+        );
+
+        let header_height = grid_top;
+
+        Self {
+            width,
+            height,
+            search,
+            grid,
+            workspace_bar,
+            columns,
+            cell_width,
+            cell_height: 132.0,
+            icon_size: 64.0,
+            gap,
+            header_height,
+        }
+    }
+
+    pub fn content_height(&self, app_count: usize) -> f64 {
+        let rows = app_count.div_ceil(self.columns);
+        rows as f64 * self.cell_height
+    }
+
+    pub fn max_scroll(&self, app_count: usize) -> f64 {
+        (self.content_height(app_count) - self.grid.h).max(0.0)
+    }
+
+    pub fn cell_rect(&self, index: usize, scroll: f64) -> Rect {
+        let row = index / self.columns;
+        let column = index % self.columns;
+        Rect::new(
+            self.grid.x + column as f64 * (self.cell_width + self.gap),
+            self.grid.y + row as f64 * self.cell_height - scroll,
+            self.cell_width,
+            self.cell_height,
+        )
+    }
+
+    pub fn hit_test(&self, x: f64, y: f64, app_count: usize, scroll: f64) -> Option<usize> {
+        if !self.grid.contains(x, y) {
+            return None;
+        }
+        let local_y = y - self.grid.y + scroll;
+        if local_y < 0.0 {
+            return None;
+        }
+        let row = (local_y / self.cell_height).floor() as usize;
+        let local_x = x - self.grid.x;
+        if local_x < 0.0 {
+            return None;
+        }
+        let column = (local_x / (self.cell_width + self.gap)).floor() as usize;
+        if column >= self.columns {
+            return None;
+        }
+        let cell_x = column as f64 * (self.cell_width + self.gap);
+        if local_x - cell_x > self.cell_width {
+            return None;
+        }
+        let index = row * self.columns + column;
+        (index < app_count
+            && self
+                .cell_rect(index, scroll)
+                .intersection(&self.grid)
+                .is_some())
+        .then_some(index)
+    }
+
+    pub fn workspace_pill(&self, index: usize, count: usize) -> Rect {
+        let pill_width = 38.0;
+        let gap = 10.0;
+        let total = count as f64 * pill_width + (count.saturating_sub(1)) as f64 * gap;
+        Rect::new(
+            (self.width - total) / 2.0 + index as f64 * (pill_width + gap),
+            self.workspace_bar.y,
+            pill_width,
+            self.workspace_bar.h,
+        )
+    }
+
+    pub fn workspace_hit(&self, x: f64, y: f64, count: usize) -> Option<usize> {
+        (0..count).find(|index| self.workspace_pill(*index, count).contains(x, y))
+    }
+
+    /// Snap a scroll offset to a whole row so the grid always looks tidy.
+    pub fn clamp_scroll(&self, scroll: f64, app_count: usize) -> f64 {
+        let max = self.max_scroll(app_count);
+        let snapped = (scroll / self.cell_height).round() * self.cell_height;
+        snapped.clamp(0.0, max)
+    }
+
+    pub fn visible_rows(&self) -> usize {
+        (self.grid.h / self.cell_height).floor() as usize
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn grid_hit_testing_round_trips() {
+        let layout = OverviewLayout::new(Size::from((1600, 1000)));
+        let scroll = 0.0;
+        for index in [0, 1, layout.columns, layout.columns * 2 + 2, 30] {
+            let cell = layout.cell_rect(index, scroll);
+            if cell.intersection(&layout.grid).is_none() {
+                continue;
+            }
+            let x = cell.x + cell.w / 2.0;
+            let y = cell.y + cell.h / 2.0;
+            assert_eq!(layout.hit_test(x, y, 200, scroll), Some(index));
+        }
+    }
+
+    #[test]
+    fn scroll_is_clamped_and_row_snapped() {
+        let layout = OverviewLayout::new(Size::from((1600, 1000)));
+        assert_eq!(layout.clamp_scroll(-50.0, 200), 0.0);
+        let max = layout.max_scroll(200);
+        assert_eq!(layout.clamp_scroll(1e9, 200), max);
+        assert_eq!(layout.clamp_scroll(140.0, 200) % layout.cell_height, 0.0);
+    }
+
+    #[test]
+    fn workspace_pills_are_hit_testable() {
+        let layout = OverviewLayout::new(Size::from((1600, 1000)));
+        for index in 0..6 {
+            let pill = layout.workspace_pill(index, 6);
+            assert_eq!(
+                layout.workspace_hit(pill.x + 4.0, pill.y + 4.0, 6),
+                Some(index)
+            );
+        }
+    }
+}

+ 498 - 0
src/overview/mod.rs

@@ -0,0 +1,498 @@
+//! Fullscreen, searchable application overview.
+
+pub mod layout;
+mod render;
+
+use smithay::{
+    backend::renderer::element::memory::MemoryRenderBuffer,
+    input::keyboard::{Keysym, ModifiersState},
+    utils::{Logical, Size},
+};
+use tracing::debug;
+
+use crate::{
+    apps::{AppCatalog, AppEntry, Terminal},
+    config::Config,
+    icons::IconCache,
+    text::TextRenderer,
+};
+
+pub use layout::{OverviewLayout, Rect};
+
+const WORKSPACE_COUNT: usize = 6;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum OverviewAction {
+    None,
+    Close,
+    Launch(usize),
+    SwitchWorkspace(usize),
+}
+
+#[derive(Debug, Clone)]
+pub enum RepeatAction {
+    Text(String),
+    Backspace,
+    Delete,
+    CursorLeft,
+    CursorRight,
+    SelectionUp,
+    SelectionDown,
+}
+
+pub struct Overview {
+    pub(crate) apps: AppCatalog,
+    pub(crate) filtered: Vec<usize>,
+    pub(crate) query: String,
+    pub(crate) cursor: usize,
+    pub(crate) selected: Option<usize>,
+    pub(crate) hover: Option<usize>,
+    pub(crate) scroll: f64,
+    pub(crate) layout: OverviewLayout,
+    pub(crate) icons: IconCache,
+    pub(crate) text: TextRenderer,
+    pub(crate) buffer: Option<MemoryRenderBuffer>,
+    pub(crate) buffer_scale: u32,
+    pub(crate) buffer_size: Size<i32, Logical>,
+    pub(crate) dirty: bool,
+    pub(crate) error: Option<String>,
+    pub(crate) active_workspace: usize,
+    pub(crate) workspace_windows: [usize; WORKSPACE_COUNT],
+    terminal: Terminal,
+    open: bool,
+}
+
+impl std::fmt::Debug for Overview {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("Overview")
+            .field("open", &self.open)
+            .field("query", &self.query)
+            .field("apps", &self.apps.len())
+            .finish_non_exhaustive()
+    }
+}
+
+impl Overview {
+    pub fn new(config: &Config) -> Self {
+        let font = config.font();
+        let terminal = Terminal::detect(config.terminal());
+        let icon_theme = config.icon_theme();
+        let layout = OverviewLayout::new(Size::from((1600, 1000)));
+        let size = Size::from((1600, 1000));
+        let apps = AppCatalog::load();
+        let filtered = (0..apps.len()).collect();
+
+        Self {
+            apps,
+            filtered,
+            query: String::new(),
+            cursor: 0,
+            selected: None,
+            hover: None,
+            scroll: 0.0,
+            layout,
+            icons: IconCache::new(icon_theme, 64),
+            text: TextRenderer::new(font),
+            buffer: None,
+            buffer_scale: 1,
+            buffer_size: size,
+            dirty: true,
+            error: None,
+            active_workspace: 0,
+            workspace_windows: [0; WORKSPACE_COUNT],
+            terminal,
+            open: false,
+        }
+    }
+
+    pub fn is_open(&self) -> bool {
+        self.open
+    }
+
+    pub fn open(&mut self) {
+        self.apps = AppCatalog::load();
+        self.query.clear();
+        self.cursor = 0;
+        self.selected = None;
+        self.hover = None;
+        self.scroll = 0.0;
+        self.error = None;
+        self.filtered = (0..self.apps.len()).collect();
+        self.open = true;
+        self.dirty = true;
+        debug!(apps = self.apps.len(), "overview opened");
+    }
+
+    pub fn close(&mut self) {
+        self.open = false;
+        self.buffer = None;
+        self.hover = None;
+    }
+
+    pub fn app(&self, catalog_index: usize) -> Option<&AppEntry> {
+        self.apps.get(catalog_index)
+    }
+
+    pub fn terminal(&self) -> &Terminal {
+        &self.terminal
+    }
+
+    pub fn set_error(&mut self, error: impl Into<String>) {
+        self.error = Some(error.into());
+        self.dirty = true;
+    }
+
+    pub fn set_workspace_info(&mut self, active: usize, windows: [usize; WORKSPACE_COUNT]) {
+        if self.active_workspace != active || self.workspace_windows != windows {
+            self.active_workspace = active;
+            self.workspace_windows = windows;
+            self.dirty = true;
+        }
+    }
+
+    pub fn handle_key(
+        &mut self,
+        key_state: smithay::backend::input::KeyState,
+        modifiers: &ModifiersState,
+        keysym: Keysym,
+        text: &str,
+    ) -> OverviewAction {
+        use smithay::backend::input::KeyState;
+
+        if !matches!(key_state, KeyState::Pressed) {
+            return OverviewAction::None;
+        }
+
+        if modifiers.ctrl {
+            match keysym {
+                Keysym::u => {
+                    self.set_query("");
+                    return OverviewAction::None;
+                }
+                Keysym::BackSpace => {
+                    self.delete_word_backward();
+                    return OverviewAction::None;
+                }
+                _ => {}
+            }
+        }
+
+        match keysym {
+            Keysym::Escape => OverviewAction::Close,
+            Keysym::Return | Keysym::KP_Enter => self.activate_selected(),
+            Keysym::BackSpace => {
+                self.backspace();
+                OverviewAction::None
+            }
+            Keysym::Delete => {
+                self.delete_forward();
+                OverviewAction::None
+            }
+            Keysym::Left => {
+                self.move_cursor(-1);
+                OverviewAction::None
+            }
+            Keysym::Right => {
+                self.move_cursor(1);
+                OverviewAction::None
+            }
+            Keysym::Home => {
+                self.cursor = 0;
+                self.dirty = true;
+                OverviewAction::None
+            }
+            Keysym::End => {
+                self.cursor = self.query.len();
+                self.dirty = true;
+                OverviewAction::None
+            }
+            Keysym::Up => {
+                self.move_selection(-(self.layout.columns as isize));
+                OverviewAction::None
+            }
+            Keysym::Down => {
+                self.move_selection(self.layout.columns as isize);
+                OverviewAction::None
+            }
+            Keysym::Page_Up => {
+                self.scroll_by(-self.layout.grid.h);
+                OverviewAction::None
+            }
+            Keysym::Page_Down => {
+                self.scroll_by(self.layout.grid.h);
+                OverviewAction::None
+            }
+            _ => {
+                if !modifiers.ctrl && !modifiers.alt && !modifiers.logo {
+                    let printable = text.chars().filter(|character| !character.is_control());
+                    let text: String = printable.collect();
+                    if !text.is_empty() {
+                        self.insert_text(&text);
+                    }
+                }
+                OverviewAction::None
+            }
+        }
+    }
+
+    pub fn handle_pointer_motion(&mut self, local: (f64, f64)) {
+        let hover = self
+            .layout
+            .hit_test(local.0, local.1, self.filtered.len(), self.scroll);
+        if hover != self.hover {
+            self.hover = hover;
+            self.dirty = true;
+        }
+    }
+
+    pub fn handle_pointer_click(&mut self, local: (f64, f64)) -> OverviewAction {
+        if self.layout.search.contains(local.0, local.1) {
+            return OverviewAction::None;
+        }
+        if let Some(workspace) = self.layout.workspace_hit(local.0, local.1, WORKSPACE_COUNT) {
+            return OverviewAction::SwitchWorkspace(workspace);
+        }
+        if let Some(index) =
+            self.layout
+                .hit_test(local.0, local.1, self.filtered.len(), self.scroll)
+        {
+            if let Some(catalog_index) = self.filtered.get(index) {
+                return OverviewAction::Launch(*catalog_index);
+            }
+        }
+        OverviewAction::Close
+    }
+
+    pub fn handle_axis(&mut self, delta: f64) {
+        self.scroll_by(delta * 80.0);
+    }
+
+    fn set_query(&mut self, query: &str) {
+        self.query = query.to_string();
+        self.cursor = self.query.len();
+        self.refilter();
+    }
+
+    /// Apply a held key while the overview owns keyboard focus.
+    pub(crate) fn apply_repeat(&mut self, action: RepeatAction) {
+        match action {
+            RepeatAction::Text(text) => self.insert_text(&text),
+            RepeatAction::Backspace => self.backspace(),
+            RepeatAction::Delete => self.delete_forward(),
+            RepeatAction::CursorLeft => self.move_cursor(-1),
+            RepeatAction::CursorRight => self.move_cursor(1),
+            RepeatAction::SelectionUp => self.move_selection(-(self.layout.columns as isize)),
+            RepeatAction::SelectionDown => self.move_selection(self.layout.columns as isize),
+        }
+    }
+
+    fn insert_text(&mut self, text: &str) {
+        if !self.query.is_char_boundary(self.cursor) {
+            self.cursor = self.query.len();
+        }
+        self.query.insert_str(self.cursor, text);
+        self.cursor += text.len();
+        self.refilter();
+    }
+
+    fn backspace(&mut self) {
+        if self.cursor == 0 || self.query.is_empty() {
+            return;
+        }
+        let start = previous_char_boundary(&self.query, self.cursor);
+        self.query.replace_range(start..self.cursor, "");
+        self.cursor = start;
+        self.refilter();
+    }
+
+    fn delete_forward(&mut self) {
+        if self.cursor >= self.query.len() {
+            return;
+        }
+        let end = next_char_boundary(&self.query, self.cursor);
+        self.query.replace_range(self.cursor..end, "");
+        self.refilter();
+    }
+
+    fn delete_word_backward(&mut self) {
+        if self.cursor == 0 {
+            return;
+        }
+        let prefix = &self.query[..self.cursor];
+        let trimmed = prefix.trim_end();
+        let boundary = trimmed
+            .rfind(|character: char| !character.is_alphanumeric())
+            .map(|index| {
+                index
+                    + trimmed[index..]
+                        .chars()
+                        .next()
+                        .map(char::len_utf8)
+                        .unwrap_or(0)
+            })
+            .unwrap_or(0);
+        self.query.replace_range(boundary..self.cursor, "");
+        self.cursor = boundary;
+        self.refilter();
+    }
+
+    fn move_cursor(&mut self, delta: isize) {
+        self.cursor = if delta < 0 {
+            (0..(-delta)).fold(self.cursor, |cursor, _| {
+                previous_char_boundary(&self.query, cursor)
+            })
+        } else {
+            (0..delta).fold(self.cursor, |cursor, _| {
+                next_char_boundary(&self.query, cursor)
+            })
+        };
+        self.dirty = true;
+    }
+
+    fn refilter(&mut self) {
+        self.filtered = self.apps.filter(&self.query);
+        self.selected = None;
+        self.hover = None;
+        self.scroll = 0.0;
+        self.error = None;
+        self.dirty = true;
+    }
+
+    fn activate_selected(&self) -> OverviewAction {
+        let selected = self
+            .selected
+            .filter(|selected| *selected < self.filtered.len())
+            .or(if self.filtered.is_empty() {
+                None
+            } else {
+                Some(0)
+            });
+        match selected.and_then(|index| self.filtered.get(index)) {
+            Some(catalog_index) => OverviewAction::Launch(*catalog_index),
+            None => OverviewAction::None,
+        }
+    }
+
+    fn move_selection(&mut self, delta: isize) {
+        if self.filtered.is_empty() {
+            self.selected = None;
+            return;
+        }
+        let length = self.filtered.len() as isize;
+        let current = self
+            .selected
+            .map(|selected| selected as isize)
+            .unwrap_or(if delta >= 0 { -1 } else { length });
+        let next = (current + delta).clamp(0, length - 1) as usize;
+        self.selected = Some(next);
+        self.ensure_selected_visible();
+        self.dirty = true;
+    }
+
+    fn ensure_selected_visible(&mut self) {
+        let Some(selected) = self.selected else {
+            return;
+        };
+        let row = selected / self.layout.columns.max(1);
+        let top = row as f64 * self.layout.cell_height;
+        let bottom = top + self.layout.cell_height;
+        if top < self.scroll {
+            self.scroll = top;
+        } else if bottom > self.scroll + self.layout.grid.h {
+            self.scroll = bottom - self.layout.grid.h;
+        }
+        self.scroll = self.layout.clamp_scroll(self.scroll, self.filtered.len());
+    }
+
+    fn scroll_by(&mut self, delta: f64) {
+        let next = (self.scroll + delta).clamp(0.0, self.layout.max_scroll(self.filtered.len()));
+        let next = self.layout.clamp_scroll(next, self.filtered.len());
+        if (next - self.scroll).abs() > f64::EPSILON {
+            self.scroll = next;
+            self.dirty = true;
+        }
+    }
+
+    pub(crate) fn prepare(&mut self, size: Size<i32, Logical>, buffer_scale: u32) {
+        if self.buffer_size != size
+            || self.layout.width != size.w as f64
+            || self.layout.height != size.h as f64
+        {
+            self.layout = OverviewLayout::new(size);
+            self.buffer_size = size;
+            self.buffer = None;
+            self.scroll = self.layout.clamp_scroll(self.scroll, self.filtered.len());
+            self.dirty = true;
+        }
+        if self.buffer_scale != buffer_scale {
+            self.buffer_scale = buffer_scale;
+            self.buffer = None;
+            self.icons
+                .set_size((self.layout.icon_size * buffer_scale as f64).round() as u32);
+            self.dirty = true;
+        }
+    }
+}
+
+fn previous_char_boundary(text: &str, index: usize) -> usize {
+    let mut index = index.min(text.len());
+    while index > 0 && !text.is_char_boundary(index) {
+        index -= 1;
+    }
+    text[..index]
+        .char_indices()
+        .next_back()
+        .map(|(offset, _)| offset)
+        .unwrap_or(0)
+}
+
+fn next_char_boundary(text: &str, mut index: usize) -> usize {
+    let length = text.len();
+    if index >= length {
+        return length;
+    }
+    index += 1;
+    while index < length && !text.is_char_boundary(index) {
+        index += 1;
+    }
+    index
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::config::Config;
+
+    #[test]
+    fn typing_filters_and_escapes() {
+        let mut overview = Overview::new(&Config::default());
+        overview.open();
+        let action = overview.handle_key(
+            smithay::backend::input::KeyState::Pressed,
+            &ModifiersState::default(),
+            Keysym::f,
+            "f",
+        );
+        assert_eq!(action, OverviewAction::None);
+        assert_eq!(overview.query, "f");
+    }
+
+    #[test]
+    fn backspace_removes_utf8_character() {
+        let mut overview = Overview::new(&Config::default());
+        overview.open();
+        overview.handle_key(
+            smithay::backend::input::KeyState::Pressed,
+            &ModifiersState::default(),
+            Keysym::e,
+            "é",
+        );
+        overview.handle_key(
+            smithay::backend::input::KeyState::Pressed,
+            &ModifiersState::default(),
+            Keysym::BackSpace,
+            "",
+        );
+        assert!(overview.query.is_empty());
+    }
+}

+ 548 - 0
src/overview/render.rs

@@ -0,0 +1,548 @@
+use smithay::{
+    backend::{
+        allocator::Fourcc,
+        renderer::{
+            element::{
+                memory::{MemoryRenderBuffer, MemoryRenderBufferRenderElement},
+                Kind,
+            },
+            ImportMem, Renderer,
+        },
+    },
+    output::Output,
+    utils::{Buffer, Physical, Point, Rectangle, Transform},
+};
+use tiny_skia::{
+    Color, FillRule, Paint, Path, PathBuilder, Pixmap, PixmapPaint, Rect as SkRect, Stroke,
+    Transform as SkTransform,
+};
+use tracing::warn;
+
+use super::{layout::Rect, Overview};
+use crate::{
+    icons::fallback_color,
+    text::{TextImage, TextStyle},
+};
+
+const WORKSPACE_COUNT: usize = 6;
+
+const SCRIM: [u8; 4] = [9, 10, 15, 255];
+const SEARCH_BG: [u8; 4] = [30, 31, 38, 255];
+const SEARCH_BORDER: [u8; 4] = [68, 70, 84, 255];
+const TEXT: [u8; 4] = [240, 241, 247, 255];
+const TEXT_DIM: [u8; 4] = [142, 145, 160, 255];
+const LABEL: [u8; 4] = [222, 224, 235, 235];
+const ACCENT: [u8; 4] = [102, 151, 255, 255];
+const ERROR: [u8; 4] = [255, 122, 122, 255];
+const HOVER_BG: [u8; 4] = [255, 255, 255, 16];
+const SELECT_BG: [u8; 4] = [102, 151, 255, 48];
+
+impl Overview {
+    pub fn render_element<R>(
+        &mut self,
+        renderer: &mut R,
+        output: &Output,
+        location: Point<i32, Physical>,
+    ) -> Option<MemoryRenderBufferRenderElement<R>>
+    where
+        R: Renderer + ImportMem,
+        R::TextureId: Send + Clone + 'static,
+    {
+        if !self.is_open() {
+            return None;
+        }
+
+        let mode = output.current_mode()?;
+        let output_scale = output.current_scale().fractional_scale();
+        let size = output
+            .current_transform()
+            .transform_size(mode.size)
+            .to_f64()
+            .to_logical(output_scale)
+            .to_i32_round();
+        let buffer_scale = output_scale.ceil().max(1.0) as u32;
+
+        self.prepare(size, buffer_scale);
+
+        if self.dirty || self.buffer.is_none() {
+            match self.paint(buffer_scale) {
+                Some(buffer) => self.buffer = Some(buffer),
+                None => {
+                    warn!("could not allocate overview buffer");
+                    return None;
+                }
+            }
+        }
+
+        MemoryRenderBufferRenderElement::from_buffer(
+            renderer,
+            location.to_f64(),
+            self.buffer.as_ref()?,
+            Some(1.0),
+            None,
+            Some(size),
+            Kind::Unspecified,
+        )
+        .ok()
+    }
+
+    fn paint(&mut self, buffer_scale: u32) -> Option<MemoryRenderBuffer> {
+        let pixmap = self.paint_pixmap(buffer_scale)?;
+        let width = pixmap.width() as i32;
+        let height = pixmap.height() as i32;
+        Some(MemoryRenderBuffer::from_slice(
+            pixmap.data(),
+            Fourcc::Abgr8888,
+            (width, height),
+            buffer_scale as i32,
+            Transform::Normal,
+            Some(vec![Rectangle::<i32, Buffer>::from_size(
+                (width, height).into(),
+            )]),
+        ))
+    }
+
+    fn paint_pixmap(&mut self, buffer_scale: u32) -> Option<Pixmap> {
+        let scale = buffer_scale as f64;
+        let width = (self.layout.width * scale).ceil() as u32;
+        let height = (self.layout.height * scale).ceil() as u32;
+        let mut pixmap = Pixmap::new(width.max(1), height.max(1))?;
+        pixmap.fill(Color::from_rgba8(SCRIM[0], SCRIM[1], SCRIM[2], SCRIM[3]));
+
+        let icon_size = (self.layout.icon_size * scale).round() as u32;
+        if self.icons.size() != icon_size {
+            self.icons.set_size(icon_size);
+        }
+
+        self.paint_search(&mut pixmap, scale);
+        self.paint_grid(&mut pixmap, scale);
+        self.paint_workspace_bar(&mut pixmap, scale);
+        self.paint_scrollbar(&mut pixmap, scale);
+        self.paint_error(&mut pixmap, scale);
+
+        self.dirty = false;
+        Some(pixmap)
+    }
+
+    fn paint_search(&mut self, pixmap: &mut Pixmap, scale: f64) {
+        let search = physical_rect(self.layout.search, scale);
+        fill_rounded(pixmap, search, (28.0 * scale) as f32, SEARCH_BG);
+        stroke_rounded(
+            pixmap,
+            search,
+            (28.0 * scale) as f32,
+            scale as f32,
+            SEARCH_BORDER,
+        );
+
+        // Magnifier.
+        let cx = ((self.layout.search.x + 29.0) * scale) as f32;
+        let cy = ((self.layout.search.y + 28.0) * scale) as f32;
+        let radius = (7.0 * scale) as f32;
+        let stroke = Stroke {
+            width: (2.0 * scale) as f32,
+            ..Default::default()
+        };
+        let mut paint = Paint {
+            anti_alias: true,
+            ..Default::default()
+        };
+        paint.set_color_rgba8(150, 154, 170, 255);
+        if let Some(circle) = PathBuilder::from_circle(cx, cy, radius) {
+            pixmap.stroke_path(&circle, &paint, &stroke, SkTransform::identity(), None);
+        }
+        let mut handle = PathBuilder::new();
+        handle.move_to(cx + radius * 0.7, cy + radius * 0.7);
+        handle.line_to(cx + radius * 1.6, cy + radius * 1.6);
+        if let Some(handle) = handle.finish() {
+            pixmap.stroke_path(&handle, &paint, &stroke, SkTransform::identity(), None);
+        }
+
+        let text_x = (self.layout.search.x + 56.0) * scale;
+        let max_width = (self.layout.search.w - 56.0 - 24.0).max(40.0) * scale;
+        let style = TextStyle::new((18.0 * scale) as f32, TEXT, Some(max_width as f32));
+        let placeholder_style =
+            TextStyle::new((18.0 * scale) as f32, TEXT_DIM, Some(max_width as f32));
+
+        let (display, style) = if self.query.is_empty() {
+            ("Search applications…", placeholder_style)
+        } else {
+            (self.query.as_str(), style)
+        };
+        let image = self.text.render(display, style);
+        let y = ((self.layout.search.y
+            + (self.layout.search.h - image.height as f64 / scale) / 2.0)
+            * scale) as f32
+            + 1.0;
+        draw_text_image(pixmap, image, text_x as f32, y);
+
+        // Caret.
+        let caret_style = TextStyle::new((18.0 * scale) as f32, TEXT, Some(max_width as f32));
+        let prefix_width = if self.cursor == 0 {
+            0.0
+        } else {
+            let cursor = self.cursor.min(self.query.len());
+            let prefix = &self.query[..cursor];
+            self.text.render(prefix, caret_style).width as f64
+        };
+        let caret_x = (text_x + prefix_width + 2.0 * scale)
+            .min((self.layout.search.x + self.layout.search.w - 18.0) * scale);
+        let caret_y = (self.layout.search.y + 15.0) * scale;
+        fill_rounded(
+            pixmap,
+            sk_rect(caret_x, caret_y, 2.0 * scale, 26.0 * scale),
+            (1.0 * scale) as f32,
+            ACCENT,
+        );
+    }
+
+    fn paint_grid(&mut self, pixmap: &mut Pixmap, scale: f64) {
+        let columns = self.layout.columns.max(1);
+        let app_count = self.filtered.len();
+
+        if app_count == 0 {
+            let style = TextStyle::new(
+                (16.0 * scale) as f32,
+                TEXT_DIM,
+                Some((self.layout.grid.w * scale) as f32),
+            );
+            let image = self.text.render("No applications found", style);
+            let x = ((self.layout.width - image.width as f64 / scale) / 2.0) * scale;
+            let y = (self.layout.grid.y + self.layout.grid.h / 2.0) * scale;
+            draw_text_image(pixmap, image, x as f32, y as f32);
+            return;
+        }
+
+        let rows = app_count.div_ceil(columns);
+        for row in 0..rows {
+            for column in 0..columns {
+                let index = row * columns + column;
+                if index >= app_count {
+                    break;
+                }
+                let cell = self.layout.cell_rect(index, self.scroll);
+                if cell.intersection(&self.layout.grid).is_none() {
+                    continue;
+                }
+                if cell.y < self.layout.grid.y - 0.5
+                    || cell.y + cell.h > self.layout.grid.y + self.layout.grid.h + 0.5
+                {
+                    continue;
+                }
+
+                let physical_cell = physical_rect(cell, scale);
+                if self.selected == Some(index) || self.hover == Some(index) {
+                    let color = if self.selected == Some(index) {
+                        SELECT_BG
+                    } else {
+                        HOVER_BG
+                    };
+                    fill_rounded(
+                        pixmap,
+                        sk_rect(
+                            physical_cell.x() as f64 + 4.0 * scale,
+                            physical_cell.y() as f64 + 4.0 * scale,
+                            (cell.w - 8.0) * scale,
+                            (cell.h - 8.0) * scale,
+                        ),
+                        (14.0 * scale) as f32,
+                        color,
+                    );
+                }
+
+                let Some(catalog_index) = self.filtered.get(index) else {
+                    continue;
+                };
+                let Some(app) = self.apps.get(*catalog_index) else {
+                    continue;
+                };
+
+                let icon_size = self.layout.icon_size;
+                let icon_x = cell.x + (cell.w - icon_size) / 2.0;
+                let icon_y = cell.y + 15.0;
+                let icon_rect = sk_rect(
+                    icon_x * scale,
+                    icon_y * scale,
+                    icon_size * scale,
+                    icon_size * scale,
+                );
+                let icon = app.icon.as_deref().and_then(|name| self.icons.icon(name));
+                if let Some(icon) = icon {
+                    pixmap.draw_pixmap(
+                        icon_rect.x().round() as i32,
+                        icon_rect.y().round() as i32,
+                        icon.as_ref().as_ref(),
+                        &PixmapPaint::default(),
+                        SkTransform::identity(),
+                        None,
+                    );
+                } else {
+                    fill_rounded(
+                        pixmap,
+                        icon_rect,
+                        (15.0 * scale) as f32,
+                        fallback_color(&app.name),
+                    );
+                    let initial = app
+                        .name
+                        .chars()
+                        .find(|character| character.is_alphanumeric())
+                        .unwrap_or('A')
+                        .to_uppercase()
+                        .to_string();
+                    let style = TextStyle::new(
+                        (32.0 * scale) as f32,
+                        [255, 255, 255, 245],
+                        Some((icon_size * scale) as f32),
+                    );
+                    let image = self.text.render(&initial, style);
+                    let x = icon_rect.x() + (icon_rect.width() - image.width) / 2.0;
+                    let y = icon_rect.y() + (icon_rect.height() - image.height) / 2.0;
+                    draw_text_image(pixmap, image, x, y);
+                }
+
+                let label_style = TextStyle::new(
+                    (13.0 * scale) as f32,
+                    LABEL,
+                    Some(((cell.w - 18.0).max(30.0) * scale) as f32),
+                );
+                let image = self.text.render(&app.name, label_style);
+                let x = (cell.x + (cell.w - image.width as f64 / scale) / 2.0) * scale;
+                let y = (icon_y + icon_size + 8.0) * scale;
+                draw_text_image(pixmap, image, x as f32, y as f32);
+            }
+        }
+    }
+
+    fn paint_workspace_bar(&mut self, pixmap: &mut Pixmap, scale: f64) {
+        let bar = physical_rect(self.layout.workspace_bar, scale);
+        fill_rounded(pixmap, bar, (20.0 * scale) as f32, [22, 23, 30, 225]);
+        stroke_rounded(
+            pixmap,
+            bar,
+            (20.0 * scale) as f32,
+            scale as f32,
+            [60, 62, 76, 190],
+        );
+
+        for index in 0..WORKSPACE_COUNT {
+            let pill = physical_rect(self.layout.workspace_pill(index, WORKSPACE_COUNT), scale);
+            let active = index == self.active_workspace;
+            if active {
+                fill_rounded(pixmap, pill, (12.0 * scale) as f32, ACCENT);
+            } else {
+                fill_rounded(pixmap, pill, (12.0 * scale) as f32, [255, 255, 255, 12]);
+            }
+
+            let number = (index + 1).to_string();
+            let color = if active { [10, 16, 30, 255] } else { TEXT };
+            let style = TextStyle::new((14.0 * scale) as f32, color, Some(pill.width()));
+            let image = self.text.render(&number, style);
+            let x = pill.x() + (pill.width() - image.width) / 2.0;
+            let y = pill.y() + (pill.height() - image.height) / 2.0 - scale as f32;
+            draw_text_image(pixmap, image, x, y);
+
+            if self.workspace_windows[index] > 0 {
+                let dot_color = if active { [10, 16, 30, 210] } else { ACCENT };
+                if let Some(dot) = PathBuilder::from_circle(
+                    pill.x() + pill.width() / 2.0,
+                    pill.y() + pill.height() - (7.0 * scale) as f32,
+                    (2.0 * scale) as f32,
+                ) {
+                    let mut paint = Paint {
+                        anti_alias: true,
+                        ..Default::default()
+                    };
+                    paint.set_color_rgba8(dot_color[0], dot_color[1], dot_color[2], dot_color[3]);
+                    pixmap.fill_path(
+                        &dot,
+                        &paint,
+                        FillRule::Winding,
+                        SkTransform::identity(),
+                        None,
+                    );
+                }
+            }
+        }
+    }
+
+    fn paint_scrollbar(&self, pixmap: &mut Pixmap, scale: f64) {
+        let max_scroll = self.layout.max_scroll(self.filtered.len());
+        if max_scroll <= 0.0 {
+            return;
+        }
+        let content = self.layout.content_height(self.filtered.len());
+        let track_x = (self.layout.grid.x + self.layout.grid.w + 8.0) * scale;
+        let track_y = self.layout.grid.y * scale;
+        let track_h = self.layout.grid.h * scale;
+        let thumb_h = ((self.layout.grid.h * self.layout.grid.h / content).max(31.0)) * scale;
+        let thumb_y = track_y
+            + ((self.scroll / max_scroll) * (track_h - thumb_h)).clamp(0.0, track_h - thumb_h);
+        fill_rounded(
+            pixmap,
+            sk_rect(track_x, track_y, 4.0 * scale, track_h),
+            (2.0 * scale) as f32,
+            [255, 255, 255, 18],
+        );
+        fill_rounded(
+            pixmap,
+            sk_rect(track_x, thumb_y, 4.0 * scale, thumb_h),
+            (2.0 * scale) as f32,
+            [255, 255, 255, 92],
+        );
+    }
+
+    fn paint_error(&mut self, pixmap: &mut Pixmap, scale: f64) {
+        let Some(error) = self.error.as_deref() else {
+            return;
+        };
+        let style = TextStyle::new(
+            (12.5 * scale) as f32,
+            ERROR,
+            Some(((self.layout.grid.w - 20.0) * scale) as f32),
+        );
+        let image = self.text.render(error, style);
+        let x = ((self.layout.width - image.width as f64 / scale) / 2.0) * scale;
+        let y = (self.layout.search.y + self.layout.search.h + 7.0) * scale;
+        draw_text_image(pixmap, image, x as f32, y as f32);
+    }
+}
+
+fn physical_rect(rect: Rect, scale: f64) -> SkRect {
+    sk_rect(
+        rect.x * scale,
+        rect.y * scale,
+        rect.w * scale,
+        rect.h * scale,
+    )
+}
+
+fn sk_rect(x: f64, y: f64, width: f64, height: f64) -> SkRect {
+    SkRect::from_xywh(
+        x as f32,
+        y as f32,
+        width.max(0.0) as f32,
+        height.max(0.0) as f32,
+    )
+    .expect("valid rect")
+}
+
+fn rounded_path(rect: SkRect, radius: f32) -> Option<Path> {
+    let radius = radius
+        .min(rect.width() / 2.0)
+        .min(rect.height() / 2.0)
+        .max(0.0);
+    if radius <= 0.0 {
+        return Some(PathBuilder::from_rect(rect));
+    }
+    let x = rect.x();
+    let y = rect.y();
+    let w = rect.width();
+    let h = rect.height();
+    let mut builder = PathBuilder::new();
+    builder.move_to(x + radius, y);
+    builder.line_to(x + w - radius, y);
+    builder.quad_to(x + w, y, x + w, y + radius);
+    builder.line_to(x + w, y + h - radius);
+    builder.quad_to(x + w, y + h, x + w - radius, y + h);
+    builder.line_to(x + radius, y + h);
+    builder.quad_to(x, y + h, x, y + h - radius);
+    builder.line_to(x, y + radius);
+    builder.quad_to(x, y, x + radius, y);
+    builder.close();
+    builder.finish()
+}
+
+fn fill_rounded(pixmap: &mut Pixmap, rect: SkRect, radius: f32, color: [u8; 4]) {
+    let Some(path) = rounded_path(rect, radius) else {
+        return;
+    };
+    let mut paint = Paint {
+        anti_alias: true,
+        ..Default::default()
+    };
+    paint.set_color_rgba8(color[0], color[1], color[2], color[3]);
+    pixmap.fill_path(
+        &path,
+        &paint,
+        FillRule::Winding,
+        SkTransform::identity(),
+        None,
+    );
+}
+
+fn stroke_rounded(pixmap: &mut Pixmap, rect: SkRect, radius: f32, width: f32, color: [u8; 4]) {
+    let inset = width / 2.0;
+    let Some(inset_rect) = SkRect::from_xywh(
+        rect.x() + inset,
+        rect.y() + inset,
+        (rect.width() - width).max(0.0),
+        (rect.height() - width).max(0.0),
+    ) else {
+        return;
+    };
+    let Some(path) = rounded_path(inset_rect, radius) else {
+        return;
+    };
+    let mut paint = Paint {
+        anti_alias: true,
+        ..Default::default()
+    };
+    paint.set_color_rgba8(color[0], color[1], color[2], color[3]);
+    let stroke = Stroke {
+        width,
+        ..Default::default()
+    };
+    pixmap.stroke_path(&path, &paint, &stroke, SkTransform::identity(), None);
+}
+
+fn draw_text_image(pixmap: &mut Pixmap, image: &TextImage, x: f32, y: f32) -> f32 {
+    pixmap.draw_pixmap(
+        x.round() as i32,
+        y.round() as i32,
+        image.pixmap.as_ref(),
+        &PixmapPaint::default(),
+        SkTransform::identity(),
+        None,
+    );
+    image.width
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::config::Config;
+    use smithay::utils::Size;
+
+    #[test]
+    #[ignore = "writes an overview snapshot for manual visual inspection"]
+    fn overview_snapshot() {
+        let started = std::time::Instant::now();
+        let mut overview = Overview::new(&Config::default());
+        eprintln!("overview new: {:?}", started.elapsed());
+        let started = std::time::Instant::now();
+        overview.open();
+        eprintln!(
+            "overview open: {:?}, apps={}",
+            started.elapsed(),
+            overview.filtered.len()
+        );
+        if overview.filtered.is_empty() {
+            return;
+        }
+        overview.selected = Some(0);
+        overview.hover = Some(3.min(overview.filtered.len() - 1));
+        overview.set_workspace_info(2, [3, 1, 0, 0, 4, 2]);
+        overview.prepare(Size::from((1600, 1000)), 1);
+        let started = std::time::Instant::now();
+        let pixmap = overview.paint_pixmap(1).expect("overview pixmap");
+        eprintln!("overview paint: {:?}", started.elapsed());
+        let path = std::env::temp_dir().join("compositron-overview.png");
+        pixmap.save_png(&path).unwrap();
+        eprintln!("wrote {}", path.display());
+        let started = std::time::Instant::now();
+        let pixmap = overview.paint_pixmap(1).expect("overview pixmap");
+        eprintln!("overview repaint: {:?}", started.elapsed());
+        drop(pixmap);
+    }
+}

+ 222 - 0
src/render.rs

@@ -0,0 +1,222 @@
+use smithay::{
+    backend::renderer::{
+        damage::{Error as OutputDamageTrackerError, OutputDamageTracker, RenderOutputResult},
+        element::{
+            memory::MemoryRenderBufferRenderElement,
+            surface::WaylandSurfaceRenderElement,
+            utils::{
+                ConstrainAlign, ConstrainScaleBehavior, CropRenderElement, RelocateRenderElement,
+                RescaleRenderElement,
+            },
+            AsRenderElements, RenderElement, Wrap,
+        },
+        Color32F, ImportAll, ImportMem, Renderer,
+    },
+    desktop::space::{
+        constrain_space_element, ConstrainBehavior, ConstrainReference, Space, SpaceRenderElements,
+    },
+    output::Output,
+    utils::{Point, Rectangle, Size},
+};
+
+#[cfg(feature = "debug")]
+use crate::drawing::FpsElement;
+use crate::{
+    drawing::{PointerRenderElement, CLEAR_COLOR, CLEAR_COLOR_FULLSCREEN},
+    shell::{FullscreenSurface, WindowElement, WindowRenderElement},
+};
+
+smithay::backend::renderer::element::render_elements! {
+    pub CustomRenderElements<R> where
+        R: ImportAll + ImportMem;
+    Pointer=PointerRenderElement<R>,
+    Surface=WaylandSurfaceRenderElement<R>,
+    Overview=MemoryRenderBufferRenderElement<R>,
+    #[cfg(feature = "debug")]
+    // Note: We would like to borrow this element instead, but that would introduce
+    // a feature-dependent lifetime, which introduces a lot more feature bounds
+    // as the whole type changes and we can't have an unused lifetime (for when "debug" is disabled)
+    // in the declaration.
+    Fps=FpsElement<R::TextureId>,
+}
+
+impl<R: Renderer> std::fmt::Debug for CustomRenderElements<R> {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            Self::Pointer(arg0) => f.debug_tuple("Pointer").field(arg0).finish(),
+            Self::Surface(arg0) => f.debug_tuple("Surface").field(arg0).finish(),
+            Self::Overview(arg0) => f.debug_tuple("Overview").field(arg0).finish(),
+            #[cfg(feature = "debug")]
+            Self::Fps(arg0) => f.debug_tuple("Fps").field(arg0).finish(),
+            Self::_GenericCatcher(arg0) => f.debug_tuple("_GenericCatcher").field(arg0).finish(),
+        }
+    }
+}
+
+smithay::backend::renderer::element::render_elements! {
+    pub OutputRenderElements<R, E> where R: ImportAll + ImportMem;
+    Space=SpaceRenderElements<R, E>,
+    Window=Wrap<E>,
+    Custom=CustomRenderElements<R>,
+    Preview=CropRenderElement<RelocateRenderElement<RescaleRenderElement<WindowRenderElement<R>>>>,
+}
+
+impl<R: Renderer + ImportAll + ImportMem, E: RenderElement<R> + std::fmt::Debug> std::fmt::Debug
+    for OutputRenderElements<R, E>
+{
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            Self::Space(arg0) => f.debug_tuple("Space").field(arg0).finish(),
+            Self::Window(arg0) => f.debug_tuple("Window").field(arg0).finish(),
+            Self::Custom(arg0) => f.debug_tuple("Custom").field(arg0).finish(),
+            Self::Preview(arg0) => f.debug_tuple("Preview").field(arg0).finish(),
+            Self::_GenericCatcher(arg0) => f.debug_tuple("_GenericCatcher").field(arg0).finish(),
+        }
+    }
+}
+
+pub fn space_preview_elements<'a, R, C>(
+    renderer: &'a mut R,
+    space: &'a Space<WindowElement>,
+    output: &'a Output,
+) -> impl Iterator<Item = C> + 'a
+where
+    R: Renderer + ImportAll + ImportMem,
+    R::TextureId: Clone + 'static,
+    C: From<CropRenderElement<RelocateRenderElement<RescaleRenderElement<WindowRenderElement<R>>>>>
+        + 'a,
+{
+    let constrain_behavior = ConstrainBehavior {
+        reference: ConstrainReference::BoundingBox,
+        behavior: ConstrainScaleBehavior::Fit,
+        align: ConstrainAlign::CENTER,
+    };
+
+    let preview_padding = 10;
+
+    let elements_on_space = space.elements_for_output(output).count();
+    let output_scale = output.current_scale().fractional_scale();
+    let output_transform = output.current_transform();
+    let output_size = output
+        .current_mode()
+        .map(|mode| {
+            output_transform
+                .transform_size(mode.size)
+                .to_f64()
+                .to_logical(output_scale)
+        })
+        .unwrap_or_default();
+
+    let max_elements_per_row = 4;
+    let elements_per_row = usize::min(elements_on_space, max_elements_per_row);
+    let rows = f64::ceil(elements_on_space as f64 / elements_per_row as f64);
+
+    let preview_size = Size::from((
+        f64::round(output_size.w / elements_per_row as f64) as i32 - preview_padding * 2,
+        f64::round(output_size.h / rows) as i32 - preview_padding * 2,
+    ));
+
+    space
+        .elements_for_output(output)
+        .enumerate()
+        .flat_map(move |(element_index, window)| {
+            let column = element_index % elements_per_row;
+            let row = element_index / elements_per_row;
+            let preview_location = Point::from((
+                preview_padding + (preview_padding + preview_size.w) * column as i32,
+                preview_padding + (preview_padding + preview_size.h) * row as i32,
+            ));
+            let constrain = Rectangle::new(preview_location, preview_size);
+            constrain_space_element(
+                renderer,
+                window,
+                preview_location,
+                1.0,
+                output_scale,
+                constrain,
+                constrain_behavior,
+            )
+        })
+}
+
+#[profiling::function]
+pub fn output_elements<R>(
+    output: &Output,
+    space: &Space<WindowElement>,
+    custom_elements: impl IntoIterator<Item = CustomRenderElements<R>>,
+    renderer: &mut R,
+    show_window_preview: bool,
+) -> (
+    Vec<OutputRenderElements<R, WindowRenderElement<R>>>,
+    Color32F,
+)
+where
+    R: Renderer + ImportAll + ImportMem,
+    R::TextureId: Clone + 'static,
+{
+    if let Some(window) = output
+        .user_data()
+        .get::<FullscreenSurface>()
+        .and_then(|f| f.get())
+    {
+        let scale = output.current_scale().fractional_scale().into();
+        let window_render_elements: Vec<WindowRenderElement<R>> =
+            AsRenderElements::<R>::render_elements(&window, renderer, (0, 0).into(), scale, 1.0);
+
+        let elements = custom_elements
+            .into_iter()
+            .map(OutputRenderElements::from)
+            .chain(
+                window_render_elements
+                    .into_iter()
+                    .map(|e| OutputRenderElements::Window(Wrap::from(e))),
+            )
+            .collect::<Vec<_>>();
+        (elements, CLEAR_COLOR_FULLSCREEN)
+    } else {
+        let mut output_render_elements = custom_elements
+            .into_iter()
+            .map(OutputRenderElements::from)
+            .collect::<Vec<_>>();
+
+        if show_window_preview && space.elements_for_output(output).count() > 0 {
+            output_render_elements.extend(space_preview_elements(renderer, space, output));
+        }
+
+        let space_elements = smithay::desktop::space::space_render_elements::<_, WindowElement, _>(
+            renderer,
+            [space],
+            output,
+            1.0,
+        )
+        .expect("output without mode?");
+        output_render_elements.extend(space_elements.into_iter().map(OutputRenderElements::Space));
+
+        (output_render_elements, CLEAR_COLOR)
+    }
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn render_output<'a, 'd, R>(
+    output: &'a Output,
+    space: &'a Space<WindowElement>,
+    custom_elements: impl IntoIterator<Item = CustomRenderElements<R>>,
+    renderer: &'a mut R,
+    framebuffer: &'a mut R::Framebuffer<'_>,
+    damage_tracker: &'d mut OutputDamageTracker,
+    age: usize,
+    show_window_preview: bool,
+) -> Result<RenderOutputResult<'d>, OutputDamageTrackerError<R::Error>>
+where
+    R: Renderer + ImportAll + ImportMem,
+    R::TextureId: Clone + 'static,
+{
+    let (elements, clear_color) = output_elements(
+        output,
+        space,
+        custom_elements,
+        renderer,
+        show_window_preview,
+    );
+    damage_tracker.render_output(renderer, framebuffer, age, &elements, clear_color)
+}

+ 475 - 0
src/shell/element.rs

@@ -0,0 +1,475 @@
+use std::{borrow::Cow, time::Duration};
+
+use smithay::{
+    backend::renderer::{
+        element::{
+            solid::SolidColorRenderElement, surface::WaylandSurfaceRenderElement, AsRenderElements,
+        },
+        ImportAll, ImportMem, Renderer, Texture,
+    },
+    desktop::{
+        space::SpaceElement, utils::OutputPresentationFeedback, Window, WindowSurface,
+        WindowSurfaceType,
+    },
+    input::{
+        pointer::{
+            AxisFrame, ButtonEvent, GestureHoldBeginEvent, GestureHoldEndEvent,
+            GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent,
+            GestureSwipeBeginEvent, GestureSwipeEndEvent, GestureSwipeUpdateEvent, MotionEvent,
+            PointerTarget, RelativeMotionEvent,
+        },
+        touch::TouchTarget,
+        Seat,
+    },
+    output::Output,
+    reexports::{
+        wayland_protocols::wp::presentation_time::server::wp_presentation_feedback,
+        wayland_server::protocol::wl_surface::WlSurface,
+    },
+    render_elements,
+    utils::{user_data::UserDataMap, IsAlive, Logical, Physical, Point, Rectangle, Scale, Serial},
+    wayland::{
+        compositor::SurfaceData as WlSurfaceData, dmabuf::DmabufFeedback, seat::WaylandFocus,
+    },
+};
+
+use super::ssd::HEADER_BAR_HEIGHT;
+use crate::{focus::PointerFocusTarget, state::Backend, CompositronState};
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct WindowElement(pub Window);
+
+impl WindowElement {
+    pub fn surface_under(
+        &self,
+        location: Point<f64, Logical>,
+        window_type: WindowSurfaceType,
+    ) -> Option<(PointerFocusTarget, Point<i32, Logical>)> {
+        let state = self.decoration_state();
+        if state.is_ssd && location.y < HEADER_BAR_HEIGHT as f64 {
+            return Some((PointerFocusTarget::SSD(SSD(self.clone())), Point::default()));
+        }
+        let offset = if state.is_ssd {
+            Point::from((0, HEADER_BAR_HEIGHT))
+        } else {
+            Point::default()
+        };
+
+        let surface_under = self
+            .0
+            .surface_under(location - offset.to_f64(), window_type);
+        let (under, loc) = match self.0.underlying_surface() {
+            WindowSurface::Wayland(_) => {
+                surface_under.map(|(surface, loc)| (PointerFocusTarget::WlSurface(surface), loc))
+            }
+            #[cfg(feature = "xwayland")]
+            WindowSurface::X11(s) => {
+                surface_under.map(|(_, loc)| (PointerFocusTarget::X11Surface(s.clone()), loc))
+            }
+        }?;
+        Some((under, loc + offset))
+    }
+
+    pub fn with_surfaces<F>(&self, processor: F)
+    where
+        F: FnMut(&WlSurface, &WlSurfaceData),
+    {
+        self.0.with_surfaces(processor);
+    }
+
+    pub fn send_frame<T, F>(
+        &self,
+        output: &Output,
+        time: T,
+        throttle: Option<Duration>,
+        primary_scan_out_output: F,
+    ) where
+        T: Into<Duration>,
+        F: FnMut(&WlSurface, &WlSurfaceData) -> Option<Output> + Copy,
+    {
+        self.0
+            .send_frame(output, time, throttle, primary_scan_out_output)
+    }
+
+    pub fn send_dmabuf_feedback<'a, P, F>(
+        &self,
+        output: &Output,
+        primary_scan_out_output: P,
+        select_dmabuf_feedback: F,
+    ) where
+        P: FnMut(&WlSurface, &WlSurfaceData) -> Option<Output> + Copy,
+        F: Fn(&WlSurface, &WlSurfaceData) -> &'a DmabufFeedback + Copy,
+    {
+        self.0
+            .send_dmabuf_feedback(output, primary_scan_out_output, select_dmabuf_feedback)
+    }
+
+    pub fn take_presentation_feedback<F1, F2>(
+        &self,
+        output_feedback: &mut OutputPresentationFeedback,
+        primary_scan_out_output: F1,
+        presentation_feedback_flags: F2,
+    ) where
+        F1: FnMut(&WlSurface, &WlSurfaceData) -> Option<Output> + Copy,
+        F2: FnMut(&WlSurface, &WlSurfaceData) -> wp_presentation_feedback::Kind + Copy,
+    {
+        self.0.take_presentation_feedback(
+            output_feedback,
+            primary_scan_out_output,
+            presentation_feedback_flags,
+        )
+    }
+
+    #[cfg(feature = "xwayland")]
+    #[inline]
+    pub fn is_x11(&self) -> bool {
+        self.0.is_x11()
+    }
+
+    #[inline]
+    pub fn is_wayland(&self) -> bool {
+        self.0.is_wayland()
+    }
+
+    #[inline]
+    pub fn wl_surface(&self) -> Option<Cow<'_, WlSurface>> {
+        self.0.wl_surface()
+    }
+
+    #[inline]
+    pub fn user_data(&self) -> &UserDataMap {
+        self.0.user_data()
+    }
+}
+
+impl IsAlive for WindowElement {
+    #[inline]
+    fn alive(&self) -> bool {
+        self.0.alive()
+    }
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct SSD(WindowElement);
+
+impl IsAlive for SSD {
+    #[inline]
+    fn alive(&self) -> bool {
+        self.0.alive()
+    }
+}
+
+impl WaylandFocus for SSD {
+    #[inline]
+    fn wl_surface(&self) -> Option<Cow<'_, WlSurface>> {
+        self.0.wl_surface()
+    }
+}
+
+impl<BackendData: Backend> PointerTarget<CompositronState<BackendData>> for SSD {
+    fn enter(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        event: &MotionEvent,
+    ) {
+        let mut state = self.0.decoration_state();
+        if state.is_ssd {
+            state.header_bar.pointer_enter(event.location);
+        }
+    }
+    fn motion(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        event: &MotionEvent,
+    ) {
+        let mut state = self.0.decoration_state();
+        if state.is_ssd {
+            state.header_bar.pointer_enter(event.location);
+        }
+    }
+    fn relative_motion(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &RelativeMotionEvent,
+    ) {
+    }
+    fn button(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &ButtonEvent,
+    ) {
+        let mut state = self.0.decoration_state();
+        if state.is_ssd {
+            state.header_bar.clicked(seat, data, &self.0, event.serial);
+        }
+    }
+    fn axis(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _frame: AxisFrame,
+    ) {
+    }
+    fn frame(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+    ) {
+    }
+    fn leave(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _serial: Serial,
+        _time: u32,
+    ) {
+        let mut state = self.0.decoration_state();
+        if state.is_ssd {
+            state.header_bar.pointer_leave();
+        }
+    }
+    fn gesture_swipe_begin(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &GestureSwipeBeginEvent,
+    ) {
+    }
+    fn gesture_swipe_update(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &GestureSwipeUpdateEvent,
+    ) {
+    }
+    fn gesture_swipe_end(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &GestureSwipeEndEvent,
+    ) {
+    }
+    fn gesture_pinch_begin(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &GesturePinchBeginEvent,
+    ) {
+    }
+    fn gesture_pinch_update(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &GesturePinchUpdateEvent,
+    ) {
+    }
+    fn gesture_pinch_end(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &GesturePinchEndEvent,
+    ) {
+    }
+    fn gesture_hold_begin(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &GestureHoldBeginEvent,
+    ) {
+    }
+    fn gesture_hold_end(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &GestureHoldEndEvent,
+    ) {
+    }
+}
+
+impl<BackendData: Backend> TouchTarget<CompositronState<BackendData>> for SSD {
+    fn down(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &smithay::input::touch::DownEvent,
+        _seq: Serial,
+    ) {
+        let mut state = self.0.decoration_state();
+        if state.is_ssd {
+            state.header_bar.pointer_enter(event.location);
+            state
+                .header_bar
+                .touch_down(seat, data, &self.0, event.serial);
+        }
+    }
+
+    fn up(
+        &self,
+        seat: &Seat<CompositronState<BackendData>>,
+        data: &mut CompositronState<BackendData>,
+        event: &smithay::input::touch::UpEvent,
+        _seq: Serial,
+    ) {
+        let mut state = self.0.decoration_state();
+        if state.is_ssd {
+            state.header_bar.touch_up(seat, data, &self.0, event.serial);
+        }
+    }
+
+    fn motion(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        event: &smithay::input::touch::MotionEvent,
+        _seq: Serial,
+    ) {
+        let mut state = self.0.decoration_state();
+        if state.is_ssd {
+            state.header_bar.pointer_enter(event.location);
+        }
+    }
+
+    fn frame(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _seq: Serial,
+    ) {
+    }
+
+    fn cancel(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _seq: Serial,
+    ) {
+    }
+
+    fn shape(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &smithay::input::touch::ShapeEvent,
+        _seq: Serial,
+    ) {
+    }
+
+    fn orientation(
+        &self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        _data: &mut CompositronState<BackendData>,
+        _event: &smithay::input::touch::OrientationEvent,
+        _seq: Serial,
+    ) {
+    }
+}
+
+impl SpaceElement for WindowElement {
+    fn geometry(&self) -> Rectangle<i32, Logical> {
+        let mut geo = SpaceElement::geometry(&self.0);
+        if self.decoration_state().is_ssd {
+            geo.size.h += HEADER_BAR_HEIGHT;
+        }
+        geo
+    }
+    fn bbox(&self) -> Rectangle<i32, Logical> {
+        let mut bbox = SpaceElement::bbox(&self.0);
+        if self.decoration_state().is_ssd {
+            bbox.size.h += HEADER_BAR_HEIGHT;
+        }
+        bbox
+    }
+    fn is_in_input_region(&self, point: &Point<f64, Logical>) -> bool {
+        if self.decoration_state().is_ssd {
+            point.y < HEADER_BAR_HEIGHT as f64
+                || SpaceElement::is_in_input_region(
+                    &self.0,
+                    &(*point - Point::from((0.0, HEADER_BAR_HEIGHT as f64))),
+                )
+        } else {
+            SpaceElement::is_in_input_region(&self.0, point)
+        }
+    }
+    fn z_index(&self) -> u8 {
+        SpaceElement::z_index(&self.0)
+    }
+
+    fn set_activate(&self, activated: bool) {
+        SpaceElement::set_activate(&self.0, activated);
+    }
+    fn output_enter(&self, output: &Output, overlap: Rectangle<i32, Logical>) {
+        SpaceElement::output_enter(&self.0, output, overlap);
+    }
+    fn output_leave(&self, output: &Output) {
+        SpaceElement::output_leave(&self.0, output);
+    }
+    #[profiling::function]
+    fn refresh(&self) {
+        SpaceElement::refresh(&self.0);
+    }
+}
+
+render_elements!(
+    pub WindowRenderElement<R> where R: ImportAll + ImportMem;
+    Window=WaylandSurfaceRenderElement<R>,
+    Decoration=SolidColorRenderElement,
+);
+
+impl<R: Renderer> std::fmt::Debug for WindowRenderElement<R> {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            Self::Window(arg0) => f.debug_tuple("Window").field(arg0).finish(),
+            Self::Decoration(arg0) => f.debug_tuple("Decoration").field(arg0).finish(),
+            Self::_GenericCatcher(arg0) => f.debug_tuple("_GenericCatcher").field(arg0).finish(),
+        }
+    }
+}
+
+impl<R> AsRenderElements<R> for WindowElement
+where
+    R: Renderer + ImportAll + ImportMem,
+    R::TextureId: Clone + Texture + 'static,
+{
+    type RenderElement = WindowRenderElement<R>;
+
+    fn render_elements<C: From<Self::RenderElement>>(
+        &self,
+        renderer: &mut R,
+        mut location: Point<i32, Physical>,
+        scale: Scale<f64>,
+        alpha: f32,
+    ) -> Vec<C> {
+        let window_bbox = SpaceElement::bbox(&self.0);
+
+        if self.decoration_state().is_ssd && !window_bbox.is_empty() {
+            let window_geo = SpaceElement::geometry(&self.0);
+
+            let mut state = self.decoration_state();
+            let width = window_geo.size.w;
+            state.header_bar.redraw(width as u32);
+            let mut vec = AsRenderElements::<R>::render_elements::<WindowRenderElement<R>>(
+                &state.header_bar,
+                renderer,
+                location,
+                scale,
+                alpha,
+            );
+
+            location.y += (scale.y * HEADER_BAR_HEIGHT as f64) as i32;
+
+            let window_elements =
+                AsRenderElements::render_elements(&self.0, renderer, location, scale, alpha);
+            vec.extend(window_elements);
+            vec.into_iter().map(C::from).collect()
+        } else {
+            AsRenderElements::render_elements(&self.0, renderer, location, scale, alpha)
+                .into_iter()
+                .map(C::from)
+                .collect()
+        }
+    }
+}

+ 896 - 0
src/shell/grabs.rs

@@ -0,0 +1,896 @@
+use std::cell::RefCell;
+
+use smithay::{
+    desktop::{space::SpaceElement, WindowSurface},
+    input::{
+        pointer::{
+            AxisFrame, ButtonEvent, GestureHoldBeginEvent, GestureHoldEndEvent,
+            GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent,
+            GestureSwipeBeginEvent, GestureSwipeEndEvent, GestureSwipeUpdateEvent,
+            GrabStartData as PointerGrabStartData, MotionEvent, PointerGrab, PointerInnerHandle,
+            RelativeMotionEvent,
+        },
+        touch::{GrabStartData as TouchGrabStartData, TouchGrab},
+    },
+    reexports::wayland_protocols::xdg::shell::server::xdg_toplevel,
+    utils::{IsAlive, Logical, Point, Serial, Size},
+    wayland::{compositor::with_states, shell::xdg::SurfaceCachedState},
+};
+#[cfg(feature = "xwayland")]
+use smithay::{utils::Rectangle, xwayland::xwm::ResizeEdge as X11ResizeEdge};
+
+use super::{SurfaceData, WindowElement};
+use crate::{
+    focus::PointerFocusTarget,
+    state::{Backend, CompositronState},
+};
+
+pub struct PointerMoveSurfaceGrab<BackendData: Backend + 'static> {
+    pub start_data: PointerGrabStartData<CompositronState<BackendData>>,
+    pub window: WindowElement,
+    pub initial_window_location: Point<i32, Logical>,
+}
+
+impl<BackendData: Backend> PointerGrab<CompositronState<BackendData>>
+    for PointerMoveSurfaceGrab<BackendData>
+{
+    fn motion(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        _focus: Option<(PointerFocusTarget, Point<f64, Logical>)>,
+        event: &MotionEvent,
+    ) {
+        // While the grab is active, no client has pointer focus
+        handle.motion(data, None, event);
+
+        let delta = event.location - self.start_data.location;
+        let new_location = self.initial_window_location.to_f64() + delta;
+
+        data.space
+            .map_element(self.window.clone(), new_location.to_i32_round(), true);
+    }
+
+    fn relative_motion(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        focus: Option<(PointerFocusTarget, Point<f64, Logical>)>,
+        event: &RelativeMotionEvent,
+    ) {
+        handle.relative_motion(data, focus, event);
+    }
+
+    fn button(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &ButtonEvent,
+    ) {
+        handle.button(data, event);
+        if handle.current_pressed().is_empty() {
+            // No more buttons are pressed, release the grab.
+            handle.unset_grab(self, data, event.serial, event.time, true);
+        }
+    }
+
+    fn axis(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        details: AxisFrame,
+    ) {
+        handle.axis(data, details)
+    }
+
+    fn frame(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+    ) {
+        handle.frame(data);
+    }
+
+    fn gesture_swipe_begin(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GestureSwipeBeginEvent,
+    ) {
+        handle.gesture_swipe_begin(data, event);
+    }
+
+    fn gesture_swipe_update(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GestureSwipeUpdateEvent,
+    ) {
+        handle.gesture_swipe_update(data, event);
+    }
+
+    fn gesture_swipe_end(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GestureSwipeEndEvent,
+    ) {
+        handle.gesture_swipe_end(data, event);
+    }
+
+    fn gesture_pinch_begin(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GesturePinchBeginEvent,
+    ) {
+        handle.gesture_pinch_begin(data, event);
+    }
+
+    fn gesture_pinch_update(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GesturePinchUpdateEvent,
+    ) {
+        handle.gesture_pinch_update(data, event);
+    }
+
+    fn gesture_pinch_end(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GesturePinchEndEvent,
+    ) {
+        handle.gesture_pinch_end(data, event);
+    }
+
+    fn gesture_hold_begin(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GestureHoldBeginEvent,
+    ) {
+        handle.gesture_hold_begin(data, event);
+    }
+
+    fn gesture_hold_end(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GestureHoldEndEvent,
+    ) {
+        handle.gesture_hold_end(data, event);
+    }
+
+    fn start_data(&self) -> &PointerGrabStartData<CompositronState<BackendData>> {
+        &self.start_data
+    }
+
+    fn unset(&mut self, _data: &mut CompositronState<BackendData>) {}
+}
+
+pub struct TouchMoveSurfaceGrab<BackendData: Backend + 'static> {
+    pub start_data: TouchGrabStartData<CompositronState<BackendData>>,
+    pub window: WindowElement,
+    pub initial_window_location: Point<i32, Logical>,
+}
+
+impl<BackendData: Backend> TouchGrab<CompositronState<BackendData>>
+    for TouchMoveSurfaceGrab<BackendData>
+{
+    fn down(
+        &mut self,
+        _data: &mut CompositronState<BackendData>,
+        _handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        _focus: Option<(
+            <CompositronState<BackendData> as smithay::input::SeatHandler>::TouchFocus,
+            Point<f64, Logical>,
+        )>,
+        _event: &smithay::input::touch::DownEvent,
+        _seq: Serial,
+    ) {
+    }
+
+    fn up(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        event: &smithay::input::touch::UpEvent,
+        seq: Serial,
+    ) {
+        if event.slot != self.start_data.slot {
+            return;
+        }
+
+        handle.up(data, event, seq);
+        handle.unset_grab(self, data);
+    }
+
+    fn motion(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        _handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        _focus: Option<(
+            <CompositronState<BackendData> as smithay::input::SeatHandler>::TouchFocus,
+            Point<f64, Logical>,
+        )>,
+        event: &smithay::input::touch::MotionEvent,
+        _seq: Serial,
+    ) {
+        if event.slot != self.start_data.slot {
+            return;
+        }
+
+        let delta = event.location - self.start_data.location;
+        let new_location = self.initial_window_location.to_f64() + delta;
+        data.space
+            .map_element(self.window.clone(), new_location.to_i32_round(), true);
+    }
+
+    fn frame(
+        &mut self,
+        _data: &mut CompositronState<BackendData>,
+        _handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        _seq: Serial,
+    ) {
+    }
+
+    fn cancel(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        seq: Serial,
+    ) {
+        handle.cancel(data, seq);
+        handle.unset_grab(self, data);
+    }
+
+    fn shape(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        event: &smithay::input::touch::ShapeEvent,
+        seq: Serial,
+    ) {
+        handle.shape(data, event, seq);
+    }
+
+    fn orientation(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        event: &smithay::input::touch::OrientationEvent,
+        seq: Serial,
+    ) {
+        handle.orientation(data, event, seq);
+    }
+
+    fn start_data(&self) -> &smithay::input::touch::GrabStartData<CompositronState<BackendData>> {
+        &self.start_data
+    }
+
+    fn unset(&mut self, _data: &mut CompositronState<BackendData>) {}
+}
+
+bitflags::bitflags! {
+    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+    pub struct ResizeEdge: u32 {
+        const NONE = 0;
+        const TOP = 1;
+        const BOTTOM = 2;
+        const LEFT = 4;
+        const TOP_LEFT = 5;
+        const BOTTOM_LEFT = 6;
+        const RIGHT = 8;
+        const TOP_RIGHT = 9;
+        const BOTTOM_RIGHT = 10;
+    }
+}
+
+impl From<xdg_toplevel::ResizeEdge> for ResizeEdge {
+    #[inline]
+    fn from(x: xdg_toplevel::ResizeEdge) -> Self {
+        Self::from_bits(x as u32).unwrap()
+    }
+}
+
+impl From<ResizeEdge> for xdg_toplevel::ResizeEdge {
+    #[inline]
+    fn from(x: ResizeEdge) -> Self {
+        Self::try_from(x.bits()).unwrap()
+    }
+}
+
+#[cfg(feature = "xwayland")]
+impl From<X11ResizeEdge> for ResizeEdge {
+    #[inline]
+    fn from(edge: X11ResizeEdge) -> Self {
+        match edge {
+            X11ResizeEdge::Bottom => ResizeEdge::BOTTOM,
+            X11ResizeEdge::BottomLeft => ResizeEdge::BOTTOM_LEFT,
+            X11ResizeEdge::BottomRight => ResizeEdge::BOTTOM_RIGHT,
+            X11ResizeEdge::Left => ResizeEdge::LEFT,
+            X11ResizeEdge::Right => ResizeEdge::RIGHT,
+            X11ResizeEdge::Top => ResizeEdge::TOP,
+            X11ResizeEdge::TopLeft => ResizeEdge::TOP_LEFT,
+            X11ResizeEdge::TopRight => ResizeEdge::TOP_RIGHT,
+        }
+    }
+}
+
+/// Information about the resize operation.
+#[derive(Debug, Clone, Copy, Eq, PartialEq)]
+pub struct ResizeData {
+    /// The edges the surface is being resized with.
+    pub edges: ResizeEdge,
+    /// The initial window location.
+    pub initial_window_location: Point<i32, Logical>,
+    /// The initial window size (geometry width and height).
+    pub initial_window_size: Size<i32, Logical>,
+}
+
+/// State of the resize operation.
+#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
+pub enum ResizeState {
+    /// The surface is not being resized.
+    #[default]
+    NotResizing,
+    /// The surface is currently being resized.
+    Resizing(ResizeData),
+    /// The resize has finished, and the surface needs to ack the final configure.
+    WaitingForFinalAck(ResizeData, Serial),
+    /// The resize has finished, and the surface needs to commit its final state.
+    WaitingForCommit(ResizeData),
+}
+
+pub struct PointerResizeSurfaceGrab<BackendData: Backend + 'static> {
+    pub start_data: PointerGrabStartData<CompositronState<BackendData>>,
+    pub window: WindowElement,
+    pub edges: ResizeEdge,
+    pub initial_window_location: Point<i32, Logical>,
+    pub initial_window_size: Size<i32, Logical>,
+    pub last_window_size: Size<i32, Logical>,
+}
+
+impl<BackendData: Backend> PointerGrab<CompositronState<BackendData>>
+    for PointerResizeSurfaceGrab<BackendData>
+{
+    fn motion(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        _focus: Option<(PointerFocusTarget, Point<f64, Logical>)>,
+        event: &MotionEvent,
+    ) {
+        // While the grab is active, no client has pointer focus
+        handle.motion(data, None, event);
+
+        // It is impossible to get `min_size` and `max_size` of dead toplevel, so we return early.
+        if !self.window.alive() {
+            handle.unset_grab(self, data, event.serial, event.time, true);
+            return;
+        }
+
+        let (mut dx, mut dy) = (event.location - self.start_data.location).into();
+
+        let mut new_window_width = self.initial_window_size.w;
+        let mut new_window_height = self.initial_window_size.h;
+
+        let left_right = ResizeEdge::LEFT | ResizeEdge::RIGHT;
+        let top_bottom = ResizeEdge::TOP | ResizeEdge::BOTTOM;
+
+        if self.edges.intersects(left_right) {
+            if self.edges.intersects(ResizeEdge::LEFT) {
+                dx = -dx;
+            }
+
+            new_window_width = (self.initial_window_size.w as f64 + dx) as i32;
+        }
+
+        if self.edges.intersects(top_bottom) {
+            if self.edges.intersects(ResizeEdge::TOP) {
+                dy = -dy;
+            }
+
+            new_window_height = (self.initial_window_size.h as f64 + dy) as i32;
+        }
+
+        let (min_size, max_size) = if let Some(surface) = self.window.wl_surface() {
+            with_states(&surface, |states| {
+                let mut guard = states.cached_state.get::<SurfaceCachedState>();
+                let data = guard.current();
+                (data.min_size, data.max_size)
+            })
+        } else {
+            ((0, 0).into(), (0, 0).into())
+        };
+
+        let min_width = min_size.w.max(1);
+        let min_height = min_size.h.max(1);
+        let max_width = if max_size.w == 0 {
+            i32::MAX
+        } else {
+            max_size.w
+        };
+        let max_height = if max_size.h == 0 {
+            i32::MAX
+        } else {
+            max_size.h
+        };
+
+        new_window_width = new_window_width.max(min_width).min(max_width);
+        new_window_height = new_window_height.max(min_height).min(max_height);
+
+        self.last_window_size = (new_window_width, new_window_height).into();
+
+        match &self.window.0.underlying_surface() {
+            WindowSurface::Wayland(xdg) => {
+                xdg.with_pending_state(|state| {
+                    state.states.set(xdg_toplevel::State::Resizing);
+                    state.size = Some(self.last_window_size);
+                });
+                xdg.send_pending_configure();
+            }
+            #[cfg(feature = "xwayland")]
+            WindowSurface::X11(x11) => {
+                let location = data.space.element_location(&self.window).unwrap();
+                x11.configure(Rectangle::new(location, self.last_window_size))
+                    .unwrap();
+            }
+        }
+    }
+
+    fn relative_motion(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        focus: Option<(PointerFocusTarget, Point<f64, Logical>)>,
+        event: &RelativeMotionEvent,
+    ) {
+        handle.relative_motion(data, focus, event);
+    }
+
+    fn button(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &ButtonEvent,
+    ) {
+        handle.button(data, event);
+        if handle.current_pressed().is_empty() {
+            // No more buttons are pressed, release the grab.
+            handle.unset_grab(self, data, event.serial, event.time, true);
+
+            // If toplevel is dead, we can't resize it, so we return early.
+            if !self.window.alive() {
+                return;
+            }
+
+            match &self.window.0.underlying_surface() {
+                WindowSurface::Wayland(xdg) => {
+                    xdg.with_pending_state(|state| {
+                        state.states.unset(xdg_toplevel::State::Resizing);
+                        state.size = Some(self.last_window_size);
+                    });
+                    xdg.send_pending_configure();
+                    if self.edges.intersects(ResizeEdge::TOP_LEFT) {
+                        let geometry = self.window.geometry();
+                        let mut location = data.space.element_location(&self.window).unwrap();
+
+                        if self.edges.intersects(ResizeEdge::LEFT) {
+                            location.x = self.initial_window_location.x
+                                + (self.initial_window_size.w - geometry.size.w);
+                        }
+                        if self.edges.intersects(ResizeEdge::TOP) {
+                            location.y = self.initial_window_location.y
+                                + (self.initial_window_size.h - geometry.size.h);
+                        }
+
+                        data.space.map_element(self.window.clone(), location, true);
+                    }
+
+                    with_states(&self.window.wl_surface().unwrap(), |states| {
+                        let mut data = states
+                            .data_map
+                            .get::<RefCell<SurfaceData>>()
+                            .unwrap()
+                            .borrow_mut();
+                        if let ResizeState::Resizing(resize_data) = data.resize_state {
+                            data.resize_state =
+                                ResizeState::WaitingForFinalAck(resize_data, event.serial);
+                        } else {
+                            panic!("invalid resize state: {:?}", data.resize_state);
+                        }
+                    });
+                }
+                #[cfg(feature = "xwayland")]
+                WindowSurface::X11(x11) => {
+                    let mut location = data.space.element_location(&self.window).unwrap();
+                    if self.edges.intersects(ResizeEdge::TOP_LEFT) {
+                        let geometry = self.window.geometry();
+
+                        if self.edges.intersects(ResizeEdge::LEFT) {
+                            location.x = self.initial_window_location.x
+                                + (self.initial_window_size.w - geometry.size.w);
+                        }
+                        if self.edges.intersects(ResizeEdge::TOP) {
+                            location.y = self.initial_window_location.y
+                                + (self.initial_window_size.h - geometry.size.h);
+                        }
+
+                        data.space.map_element(self.window.clone(), location, true);
+                    }
+                    x11.configure(Rectangle::new(location, self.last_window_size))
+                        .unwrap();
+
+                    let Some(surface) = self.window.wl_surface() else {
+                        // X11 Window got unmapped, abort
+                        return;
+                    };
+                    with_states(&surface, |states| {
+                        let mut data = states
+                            .data_map
+                            .get::<RefCell<SurfaceData>>()
+                            .unwrap()
+                            .borrow_mut();
+                        if let ResizeState::Resizing(resize_data) = data.resize_state {
+                            data.resize_state = ResizeState::WaitingForCommit(resize_data);
+                        } else {
+                            panic!("invalid resize state: {:?}", data.resize_state);
+                        }
+                    });
+                }
+            }
+        }
+    }
+
+    fn axis(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        details: AxisFrame,
+    ) {
+        handle.axis(data, details)
+    }
+
+    fn frame(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+    ) {
+        handle.frame(data);
+    }
+
+    fn gesture_swipe_begin(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GestureSwipeBeginEvent,
+    ) {
+        handle.gesture_swipe_begin(data, event);
+    }
+
+    fn gesture_swipe_update(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GestureSwipeUpdateEvent,
+    ) {
+        handle.gesture_swipe_update(data, event);
+    }
+
+    fn gesture_swipe_end(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GestureSwipeEndEvent,
+    ) {
+        handle.gesture_swipe_end(data, event);
+    }
+
+    fn gesture_pinch_begin(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GesturePinchBeginEvent,
+    ) {
+        handle.gesture_pinch_begin(data, event);
+    }
+
+    fn gesture_pinch_update(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GesturePinchUpdateEvent,
+    ) {
+        handle.gesture_pinch_update(data, event);
+    }
+
+    fn gesture_pinch_end(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GesturePinchEndEvent,
+    ) {
+        handle.gesture_pinch_end(data, event);
+    }
+
+    fn gesture_hold_begin(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GestureHoldBeginEvent,
+    ) {
+        handle.gesture_hold_begin(data, event);
+    }
+
+    fn gesture_hold_end(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut PointerInnerHandle<'_, CompositronState<BackendData>>,
+        event: &GestureHoldEndEvent,
+    ) {
+        handle.gesture_hold_end(data, event);
+    }
+
+    fn start_data(&self) -> &PointerGrabStartData<CompositronState<BackendData>> {
+        &self.start_data
+    }
+
+    fn unset(&mut self, _data: &mut CompositronState<BackendData>) {}
+}
+
+pub struct TouchResizeSurfaceGrab<BackendData: Backend + 'static> {
+    pub start_data: TouchGrabStartData<CompositronState<BackendData>>,
+    pub window: WindowElement,
+    pub edges: ResizeEdge,
+    pub initial_window_location: Point<i32, Logical>,
+    pub initial_window_size: Size<i32, Logical>,
+    pub last_window_size: Size<i32, Logical>,
+}
+
+impl<BackendData: Backend> TouchGrab<CompositronState<BackendData>>
+    for TouchResizeSurfaceGrab<BackendData>
+{
+    fn down(
+        &mut self,
+        _data: &mut CompositronState<BackendData>,
+        _handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        _focus: Option<(
+            <CompositronState<BackendData> as smithay::input::SeatHandler>::TouchFocus,
+            Point<f64, Logical>,
+        )>,
+        _event: &smithay::input::touch::DownEvent,
+        _seq: Serial,
+    ) {
+    }
+
+    fn up(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        event: &smithay::input::touch::UpEvent,
+        _seq: Serial,
+    ) {
+        if event.slot != self.start_data.slot {
+            return;
+        }
+        handle.unset_grab(self, data);
+
+        // If toplevel is dead, we can't resize it, so we return early.
+        if !self.window.alive() {
+            return;
+        }
+
+        match self.window.0.underlying_surface() {
+            WindowSurface::Wayland(xdg) => {
+                xdg.with_pending_state(|state| {
+                    state.states.unset(xdg_toplevel::State::Resizing);
+                    state.size = Some(self.last_window_size);
+                });
+                xdg.send_pending_configure();
+                if self.edges.intersects(ResizeEdge::TOP_LEFT) {
+                    let geometry = self.window.geometry();
+                    let mut location = data.space.element_location(&self.window).unwrap();
+
+                    if self.edges.intersects(ResizeEdge::LEFT) {
+                        location.x = self.initial_window_location.x
+                            + (self.initial_window_size.w - geometry.size.w);
+                    }
+                    if self.edges.intersects(ResizeEdge::TOP) {
+                        location.y = self.initial_window_location.y
+                            + (self.initial_window_size.h - geometry.size.h);
+                    }
+
+                    data.space.map_element(self.window.clone(), location, true);
+                }
+
+                with_states(&self.window.wl_surface().unwrap(), |states| {
+                    let mut data = states
+                        .data_map
+                        .get::<RefCell<SurfaceData>>()
+                        .unwrap()
+                        .borrow_mut();
+                    if let ResizeState::Resizing(resize_data) = data.resize_state {
+                        data.resize_state =
+                            ResizeState::WaitingForFinalAck(resize_data, event.serial);
+                    } else {
+                        panic!("invalid resize state: {:?}", data.resize_state);
+                    }
+                });
+            }
+            #[cfg(feature = "xwayland")]
+            WindowSurface::X11(x11) => {
+                let mut location = data.space.element_location(&self.window).unwrap();
+                if self.edges.intersects(ResizeEdge::TOP_LEFT) {
+                    let geometry = self.window.geometry();
+
+                    if self.edges.intersects(ResizeEdge::LEFT) {
+                        location.x = self.initial_window_location.x
+                            + (self.initial_window_size.w - geometry.size.w);
+                    }
+                    if self.edges.intersects(ResizeEdge::TOP) {
+                        location.y = self.initial_window_location.y
+                            + (self.initial_window_size.h - geometry.size.h);
+                    }
+
+                    data.space.map_element(self.window.clone(), location, true);
+                }
+                x11.configure(Rectangle::new(location, self.last_window_size))
+                    .unwrap();
+
+                let Some(surface) = self.window.wl_surface() else {
+                    // X11 Window got unmapped, abort
+                    return;
+                };
+                with_states(&surface, |states| {
+                    let mut data = states
+                        .data_map
+                        .get::<RefCell<SurfaceData>>()
+                        .unwrap()
+                        .borrow_mut();
+                    if let ResizeState::Resizing(resize_data) = data.resize_state {
+                        data.resize_state = ResizeState::WaitingForCommit(resize_data);
+                    } else {
+                        panic!("invalid resize state: {:?}", data.resize_state);
+                    }
+                });
+            }
+        }
+    }
+
+    fn motion(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        _focus: Option<(
+            <CompositronState<BackendData> as smithay::input::SeatHandler>::TouchFocus,
+            Point<f64, Logical>,
+        )>,
+        event: &smithay::input::touch::MotionEvent,
+        _seq: Serial,
+    ) {
+        if event.slot != self.start_data.slot {
+            return;
+        }
+
+        // It is impossible to get `min_size` and `max_size` of dead toplevel, so we return early.
+        if !self.window.alive() {
+            handle.unset_grab(self, data);
+            return;
+        }
+
+        let (mut dx, mut dy) = (event.location - self.start_data.location).into();
+
+        let mut new_window_width = self.initial_window_size.w;
+        let mut new_window_height = self.initial_window_size.h;
+
+        let left_right = ResizeEdge::LEFT | ResizeEdge::RIGHT;
+        let top_bottom = ResizeEdge::TOP | ResizeEdge::BOTTOM;
+
+        if self.edges.intersects(left_right) {
+            if self.edges.intersects(ResizeEdge::LEFT) {
+                dx = -dx;
+            }
+
+            new_window_width = (self.initial_window_size.w as f64 + dx) as i32;
+        }
+
+        if self.edges.intersects(top_bottom) {
+            if self.edges.intersects(ResizeEdge::TOP) {
+                dy = -dy;
+            }
+
+            new_window_height = (self.initial_window_size.h as f64 + dy) as i32;
+        }
+
+        let (min_size, max_size) = if let Some(surface) = self.window.wl_surface() {
+            with_states(&surface, |states| {
+                let mut guard = states.cached_state.get::<SurfaceCachedState>();
+                let data = guard.current();
+                (data.min_size, data.max_size)
+            })
+        } else {
+            ((0, 0).into(), (0, 0).into())
+        };
+
+        let min_width = min_size.w.max(1);
+        let min_height = min_size.h.max(1);
+        let max_width = if max_size.w == 0 {
+            i32::MAX
+        } else {
+            max_size.w
+        };
+        let max_height = if max_size.h == 0 {
+            i32::MAX
+        } else {
+            max_size.h
+        };
+
+        new_window_width = new_window_width.max(min_width).min(max_width);
+        new_window_height = new_window_height.max(min_height).min(max_height);
+
+        self.last_window_size = (new_window_width, new_window_height).into();
+
+        match self.window.0.underlying_surface() {
+            WindowSurface::Wayland(xdg) => {
+                xdg.with_pending_state(|state| {
+                    state.states.set(xdg_toplevel::State::Resizing);
+                    state.size = Some(self.last_window_size);
+                });
+                xdg.send_pending_configure();
+            }
+            #[cfg(feature = "xwayland")]
+            WindowSurface::X11(x11) => {
+                let location = data.space.element_location(&self.window).unwrap();
+                x11.configure(Rectangle::new(location, self.last_window_size))
+                    .unwrap();
+            }
+        }
+    }
+
+    fn frame(
+        &mut self,
+        _data: &mut CompositronState<BackendData>,
+        _handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        _seq: Serial,
+    ) {
+    }
+
+    fn cancel(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        seq: Serial,
+    ) {
+        handle.cancel(data, seq);
+        handle.unset_grab(self, data);
+    }
+
+    fn shape(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        event: &smithay::input::touch::ShapeEvent,
+        seq: Serial,
+    ) {
+        handle.shape(data, event, seq);
+    }
+
+    fn orientation(
+        &mut self,
+        data: &mut CompositronState<BackendData>,
+        handle: &mut smithay::input::touch::TouchInnerHandle<'_, CompositronState<BackendData>>,
+        event: &smithay::input::touch::OrientationEvent,
+        seq: Serial,
+    ) {
+        handle.orientation(data, event, seq);
+    }
+
+    fn start_data(&self) -> &smithay::input::touch::GrabStartData<CompositronState<BackendData>> {
+        &self.start_data
+    }
+
+    fn unset(&mut self, _data: &mut CompositronState<BackendData>) {}
+}

+ 482 - 0
src/shell/mod.rs

@@ -0,0 +1,482 @@
+use std::cell::RefCell;
+
+#[cfg(feature = "xwayland")]
+use smithay::xwayland::XWaylandClientData;
+
+#[cfg(feature = "udev")]
+use smithay::wayland::drm_syncobj::DrmSyncobjCachedState;
+
+use smithay::{
+    backend::renderer::utils::on_commit_buffer_handler,
+    desktop::{
+        layer_map_for_output, space::SpaceElement, LayerSurface, PopupKind, PopupManager, Space,
+        WindowSurfaceType,
+    },
+    input::pointer::{CursorImageStatus, CursorImageSurfaceData},
+    output::Output,
+    reexports::{
+        calloop::Interest,
+        wayland_server::{
+            protocol::{wl_buffer::WlBuffer, wl_output, wl_surface::WlSurface},
+            Client, Resource,
+        },
+    },
+    utils::{IsAlive, Logical, Point, Rectangle, Size},
+    wayland::{
+        buffer::BufferHandler,
+        compositor::{
+            add_blocker, add_pre_commit_hook, get_parent, is_sync_subsurface, with_states,
+            with_surface_tree_upward, BufferAssignment, CompositorClientState, CompositorHandler,
+            CompositorState, SurfaceAttributes, TraversalAction,
+        },
+        dmabuf::get_dmabuf,
+        shell::{
+            wlr_layer::{
+                Layer, LayerSurface as WlrLayerSurface, LayerSurfaceData, WlrLayerShellHandler,
+                WlrLayerShellState,
+            },
+            xdg::XdgToplevelSurfaceData,
+        },
+    },
+};
+
+use crate::{
+    state::{Backend, CompositronState},
+    ClientState,
+};
+
+mod element;
+mod grabs;
+pub(crate) mod ssd;
+mod xdg;
+
+pub use self::element::*;
+pub use self::grabs::*;
+
+fn fullscreen_output_geometry(
+    wl_surface: &WlSurface,
+    wl_output: Option<&wl_output::WlOutput>,
+    space: &mut Space<WindowElement>,
+) -> Option<Rectangle<i32, Logical>> {
+    // First test if a specific output has been requested
+    // if the requested output is not found ignore the request
+    wl_output
+        .and_then(Output::from_resource)
+        .or_else(|| {
+            let w = space.elements().find(|window| {
+                window
+                    .wl_surface()
+                    .map(|s| &*s == wl_surface)
+                    .unwrap_or(false)
+            });
+            w.and_then(|w| space.outputs_for_element(w).first().cloned())
+        })
+        .as_ref()
+        .and_then(|o| space.output_geometry(o))
+}
+
+#[derive(Default)]
+pub struct FullscreenSurface(RefCell<Option<WindowElement>>);
+
+impl FullscreenSurface {
+    pub fn set(&self, window: WindowElement) {
+        *self.0.borrow_mut() = Some(window);
+    }
+
+    pub fn get(&self) -> Option<WindowElement> {
+        let mut window = self.0.borrow_mut();
+        if window.as_ref().map(|w| !w.alive()).unwrap_or(false) {
+            *window = None;
+        }
+        window.clone()
+    }
+
+    pub fn clear(&self) -> Option<WindowElement> {
+        self.0.borrow_mut().take()
+    }
+}
+
+impl<BackendData: Backend> BufferHandler for CompositronState<BackendData> {
+    fn buffer_destroyed(&mut self, _buffer: &WlBuffer) {}
+}
+
+impl<BackendData: Backend> CompositorHandler for CompositronState<BackendData> {
+    fn compositor_state(&mut self) -> &mut CompositorState {
+        &mut self.compositor_state
+    }
+    fn client_compositor_state<'a>(&self, client: &'a Client) -> &'a CompositorClientState {
+        #[cfg(feature = "xwayland")]
+        if let Some(state) = client.get_data::<XWaylandClientData>() {
+            return &state.compositor_state;
+        }
+        if let Some(state) = client.get_data::<ClientState>() {
+            return &state.compositor_state;
+        }
+        panic!("Unknown client data type")
+    }
+
+    fn new_surface(&mut self, surface: &WlSurface) {
+        add_pre_commit_hook::<Self, _>(surface, move |state, _dh, surface| {
+            #[cfg(feature = "udev")]
+            let mut acquire_point = None;
+            let maybe_dmabuf = with_states(surface, |surface_data| {
+                #[cfg(feature = "udev")]
+                acquire_point.clone_from(
+                    &surface_data
+                        .cached_state
+                        .get::<DrmSyncobjCachedState>()
+                        .pending()
+                        .acquire_point,
+                );
+                surface_data
+                    .cached_state
+                    .get::<SurfaceAttributes>()
+                    .pending()
+                    .buffer
+                    .as_ref()
+                    .and_then(|assignment| match assignment {
+                        BufferAssignment::NewBuffer(buffer) => get_dmabuf(buffer).cloned().ok(),
+                        _ => None,
+                    })
+            });
+            if let Some(dmabuf) = maybe_dmabuf {
+                #[cfg(feature = "udev")]
+                if let Some(acquire_point) = acquire_point {
+                    if let Ok((blocker, source)) = acquire_point.generate_blocker() {
+                        let client = surface.client().unwrap();
+                        let res = state.handle.insert_source(source, move |_, _, data| {
+                            let dh = data.display_handle.clone();
+                            data.client_compositor_state(&client)
+                                .blocker_cleared(data, &dh);
+                            Ok(())
+                        });
+                        if res.is_ok() {
+                            add_blocker(surface, blocker);
+                            return;
+                        }
+                    }
+                }
+                if let Ok((blocker, source)) = dmabuf.generate_blocker(Interest::READ) {
+                    if let Some(client) = surface.client() {
+                        let res = state.handle.insert_source(source, move |_, _, data| {
+                            let dh = data.display_handle.clone();
+                            data.client_compositor_state(&client)
+                                .blocker_cleared(data, &dh);
+                            Ok(())
+                        });
+                        if res.is_ok() {
+                            add_blocker(surface, blocker);
+                        }
+                    }
+                }
+            }
+        });
+    }
+
+    fn commit(&mut self, surface: &WlSurface) {
+        on_commit_buffer_handler::<Self>(surface);
+        self.backend_data.early_import(surface);
+
+        if !is_sync_subsurface(surface) {
+            let mut root = surface.clone();
+            while let Some(parent) = get_parent(&root) {
+                root = parent;
+            }
+            if let Some(window) = self.window_for_surface(&root) {
+                window.0.on_commit();
+
+                if &root == surface {
+                    let buffer_offset = with_states(surface, |states| {
+                        states
+                            .cached_state
+                            .get::<SurfaceAttributes>()
+                            .current()
+                            .buffer_delta
+                            .take()
+                    });
+
+                    if let Some(buffer_offset) = buffer_offset {
+                        let current_loc = self.space.element_location(&window).unwrap();
+                        self.space
+                            .map_element(window, current_loc + buffer_offset, false);
+                    }
+                }
+            }
+        }
+        self.popups.commit(surface);
+
+        if matches!(&self.cursor_status, CursorImageStatus::Surface(cursor_surface) if cursor_surface == surface)
+        {
+            with_states(surface, |states| {
+                let cursor_image_attributes = states.data_map.get::<CursorImageSurfaceData>();
+
+                if let Some(mut cursor_image_attributes) =
+                    cursor_image_attributes.map(|attrs| attrs.lock().unwrap())
+                {
+                    let buffer_delta = states
+                        .cached_state
+                        .get::<SurfaceAttributes>()
+                        .current()
+                        .buffer_delta
+                        .take();
+                    if let Some(buffer_delta) = buffer_delta {
+                        tracing::trace!(hotspot = ?cursor_image_attributes.hotspot, ?buffer_delta, "decrementing cursor hotspot");
+                        cursor_image_attributes.hotspot -= buffer_delta;
+                    }
+                }
+            });
+        }
+
+        if matches!(&self.dnd_icon, Some(icon) if &icon.surface == surface) {
+            let dnd_icon = self.dnd_icon.as_mut().unwrap();
+            with_states(&dnd_icon.surface, |states| {
+                let buffer_delta = states
+                    .cached_state
+                    .get::<SurfaceAttributes>()
+                    .current()
+                    .buffer_delta
+                    .take()
+                    .unwrap_or_default();
+                tracing::trace!(offset = ?dnd_icon.offset, ?buffer_delta, "moving dnd offset");
+                dnd_icon.offset += buffer_delta;
+            });
+        }
+
+        ensure_initial_configure(surface, &self.space, &mut self.popups)
+    }
+}
+
+impl<BackendData: Backend> WlrLayerShellHandler for CompositronState<BackendData> {
+    fn shell_state(&mut self) -> &mut WlrLayerShellState {
+        &mut self.layer_shell_state
+    }
+
+    fn new_layer_surface(
+        &mut self,
+        surface: WlrLayerSurface,
+        wl_output: Option<wl_output::WlOutput>,
+        _layer: Layer,
+        namespace: String,
+    ) {
+        let output = wl_output
+            .as_ref()
+            .and_then(Output::from_resource)
+            .unwrap_or_else(|| self.space.outputs().next().unwrap().clone());
+        let mut map = layer_map_for_output(&output);
+        map.map_layer(&LayerSurface::new(surface, namespace))
+            .unwrap();
+    }
+
+    fn layer_destroyed(&mut self, surface: WlrLayerSurface) {
+        if let Some((mut map, layer)) = self.space.outputs().find_map(|o| {
+            let map = layer_map_for_output(o);
+            let layer = map
+                .layers()
+                .find(|&layer| layer.layer_surface() == &surface)
+                .cloned();
+            layer.map(|layer| (map, layer))
+        }) {
+            map.unmap_layer(&layer);
+        }
+    }
+}
+
+impl<BackendData: Backend> CompositronState<BackendData> {
+    pub fn window_for_surface(&self, surface: &WlSurface) -> Option<WindowElement> {
+        self.space
+            .elements()
+            .find(|window| window.wl_surface().map(|s| &*s == surface).unwrap_or(false))
+            .cloned()
+    }
+}
+
+#[derive(Default)]
+pub struct SurfaceData {
+    pub geometry: Option<Rectangle<i32, Logical>>,
+    pub resize_state: ResizeState,
+}
+
+fn ensure_initial_configure(
+    surface: &WlSurface,
+    space: &Space<WindowElement>,
+    popups: &mut PopupManager,
+) {
+    with_surface_tree_upward(
+        surface,
+        (),
+        |_, _, _| TraversalAction::DoChildren(()),
+        |_, states, _| {
+            states
+                .data_map
+                .insert_if_missing(|| RefCell::new(SurfaceData::default()));
+        },
+        |_, _, _| true,
+    );
+
+    if let Some(window) = space
+        .elements()
+        .find(|window| window.wl_surface().map(|s| &*s == surface).unwrap_or(false))
+        .cloned()
+    {
+        // send the initial configure if relevant
+        #[cfg_attr(not(feature = "xwayland"), allow(irrefutable_let_patterns))]
+        if let Some(toplevel) = window.0.toplevel() {
+            let initial_configure_sent = with_states(surface, |states| {
+                states
+                    .data_map
+                    .get::<XdgToplevelSurfaceData>()
+                    .unwrap()
+                    .lock()
+                    .unwrap()
+                    .initial_configure_sent
+            });
+            if !initial_configure_sent {
+                toplevel.send_configure();
+            }
+        }
+
+        with_states(surface, |states| {
+            let mut data = states
+                .data_map
+                .get::<RefCell<SurfaceData>>()
+                .unwrap()
+                .borrow_mut();
+
+            // Finish resizing.
+            if let ResizeState::WaitingForCommit(_) = data.resize_state {
+                data.resize_state = ResizeState::NotResizing;
+            }
+        });
+
+        return;
+    }
+
+    if let Some(popup) = popups.find_popup(surface) {
+        let popup = match popup {
+            PopupKind::Xdg(ref popup) => popup,
+            // Doesn't require configure
+            PopupKind::InputMethod(ref _input_popup) => {
+                return;
+            }
+        };
+
+        if !popup.is_initial_configure_sent() {
+            // NOTE: This should never fail as the initial configure is always
+            // allowed.
+            popup.send_configure().expect("initial configure failed");
+        }
+
+        return;
+    };
+
+    if let Some(output) = space.outputs().find(|o| {
+        let map = layer_map_for_output(o);
+        map.layer_for_surface(surface, WindowSurfaceType::TOPLEVEL)
+            .is_some()
+    }) {
+        let initial_configure_sent = with_states(surface, |states| {
+            states
+                .data_map
+                .get::<LayerSurfaceData>()
+                .unwrap()
+                .lock()
+                .unwrap()
+                .initial_configure_sent
+        });
+
+        let mut map = layer_map_for_output(output);
+
+        // arrange the layers before sending the initial configure
+        // to respect any size the client may have sent
+        map.arrange();
+        // send the initial configure if relevant
+        if !initial_configure_sent {
+            let layer = map
+                .layer_for_surface(surface, WindowSurfaceType::TOPLEVEL)
+                .unwrap();
+
+            layer.layer_surface().send_configure();
+        }
+    };
+}
+
+fn place_new_window(
+    space: &mut Space<WindowElement>,
+    pointer_location: Point<f64, Logical>,
+    window: &WindowElement,
+    activate: bool,
+) {
+    // Place new windows in a gentle cascade on the output under the pointer.
+    let output = space
+        .output_under(pointer_location)
+        .next()
+        .or_else(|| space.outputs().next())
+        .cloned();
+    let output_geometry = output
+        .as_ref()
+        .and_then(|o| {
+            let geo = space.output_geometry(o)?;
+            let map = layer_map_for_output(o);
+            let zone = map.non_exclusive_zone();
+            Some(Rectangle::new(geo.loc + zone.loc, zone.size))
+        })
+        .unwrap_or_else(|| Rectangle::from_size((800, 800).into()));
+
+    // Set the initial toplevel bounds.
+    #[allow(irrefutable_let_patterns)]
+    if let Some(toplevel) = window.0.toplevel() {
+        toplevel.with_pending_state(|state| {
+            state.bounds = Some(output_geometry.size);
+        });
+    }
+
+    let count = output
+        .as_ref()
+        .map(|output| space.elements_for_output(output).count())
+        .unwrap_or(0);
+    let cascade = (count % 8) as i32 * 28;
+    let x = output_geometry.loc.x + output_geometry.size.w / 4 + cascade;
+    let y = output_geometry.loc.y + output_geometry.size.h / 5 + cascade;
+
+    space.map_element(window.clone(), (x, y), activate);
+}
+
+pub fn fixup_positions(space: &mut Space<WindowElement>, pointer_location: Point<f64, Logical>) {
+    // fixup outputs
+    let mut offset = Point::<i32, Logical>::from((0, 0));
+    for output in space.outputs().cloned().collect::<Vec<_>>().into_iter() {
+        let size = space
+            .output_geometry(&output)
+            .map(|geo| geo.size)
+            .unwrap_or_else(|| Size::from((0, 0)));
+        space.map_output(&output, offset);
+        layer_map_for_output(&output).arrange();
+        offset.x += size.w;
+    }
+
+    // fixup windows
+    let mut orphaned_windows = Vec::new();
+    let outputs = space
+        .outputs()
+        .flat_map(|o| {
+            let geo = space.output_geometry(o)?;
+            let map = layer_map_for_output(o);
+            let zone = map.non_exclusive_zone();
+            Some(Rectangle::new(geo.loc + zone.loc, zone.size))
+        })
+        .collect::<Vec<_>>();
+    for window in space.elements() {
+        let window_location = match space.element_location(window) {
+            Some(loc) => loc,
+            None => continue,
+        };
+        let geo_loc = window.bbox().loc + window_location;
+
+        if !outputs.iter().any(|o_geo| o_geo.contains(geo_loc)) {
+            orphaned_windows.push(window.clone());
+        }
+    }
+    for window in orphaned_windows.into_iter() {
+        place_new_window(space, pointer_location, &window, false);
+    }
+}

+ 309 - 0
src/shell/ssd.rs

@@ -0,0 +1,309 @@
+use smithay::{
+    backend::renderer::{
+        element::{
+            solid::{SolidColorBuffer, SolidColorRenderElement},
+            AsRenderElements, Kind,
+        },
+        Renderer,
+    },
+    desktop::WindowSurface,
+    input::Seat,
+    utils::{Logical, Point, Serial},
+    wayland::shell::xdg::XdgShellHandler,
+};
+
+use std::cell::{RefCell, RefMut};
+
+use crate::{state::Backend, CompositronState};
+
+use super::WindowElement;
+
+pub struct WindowState {
+    pub is_ssd: bool,
+    pub header_bar: HeaderBar,
+}
+
+#[derive(Debug, Clone)]
+pub struct HeaderBar {
+    pub pointer_loc: Option<Point<f64, Logical>>,
+    pub width: u32,
+    pub close_button_hover: bool,
+    pub maximize_button_hover: bool,
+    pub background: SolidColorBuffer,
+    pub close_button: SolidColorBuffer,
+    pub maximize_button: SolidColorBuffer,
+}
+
+const BG_COLOR: [f32; 4] = [0.75f32, 0.9f32, 0.78f32, 1f32];
+const MAX_COLOR: [f32; 4] = [1f32, 0.965f32, 0.71f32, 1f32];
+const CLOSE_COLOR: [f32; 4] = [1f32, 0.66f32, 0.612f32, 1f32];
+const MAX_COLOR_HOVER: [f32; 4] = [0.71f32, 0.624f32, 0f32, 1f32];
+const CLOSE_COLOR_HOVER: [f32; 4] = [0.75f32, 0.11f32, 0.016f32, 1f32];
+
+pub const HEADER_BAR_HEIGHT: i32 = 32;
+const BUTTON_HEIGHT: u32 = HEADER_BAR_HEIGHT as u32;
+const BUTTON_WIDTH: u32 = 32;
+
+impl HeaderBar {
+    pub fn pointer_enter(&mut self, loc: Point<f64, Logical>) {
+        self.pointer_loc = Some(loc);
+    }
+
+    pub fn pointer_leave(&mut self) {
+        self.pointer_loc = None;
+    }
+
+    pub fn clicked<BackendData: Backend>(
+        &mut self,
+        seat: &Seat<CompositronState<BackendData>>,
+        state: &mut CompositronState<BackendData>,
+        window: &WindowElement,
+        serial: Serial,
+    ) {
+        match self.pointer_loc.as_ref() {
+            Some(loc) if loc.x >= (self.width - BUTTON_WIDTH) as f64 => {
+                match window.0.underlying_surface() {
+                    WindowSurface::Wayland(w) => w.send_close(),
+                    #[cfg(feature = "xwayland")]
+                    WindowSurface::X11(w) => {
+                        let _ = w.close();
+                    }
+                };
+            }
+            Some(loc) if loc.x >= (self.width - (BUTTON_WIDTH * 2)) as f64 => {
+                match window.0.underlying_surface() {
+                    WindowSurface::Wayland(w) => state.maximize_request(w.clone()),
+                    #[cfg(feature = "xwayland")]
+                    WindowSurface::X11(w) => {
+                        let surface = w.clone();
+                        state
+                            .handle
+                            .insert_idle(move |data| data.maximize_request_x11(&surface));
+                    }
+                };
+            }
+            Some(_) => {
+                match window.0.underlying_surface() {
+                    WindowSurface::Wayland(w) => {
+                        let seat = seat.clone();
+                        let toplevel = w.clone();
+                        state.handle.insert_idle(move |data| {
+                            data.move_request_xdg(&toplevel, &seat, serial)
+                        });
+                    }
+                    #[cfg(feature = "xwayland")]
+                    WindowSurface::X11(w) => {
+                        let window = w.clone();
+                        state
+                            .handle
+                            .insert_idle(move |data| data.move_request_x11(&window));
+                    }
+                };
+            }
+            _ => {}
+        };
+    }
+
+    pub fn touch_down<BackendData: Backend>(
+        &mut self,
+        seat: &Seat<CompositronState<BackendData>>,
+        state: &mut CompositronState<BackendData>,
+        window: &WindowElement,
+        serial: Serial,
+    ) {
+        match self.pointer_loc.as_ref() {
+            Some(loc) if loc.x >= (self.width - BUTTON_WIDTH) as f64 => {}
+            Some(loc) if loc.x >= (self.width - (BUTTON_WIDTH * 2)) as f64 => {}
+            Some(_) => {
+                match window.0.underlying_surface() {
+                    WindowSurface::Wayland(w) => {
+                        let seat = seat.clone();
+                        let toplevel = w.clone();
+                        state.handle.insert_idle(move |data| {
+                            data.move_request_xdg(&toplevel, &seat, serial)
+                        });
+                    }
+                    #[cfg(feature = "xwayland")]
+                    WindowSurface::X11(w) => {
+                        let window = w.clone();
+                        state
+                            .handle
+                            .insert_idle(move |data| data.move_request_x11(&window));
+                    }
+                };
+            }
+            _ => {}
+        };
+    }
+
+    pub fn touch_up<BackendData: Backend>(
+        &mut self,
+        _seat: &Seat<CompositronState<BackendData>>,
+        state: &mut CompositronState<BackendData>,
+        window: &WindowElement,
+        _serial: Serial,
+    ) {
+        match self.pointer_loc.as_ref() {
+            Some(loc) if loc.x >= (self.width - BUTTON_WIDTH) as f64 => {
+                match window.0.underlying_surface() {
+                    WindowSurface::Wayland(w) => w.send_close(),
+                    #[cfg(feature = "xwayland")]
+                    WindowSurface::X11(w) => {
+                        let _ = w.close();
+                    }
+                };
+            }
+            Some(loc) if loc.x >= (self.width - (BUTTON_WIDTH * 2)) as f64 => {
+                match window.0.underlying_surface() {
+                    WindowSurface::Wayland(w) => state.maximize_request(w.clone()),
+                    #[cfg(feature = "xwayland")]
+                    WindowSurface::X11(w) => {
+                        let surface = w.clone();
+                        state
+                            .handle
+                            .insert_idle(move |data| data.maximize_request_x11(&surface));
+                    }
+                };
+            }
+            _ => {}
+        };
+    }
+
+    pub fn redraw(&mut self, width: u32) {
+        if width == 0 {
+            self.width = 0;
+            return;
+        }
+
+        self.background
+            .update((width as i32, HEADER_BAR_HEIGHT), BG_COLOR);
+
+        let mut needs_redraw_buttons = false;
+        if width != self.width {
+            needs_redraw_buttons = true;
+            self.width = width;
+        }
+
+        if self
+            .pointer_loc
+            .as_ref()
+            .map(|l| l.x >= (width - BUTTON_WIDTH) as f64)
+            .unwrap_or(false)
+            && (needs_redraw_buttons || !self.close_button_hover)
+        {
+            self.close_button.update(
+                (BUTTON_WIDTH as i32, BUTTON_HEIGHT as i32),
+                CLOSE_COLOR_HOVER,
+            );
+            self.close_button_hover = true;
+        } else if !self
+            .pointer_loc
+            .as_ref()
+            .map(|l| l.x >= (width - BUTTON_WIDTH) as f64)
+            .unwrap_or(false)
+            && (needs_redraw_buttons || self.close_button_hover)
+        {
+            self.close_button
+                .update((BUTTON_WIDTH as i32, BUTTON_HEIGHT as i32), CLOSE_COLOR);
+            self.close_button_hover = false;
+        }
+
+        if self
+            .pointer_loc
+            .as_ref()
+            .map(|l| {
+                l.x >= (width - BUTTON_WIDTH * 2) as f64 && l.x <= (width - BUTTON_WIDTH) as f64
+            })
+            .unwrap_or(false)
+            && (needs_redraw_buttons || !self.maximize_button_hover)
+        {
+            self.maximize_button
+                .update((BUTTON_WIDTH as i32, BUTTON_HEIGHT as i32), MAX_COLOR_HOVER);
+            self.maximize_button_hover = true;
+        } else if !self
+            .pointer_loc
+            .as_ref()
+            .map(|l| {
+                l.x >= (width - BUTTON_WIDTH * 2) as f64 && l.x <= (width - BUTTON_WIDTH) as f64
+            })
+            .unwrap_or(false)
+            && (needs_redraw_buttons || self.maximize_button_hover)
+        {
+            self.maximize_button
+                .update((BUTTON_WIDTH as i32, BUTTON_HEIGHT as i32), MAX_COLOR);
+            self.maximize_button_hover = false;
+        }
+    }
+}
+
+impl<R: Renderer> AsRenderElements<R> for HeaderBar {
+    type RenderElement = SolidColorRenderElement;
+
+    fn render_elements<C: From<Self::RenderElement>>(
+        &self,
+        _renderer: &mut R,
+        location: Point<i32, smithay::utils::Physical>,
+        scale: smithay::utils::Scale<f64>,
+        alpha: f32,
+    ) -> Vec<C> {
+        let header_end_offset: Point<i32, Logical> = Point::from((self.width as i32, 0));
+        let button_offset: Point<i32, Logical> = Point::from((BUTTON_WIDTH as i32, 0));
+
+        vec![
+            SolidColorRenderElement::from_buffer(
+                &self.close_button,
+                location + (header_end_offset - button_offset).to_physical_precise_round(scale),
+                scale,
+                alpha,
+                Kind::Unspecified,
+            )
+            .into(),
+            SolidColorRenderElement::from_buffer(
+                &self.maximize_button,
+                location
+                    + (header_end_offset - button_offset.upscale(2))
+                        .to_physical_precise_round(scale),
+                scale,
+                alpha,
+                Kind::Unspecified,
+            )
+            .into(),
+            SolidColorRenderElement::from_buffer(
+                &self.background,
+                location,
+                scale,
+                alpha,
+                Kind::Unspecified,
+            )
+            .into(),
+        ]
+    }
+}
+
+impl WindowElement {
+    pub fn decoration_state(&self) -> RefMut<'_, WindowState> {
+        self.user_data().insert_if_missing(|| {
+            RefCell::new(WindowState {
+                is_ssd: false,
+                header_bar: HeaderBar {
+                    pointer_loc: None,
+                    width: 0,
+                    close_button_hover: false,
+                    maximize_button_hover: false,
+                    background: SolidColorBuffer::default(),
+                    close_button: SolidColorBuffer::default(),
+                    maximize_button: SolidColorBuffer::default(),
+                },
+            })
+        });
+
+        self.user_data()
+            .get::<RefCell<WindowState>>()
+            .unwrap()
+            .borrow_mut()
+    }
+
+    pub fn set_ssd(&self, ssd: bool) {
+        self.decoration_state().is_ssd = ssd;
+    }
+}

+ 691 - 0
src/shell/xdg.rs

@@ -0,0 +1,691 @@
+use std::cell::RefCell;
+
+use smithay::{
+    desktop::{
+        find_popup_root_surface, get_popup_toplevel_coords, layer_map_for_output,
+        space::SpaceElement, PopupKeyboardGrab, PopupKind, PopupPointerGrab, PopupUngrabStrategy,
+        Space, Window, WindowSurfaceType,
+    },
+    input::{pointer::Focus, Seat},
+    output::Output,
+    reexports::{
+        wayland_protocols::xdg::{decoration as xdg_decoration, shell::server::xdg_toplevel},
+        wayland_server::{
+            protocol::{wl_output, wl_seat, wl_surface::WlSurface},
+            Resource,
+        },
+    },
+    utils::{Logical, Point, Serial},
+    wayland::{
+        compositor::{self, with_states},
+        seat::WaylandFocus,
+        shell::xdg::{
+            Configure, PopupSurface, PositionerState, ToplevelSurface, XdgShellHandler,
+            XdgShellState, XdgToplevelSurfaceData,
+        },
+    },
+};
+use tracing::{trace, warn};
+
+use crate::{
+    focus::KeyboardFocusTarget,
+    shell::{TouchMoveSurfaceGrab, TouchResizeSurfaceGrab},
+    state::{Backend, CompositronState},
+};
+
+use super::{
+    fullscreen_output_geometry, place_new_window, FullscreenSurface, PointerMoveSurfaceGrab,
+    PointerResizeSurfaceGrab, ResizeData, ResizeEdge, ResizeState, SurfaceData, WindowElement,
+};
+
+impl<BackendData: Backend> XdgShellHandler for CompositronState<BackendData> {
+    fn xdg_shell_state(&mut self) -> &mut XdgShellState {
+        &mut self.xdg_shell_state
+    }
+
+    fn new_toplevel(&mut self, surface: ToplevelSurface) {
+        // Do not send a configure here, the initial configure
+        // of a xdg_surface has to be sent during the commit if
+        // the surface is not already configured
+        let window = WindowElement(Window::new_wayland_window(surface.clone()));
+        place_new_window(
+            &mut self.space,
+            self.pointer.current_location(),
+            &window,
+            true,
+        );
+        self.focus_window(&window);
+
+        compositor::add_post_commit_hook(surface.wl_surface(), |state: &mut Self, _, surface| {
+            handle_toplevel_commit(&mut state.space, surface);
+        });
+    }
+
+    fn new_popup(&mut self, surface: PopupSurface, _positioner: PositionerState) {
+        // Do not send a configure here, the initial configure
+        // of a xdg_surface has to be sent during the commit if
+        // the surface is not already configured
+
+        self.unconstrain_popup(&surface);
+
+        if let Err(err) = self.popups.track_popup(PopupKind::from(surface)) {
+            warn!("Failed to track popup: {}", err);
+        }
+    }
+
+    fn reposition_request(
+        &mut self,
+        surface: PopupSurface,
+        positioner: PositionerState,
+        token: u32,
+    ) {
+        surface.with_pending_state(|state| {
+            let geometry = positioner.get_geometry();
+            state.geometry = geometry;
+            state.positioner = positioner;
+        });
+        self.unconstrain_popup(&surface);
+        surface.send_repositioned(token);
+    }
+
+    fn move_request(&mut self, surface: ToplevelSurface, seat: wl_seat::WlSeat, serial: Serial) {
+        let seat: Seat<CompositronState<BackendData>> = Seat::from_resource(&seat).unwrap();
+        self.move_request_xdg(&surface, &seat, serial)
+    }
+
+    fn resize_request(
+        &mut self,
+        surface: ToplevelSurface,
+        seat: wl_seat::WlSeat,
+        serial: Serial,
+        edges: xdg_toplevel::ResizeEdge,
+    ) {
+        let seat: Seat<CompositronState<BackendData>> = Seat::from_resource(&seat).unwrap();
+
+        if let Some(touch) = seat.get_touch() {
+            if touch.has_grab(serial) {
+                let start_data = touch.grab_start_data().unwrap();
+                tracing::info!(?start_data);
+
+                // If the client disconnects after requesting a move
+                // we can just ignore the request
+                let Some(window) = self.window_for_surface(surface.wl_surface()) else {
+                    tracing::info!("no window");
+                    return;
+                };
+
+                // If the focus was for a different surface, ignore the request.
+                if start_data.focus.is_none()
+                    || !start_data
+                        .focus
+                        .as_ref()
+                        .unwrap()
+                        .0
+                        .same_client_as(&surface.wl_surface().id())
+                {
+                    tracing::info!("different surface");
+                    return;
+                }
+                let geometry = window.geometry();
+                let loc = self.space.element_location(&window).unwrap();
+                let (initial_window_location, initial_window_size) = (loc, geometry.size);
+
+                with_states(surface.wl_surface(), move |states| {
+                    states
+                        .data_map
+                        .get::<RefCell<SurfaceData>>()
+                        .unwrap()
+                        .borrow_mut()
+                        .resize_state = ResizeState::Resizing(ResizeData {
+                        edges: edges.into(),
+                        initial_window_location,
+                        initial_window_size,
+                    });
+                });
+
+                let grab = TouchResizeSurfaceGrab {
+                    start_data,
+                    window,
+                    edges: edges.into(),
+                    initial_window_location,
+                    initial_window_size,
+                    last_window_size: initial_window_size,
+                };
+
+                touch.set_grab(self, grab, serial);
+                return;
+            }
+        }
+
+        let pointer = seat.get_pointer().unwrap();
+
+        // Check that this surface has a click grab.
+        if !pointer.has_grab(serial) {
+            return;
+        }
+
+        let start_data = pointer.grab_start_data().unwrap();
+
+        let window = self.window_for_surface(surface.wl_surface()).unwrap();
+
+        // If the focus was for a different surface, ignore the request.
+        if start_data.focus.is_none()
+            || !start_data
+                .focus
+                .as_ref()
+                .unwrap()
+                .0
+                .same_client_as(&surface.wl_surface().id())
+        {
+            return;
+        }
+
+        let geometry = window.geometry();
+        let loc = self.space.element_location(&window).unwrap();
+        let (initial_window_location, initial_window_size) = (loc, geometry.size);
+
+        with_states(surface.wl_surface(), move |states| {
+            states
+                .data_map
+                .get::<RefCell<SurfaceData>>()
+                .unwrap()
+                .borrow_mut()
+                .resize_state = ResizeState::Resizing(ResizeData {
+                edges: edges.into(),
+                initial_window_location,
+                initial_window_size,
+            });
+        });
+
+        let grab = PointerResizeSurfaceGrab {
+            start_data,
+            window,
+            edges: edges.into(),
+            initial_window_location,
+            initial_window_size,
+            last_window_size: initial_window_size,
+        };
+
+        pointer.set_grab(self, grab, serial, Focus::Clear);
+    }
+
+    fn ack_configure(&mut self, surface: WlSurface, configure: Configure) {
+        if let Configure::Toplevel(configure) = configure {
+            if let Some(serial) = with_states(&surface, |states| {
+                if let Some(data) = states.data_map.get::<RefCell<SurfaceData>>() {
+                    if let ResizeState::WaitingForFinalAck(_, serial) = data.borrow().resize_state {
+                        return Some(serial);
+                    }
+                }
+
+                None
+            }) {
+                // When the resize grab is released the surface
+                // resize state will be set to WaitingForFinalAck
+                // and the client will receive a configure request
+                // without the resize state to inform the client
+                // resizing has finished. Here we will wait for
+                // the client to acknowledge the end of the
+                // resizing. To check if the surface was resizing
+                // before sending the configure we need to use
+                // the current state as the received acknowledge
+                // will no longer have the resize state set
+                let is_resizing = with_states(&surface, |states| {
+                    states
+                        .data_map
+                        .get::<XdgToplevelSurfaceData>()
+                        .unwrap()
+                        .lock()
+                        .unwrap()
+                        .current
+                        .states
+                        .contains(xdg_toplevel::State::Resizing)
+                });
+
+                if configure.serial >= serial && is_resizing {
+                    with_states(&surface, |states| {
+                        let mut data = states
+                            .data_map
+                            .get::<RefCell<SurfaceData>>()
+                            .unwrap()
+                            .borrow_mut();
+                        if let ResizeState::WaitingForFinalAck(resize_data, _) = data.resize_state {
+                            data.resize_state = ResizeState::WaitingForCommit(resize_data);
+                        } else {
+                            unreachable!()
+                        }
+                    });
+                }
+            }
+
+            let window = self
+                .space
+                .elements()
+                .find(|element| element.wl_surface().as_deref() == Some(&surface));
+            if let Some(window) = window {
+                use xdg_decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode;
+                let is_ssd = configure
+                    .state
+                    .decoration_mode
+                    .map(|mode| mode == Mode::ServerSide)
+                    .unwrap_or(false);
+                window.set_ssd(is_ssd);
+            }
+        }
+    }
+
+    fn fullscreen_request(
+        &mut self,
+        surface: ToplevelSurface,
+        mut wl_output: Option<wl_output::WlOutput>,
+    ) {
+        if surface
+            .current_state()
+            .capabilities
+            .contains(xdg_toplevel::WmCapabilities::Fullscreen)
+        {
+            // NOTE: This is only one part of the solution. We can set the
+            // location and configure size here, but the surface should be rendered fullscreen
+            // independently from its buffer size
+            let wl_surface = surface.wl_surface();
+
+            let output_geometry =
+                fullscreen_output_geometry(wl_surface, wl_output.as_ref(), &mut self.space);
+
+            if let Some(geometry) = output_geometry {
+                let output = wl_output
+                    .as_ref()
+                    .and_then(Output::from_resource)
+                    .unwrap_or_else(|| self.space.outputs().next().unwrap().clone());
+                let client = match self.display_handle.get_client(wl_surface.id()) {
+                    Ok(client) => client,
+                    Err(_) => return,
+                };
+                for output in output.client_outputs(&client) {
+                    wl_output = Some(output);
+                }
+                let window = self
+                    .space
+                    .elements()
+                    .find(|window| {
+                        window
+                            .wl_surface()
+                            .map(|s| &*s == wl_surface)
+                            .unwrap_or(false)
+                    })
+                    .unwrap();
+
+                surface.with_pending_state(|state| {
+                    state.states.set(xdg_toplevel::State::Fullscreen);
+                    state.size = Some(geometry.size);
+                    state.fullscreen_output = wl_output;
+                });
+                output
+                    .user_data()
+                    .insert_if_missing(FullscreenSurface::default);
+                output
+                    .user_data()
+                    .get::<FullscreenSurface>()
+                    .unwrap()
+                    .set(window.clone());
+                trace!("Fullscreening: {:?}", window);
+            }
+        }
+
+        // The protocol demands us to always reply with a configure,
+        // regardless of we fulfilled the request or not
+        if surface.is_initial_configure_sent() {
+            surface.send_configure();
+        } else {
+            // Will be sent during initial configure
+        }
+    }
+
+    fn unfullscreen_request(&mut self, surface: ToplevelSurface) {
+        if !surface
+            .current_state()
+            .states
+            .contains(xdg_toplevel::State::Fullscreen)
+        {
+            return;
+        }
+
+        let ret = surface.with_pending_state(|state| {
+            state.states.unset(xdg_toplevel::State::Fullscreen);
+            state.size = None;
+            state.fullscreen_output.take()
+        });
+        if let Some(output) = ret {
+            let output = Output::from_resource(&output).unwrap();
+            if let Some(fullscreen) = output.user_data().get::<FullscreenSurface>() {
+                trace!("Unfullscreening: {:?}", fullscreen.get());
+                fullscreen.clear();
+                self.backend_data.reset_buffers(&output);
+            }
+        }
+
+        surface.send_pending_configure();
+    }
+
+    fn maximize_request(&mut self, surface: ToplevelSurface) {
+        // NOTE: This should use layer-shell when it is implemented to
+        // get the correct maximum size
+        if surface
+            .current_state()
+            .capabilities
+            .contains(xdg_toplevel::WmCapabilities::Maximize)
+        {
+            let window = self.window_for_surface(surface.wl_surface()).unwrap();
+            let outputs_for_window = self.space.outputs_for_element(&window);
+            let output = outputs_for_window
+                .first()
+                // The window hasn't been mapped yet, use the primary output instead
+                .or_else(|| self.space.outputs().next())
+                // Assumes that at least one output exists
+                .expect("No outputs found");
+            let geometry = self.space.output_geometry(output).unwrap();
+
+            surface.with_pending_state(|state| {
+                state.states.set(xdg_toplevel::State::Maximized);
+                state.size = Some(geometry.size);
+            });
+            self.space.map_element(window, geometry.loc, true);
+        }
+
+        // The protocol demands us to always reply with a configure,
+        // regardless of we fulfilled the request or not
+        if surface.is_initial_configure_sent() {
+            surface.send_configure();
+        } else {
+            // Will be sent during initial configure
+        }
+    }
+
+    fn unmaximize_request(&mut self, surface: ToplevelSurface) {
+        if !surface
+            .current_state()
+            .states
+            .contains(xdg_toplevel::State::Maximized)
+        {
+            return;
+        }
+
+        surface.with_pending_state(|state| {
+            state.states.unset(xdg_toplevel::State::Maximized);
+            state.size = None;
+        });
+        surface.send_pending_configure();
+    }
+
+    fn grab(&mut self, surface: PopupSurface, seat: wl_seat::WlSeat, serial: Serial) {
+        let seat: Seat<CompositronState<BackendData>> = Seat::from_resource(&seat).unwrap();
+        let kind = PopupKind::Xdg(surface);
+        if let Some(root) = find_popup_root_surface(&kind).ok().and_then(|root| {
+            self.space
+                .elements()
+                .find(|w| w.wl_surface().map(|s| *s == root).unwrap_or(false))
+                .cloned()
+                .map(KeyboardFocusTarget::from)
+                .or_else(|| {
+                    self.space
+                        .outputs()
+                        .find_map(|o| {
+                            let map = layer_map_for_output(o);
+                            map.layer_for_surface(&root, WindowSurfaceType::TOPLEVEL)
+                                .cloned()
+                        })
+                        .map(KeyboardFocusTarget::LayerSurface)
+                })
+        }) {
+            let ret = self.popups.grab_popup(root, kind, &seat, serial);
+
+            if let Ok(mut grab) = ret {
+                if let Some(keyboard) = seat.get_keyboard() {
+                    if keyboard.is_grabbed()
+                        && !(keyboard.has_grab(serial)
+                            || keyboard.has_grab(grab.previous_serial().unwrap_or(serial)))
+                    {
+                        grab.ungrab(PopupUngrabStrategy::All);
+                        return;
+                    }
+                    keyboard.set_focus(self, grab.current_grab(), serial);
+                    keyboard.set_grab(self, PopupKeyboardGrab::new(&grab), serial);
+                }
+                if let Some(pointer) = seat.get_pointer() {
+                    if pointer.is_grabbed()
+                        && !(pointer.has_grab(serial)
+                            || pointer
+                                .has_grab(grab.previous_serial().unwrap_or_else(|| grab.serial())))
+                    {
+                        grab.ungrab(PopupUngrabStrategy::All);
+                        return;
+                    }
+                    pointer.set_grab(self, PopupPointerGrab::new(&grab), serial, Focus::Keep);
+                }
+            }
+        }
+    }
+}
+
+impl<BackendData: Backend> CompositronState<BackendData> {
+    pub fn move_request_xdg(
+        &mut self,
+        surface: &ToplevelSurface,
+        seat: &Seat<Self>,
+        serial: Serial,
+    ) {
+        if let Some(touch) = seat.get_touch() {
+            if touch.has_grab(serial) {
+                let start_data = touch.grab_start_data().unwrap();
+
+                // If the client disconnects after requesting a move
+                // we can just ignore the request
+                let Some(window) = self.window_for_surface(surface.wl_surface()) else {
+                    return;
+                };
+
+                // If the focus was for a different surface, ignore the request.
+                if start_data.focus.is_none()
+                    || !start_data
+                        .focus
+                        .as_ref()
+                        .unwrap()
+                        .0
+                        .same_client_as(&surface.wl_surface().id())
+                {
+                    return;
+                }
+
+                let mut initial_window_location = self.space.element_location(&window).unwrap();
+
+                // If surface is maximized then unmaximize it
+                let current_state = surface.current_state();
+                if current_state
+                    .states
+                    .contains(xdg_toplevel::State::Maximized)
+                {
+                    surface.with_pending_state(|state| {
+                        state.states.unset(xdg_toplevel::State::Maximized);
+                        state.size = None;
+                    });
+
+                    surface.send_configure();
+
+                    // NOTE: In real compositor mouse location should be mapped to a new window size
+                    // For example, you could:
+                    // 1) transform mouse pointer position from compositor space to window space (location relative)
+                    // 2) divide the x coordinate by width of the window to get the percentage
+                    //   - 0.0 would be on the far left of the window
+                    //   - 0.5 would be in middle of the window
+                    //   - 1.0 would be on the far right of the window
+                    // 3) multiply the percentage by new window width
+                    // 4) by doing that, drag will look a lot more natural
+                    //
+                    // but for Compositron needs setting location to pointer location is fine
+                    initial_window_location = start_data.location.to_i32_round();
+                }
+
+                let grab = TouchMoveSurfaceGrab {
+                    start_data,
+                    window,
+                    initial_window_location,
+                };
+
+                touch.set_grab(self, grab, serial);
+                return;
+            }
+        }
+
+        let pointer = seat.get_pointer().unwrap();
+
+        // Check that this surface has a click grab.
+        if !pointer.has_grab(serial) {
+            return;
+        }
+
+        let start_data = pointer.grab_start_data().unwrap();
+
+        // If the client disconnects after requesting a move
+        // we can just ignore the request
+        let Some(window) = self.window_for_surface(surface.wl_surface()) else {
+            return;
+        };
+
+        // If the focus was for a different surface, ignore the request.
+        if start_data.focus.is_none()
+            || !start_data
+                .focus
+                .as_ref()
+                .unwrap()
+                .0
+                .same_client_as(&surface.wl_surface().id())
+        {
+            return;
+        }
+
+        let mut initial_window_location = self.space.element_location(&window).unwrap();
+
+        // If surface is maximized then unmaximize it
+        let current_state = surface.current_state();
+        if current_state
+            .states
+            .contains(xdg_toplevel::State::Maximized)
+        {
+            surface.with_pending_state(|state| {
+                state.states.unset(xdg_toplevel::State::Maximized);
+                state.size = None;
+            });
+
+            surface.send_configure();
+
+            // NOTE: In real compositor mouse location should be mapped to a new window size
+            // For example, you could:
+            // 1) transform mouse pointer position from compositor space to window space (location relative)
+            // 2) divide the x coordinate by width of the window to get the percentage
+            //   - 0.0 would be on the far left of the window
+            //   - 0.5 would be in middle of the window
+            //   - 1.0 would be on the far right of the window
+            // 3) multiply the percentage by new window width
+            // 4) by doing that, drag will look a lot more natural
+            //
+            // but for Compositron needs setting location to pointer location is fine
+            let pos = pointer.current_location();
+            initial_window_location = (pos.x as i32, pos.y as i32).into();
+        }
+
+        let grab = PointerMoveSurfaceGrab {
+            start_data,
+            window,
+            initial_window_location,
+        };
+
+        pointer.set_grab(self, grab, serial, Focus::Clear);
+    }
+
+    fn unconstrain_popup(&self, popup: &PopupSurface) {
+        let Ok(root) = find_popup_root_surface(&PopupKind::Xdg(popup.clone())) else {
+            return;
+        };
+        let Some(window) = self.window_for_surface(&root) else {
+            return;
+        };
+
+        let mut outputs_for_window = self.space.outputs_for_element(&window);
+        if outputs_for_window.is_empty() {
+            return;
+        }
+
+        // Get a union of all outputs' geometries.
+        let mut outputs_geo = self
+            .space
+            .output_geometry(&outputs_for_window.pop().unwrap())
+            .unwrap();
+        for output in outputs_for_window {
+            outputs_geo = outputs_geo.merge(self.space.output_geometry(&output).unwrap());
+        }
+
+        let window_geo = self.space.element_geometry(&window).unwrap();
+
+        // The target geometry for the positioner should be relative to its parent's geometry, so
+        // we will compute that here.
+        let mut target = outputs_geo;
+        target.loc -= get_popup_toplevel_coords(&PopupKind::Xdg(popup.clone()));
+        target.loc -= window_geo.loc;
+
+        popup.with_pending_state(|state| {
+            state.geometry = state.positioner.get_unconstrained_geometry(target);
+        });
+    }
+}
+
+/// Should be called on `WlSurface::commit` of xdg toplevel
+fn handle_toplevel_commit(space: &mut Space<WindowElement>, surface: &WlSurface) -> Option<()> {
+    let window = space
+        .elements()
+        .find(|w| w.wl_surface().as_deref() == Some(surface))
+        .cloned()?;
+
+    let mut window_loc = space.element_location(&window)?;
+    let geometry = window.geometry();
+
+    let new_loc: Point<Option<i32>, Logical> =
+        with_states(window.wl_surface().as_deref()?, |states| {
+            let data = states.data_map.get::<RefCell<SurfaceData>>()?.borrow_mut();
+
+            if let ResizeState::Resizing(resize_data) = data.resize_state {
+                let edges = resize_data.edges;
+                let loc = resize_data.initial_window_location;
+                let size = resize_data.initial_window_size;
+
+                // If the window is being resized by top or left, its location must be adjusted
+                // accordingly.
+                edges.intersects(ResizeEdge::TOP_LEFT).then(|| {
+                    let new_x = edges
+                        .intersects(ResizeEdge::LEFT)
+                        .then_some(loc.x + (size.w - geometry.size.w));
+
+                    let new_y = edges
+                        .intersects(ResizeEdge::TOP)
+                        .then_some(loc.y + (size.h - geometry.size.h));
+
+                    (new_x, new_y).into()
+                })
+            } else {
+                None
+            }
+        })?;
+
+    if let Some(new_x) = new_loc.x {
+        window_loc.x = new_x;
+    }
+    if let Some(new_y) = new_loc.y {
+        window_loc.y = new_y;
+    }
+
+    if new_loc.x.is_some() || new_loc.y.is_some() {
+        // If TOP or LEFT side of the window got resized, we have to move it
+        space.map_element(window, window_loc, false);
+    }
+
+    Some(())
+}

+ 1583 - 0
src/state.rs

@@ -0,0 +1,1583 @@
+use std::{
+    collections::HashMap,
+    os::unix::io::OwnedFd,
+    sync::{atomic::AtomicBool, Arc},
+    time::Duration,
+};
+use tracing::{info, warn};
+
+use smithay::{
+    backend::{
+        input::TabletToolDescriptor,
+        renderer::element::{
+            default_primary_scanout_output_compare, utils::select_dmabuf_feedback,
+            RenderElementStates,
+        },
+    },
+    delegate_compositor, delegate_data_control, delegate_data_device, delegate_fractional_scale,
+    delegate_input_method_manager, delegate_keyboard_shortcuts_inhibit, delegate_layer_shell,
+    delegate_output, delegate_pointer_constraints, delegate_pointer_gestures,
+    delegate_presentation, delegate_primary_selection, delegate_relative_pointer, delegate_seat,
+    delegate_security_context, delegate_shm, delegate_tablet_manager, delegate_text_input_manager,
+    delegate_viewporter, delegate_virtual_keyboard_manager, delegate_xdg_activation,
+    delegate_xdg_decoration, delegate_xdg_shell,
+    desktop::{
+        space::SpaceElement,
+        utils::{
+            surface_presentation_feedback_flags_from_states, surface_primary_scanout_output,
+            update_surface_primary_scanout_output, with_surfaces_surface_tree,
+            OutputPresentationFeedback,
+        },
+        PopupKind, PopupManager, Space,
+    },
+    input::{
+        keyboard::{Keysym, LedState, XkbConfig},
+        pointer::{CursorImageStatus, CursorImageSurfaceData, PointerHandle},
+        Seat, SeatHandler, SeatState,
+    },
+    output::Output,
+    reexports::{
+        calloop::{
+            generic::Generic,
+            timer::{TimeoutAction, Timer},
+            Interest, LoopHandle, Mode, PostAction, RegistrationToken,
+        },
+        wayland_protocols::xdg::decoration::{
+            self as xdg_decoration,
+            zv1::server::zxdg_toplevel_decoration_v1::Mode as DecorationMode,
+        },
+        wayland_server::{
+            backend::{ClientData, ClientId, DisconnectReason},
+            protocol::{wl_data_source::WlDataSource, wl_surface::WlSurface},
+            Client, Display, DisplayHandle, Resource,
+        },
+    },
+    utils::{Clock, IsAlive, Logical, Monotonic, Point, Rectangle, Time},
+    wayland::{
+        commit_timing::{CommitTimerBarrierStateUserData, CommitTimingManagerState},
+        compositor::{
+            get_parent, with_states, CompositorClientState, CompositorHandler, CompositorState,
+        },
+        dmabuf::DmabufFeedback,
+        fifo::{FifoBarrierCachedState, FifoManagerState},
+        fractional_scale::{
+            with_fractional_scale, FractionalScaleHandler, FractionalScaleManagerState,
+        },
+        input_method::{InputMethodHandler, InputMethodManagerState, PopupSurface},
+        keyboard_shortcuts_inhibit::{
+            KeyboardShortcutsInhibitHandler, KeyboardShortcutsInhibitState,
+            KeyboardShortcutsInhibitor,
+        },
+        output::{OutputHandler, OutputManagerState},
+        pointer_constraints::{
+            with_pointer_constraint, PointerConstraintsHandler, PointerConstraintsState,
+        },
+        pointer_gestures::PointerGesturesState,
+        presentation::PresentationState,
+        relative_pointer::RelativePointerManagerState,
+        seat::WaylandFocus,
+        security_context::{
+            SecurityContext, SecurityContextHandler, SecurityContextListenerSource,
+            SecurityContextState,
+        },
+        selection::{
+            data_device::{
+                set_data_device_focus, ClientDndGrabHandler, DataDeviceHandler, DataDeviceState,
+                ServerDndGrabHandler,
+            },
+            primary_selection::{
+                set_primary_focus, PrimarySelectionHandler, PrimarySelectionState,
+            },
+            wlr_data_control::{DataControlHandler, DataControlState},
+            SelectionHandler,
+        },
+        shell::{
+            wlr_layer::WlrLayerShellState,
+            xdg::{
+                decoration::{XdgDecorationHandler, XdgDecorationState},
+                ToplevelSurface, XdgShellHandler, XdgShellState,
+            },
+        },
+        shm::{ShmHandler, ShmState},
+        single_pixel_buffer::SinglePixelBufferState,
+        socket::ListeningSocketSource,
+        tablet_manager::{TabletManagerState, TabletSeatHandler},
+        text_input::TextInputManagerState,
+        viewporter::ViewporterState,
+        virtual_keyboard::VirtualKeyboardManagerState,
+        xdg_activation::{
+            XdgActivationHandler, XdgActivationState, XdgActivationToken, XdgActivationTokenData,
+        },
+        xdg_foreign::{XdgForeignHandler, XdgForeignState},
+    },
+};
+
+#[cfg(feature = "xwayland")]
+use crate::cursor::Cursor;
+use crate::{
+    config::Config,
+    focus::{KeyboardFocusTarget, PointerFocusTarget},
+    overview::{Overview, OverviewAction},
+    shell::WindowElement,
+    workspaces::Workspaces,
+};
+#[cfg(feature = "xwayland")]
+use smithay::{
+    delegate_xwayland_keyboard_grab, delegate_xwayland_shell,
+    utils::Size,
+    wayland::selection::{SelectionSource, SelectionTarget},
+    wayland::xwayland_keyboard_grab::{XWaylandKeyboardGrabHandler, XWaylandKeyboardGrabState},
+    wayland::xwayland_shell,
+    xwayland::{X11Wm, XWayland, XWaylandEvent},
+};
+
+#[derive(Debug, Default)]
+pub struct ClientState {
+    pub compositor_state: CompositorClientState,
+    pub security_context: Option<SecurityContext>,
+}
+impl ClientData for ClientState {
+    /// Notification that a client was initialized
+    fn initialized(&self, _client_id: ClientId) {}
+    /// Notification that a client is disconnected
+    fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
+}
+
+#[derive(Debug)]
+pub struct CompositronState<BackendData: Backend + 'static> {
+    pub backend_data: BackendData,
+    pub socket_name: Option<String>,
+    pub display_handle: DisplayHandle,
+    pub running: Arc<AtomicBool>,
+    pub handle: LoopHandle<'static, CompositronState<BackendData>>,
+
+    // desktop
+    pub space: Workspaces,
+    pub popups: PopupManager,
+
+    // smithay state
+    pub compositor_state: CompositorState,
+    pub data_device_state: DataDeviceState,
+    pub layer_shell_state: WlrLayerShellState,
+    pub output_manager_state: OutputManagerState,
+    pub primary_selection_state: PrimarySelectionState,
+    pub data_control_state: DataControlState,
+    pub seat_state: SeatState<CompositronState<BackendData>>,
+    pub keyboard_shortcuts_inhibit_state: KeyboardShortcutsInhibitState,
+    pub shm_state: ShmState,
+    pub viewporter_state: ViewporterState,
+    pub xdg_activation_state: XdgActivationState,
+    pub xdg_decoration_state: XdgDecorationState,
+    pub xdg_shell_state: XdgShellState,
+    pub presentation_state: PresentationState,
+    pub fractional_scale_manager_state: FractionalScaleManagerState,
+    pub xdg_foreign_state: XdgForeignState,
+    #[cfg(feature = "xwayland")]
+    pub xwayland_shell_state: xwayland_shell::XWaylandShellState,
+    pub single_pixel_buffer_state: SinglePixelBufferState,
+    pub fifo_manager_state: FifoManagerState,
+    pub commit_timing_manager_state: CommitTimingManagerState,
+
+    pub dnd_icon: Option<DndIcon>,
+
+    // input-related fields
+    pub suppressed_keys: Vec<Keysym>,
+    pub cursor_status: CursorImageStatus,
+    pub seat_name: String,
+    pub seat: Seat<CompositronState<BackendData>>,
+    pub clock: Clock<Monotonic>,
+    pub pointer: PointerHandle<CompositronState<BackendData>>,
+    pub overview: Overview,
+    pub config: Config,
+    pub super_tap_armed: bool,
+    pub super_tap_used: bool,
+    repeat_token: Option<RegistrationToken>,
+    repeat_action: Option<crate::overview::RepeatAction>,
+    repeat_keysym: Option<Keysym>,
+
+    #[cfg(feature = "xwayland")]
+    pub xwm: Option<X11Wm>,
+    #[cfg(feature = "xwayland")]
+    pub xdisplay: Option<u32>,
+
+    #[cfg(feature = "debug")]
+    pub renderdoc: Option<renderdoc::RenderDoc<renderdoc::V141>>,
+
+    pub show_window_preview: bool,
+}
+
+#[derive(Debug)]
+pub struct DndIcon {
+    pub surface: WlSurface,
+    pub offset: Point<i32, Logical>,
+}
+
+delegate_compositor!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> DataDeviceHandler for CompositronState<BackendData> {
+    fn data_device_state(&self) -> &DataDeviceState {
+        &self.data_device_state
+    }
+}
+
+impl<BackendData: Backend> ClientDndGrabHandler for CompositronState<BackendData> {
+    fn started(
+        &mut self,
+        _source: Option<WlDataSource>,
+        icon: Option<WlSurface>,
+        _seat: Seat<Self>,
+    ) {
+        let offset = if let CursorImageStatus::Surface(ref surface) = self.cursor_status {
+            with_states(surface, |states| {
+                let hotspot = states
+                    .data_map
+                    .get::<CursorImageSurfaceData>()
+                    .unwrap()
+                    .lock()
+                    .unwrap()
+                    .hotspot;
+                Point::from((-hotspot.x, -hotspot.y))
+            })
+        } else {
+            (0, 0).into()
+        };
+        self.dnd_icon = icon.map(|surface| DndIcon { surface, offset });
+    }
+    fn dropped(&mut self, _target: Option<WlSurface>, _validated: bool, _seat: Seat<Self>) {
+        self.dnd_icon = None;
+    }
+}
+impl<BackendData: Backend> ServerDndGrabHandler for CompositronState<BackendData> {
+    fn send(&mut self, _mime_type: String, _fd: OwnedFd, _seat: Seat<Self>) {
+        unreachable!("Compositron does not do server-side grabs");
+    }
+}
+delegate_data_device!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> OutputHandler for CompositronState<BackendData> {}
+delegate_output!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> SelectionHandler for CompositronState<BackendData> {
+    type SelectionUserData = ();
+
+    #[cfg(feature = "xwayland")]
+    fn new_selection(
+        &mut self,
+        ty: SelectionTarget,
+        source: Option<SelectionSource>,
+        _seat: Seat<Self>,
+    ) {
+        if let Some(xwm) = self.xwm.as_mut() {
+            if let Err(err) = xwm.new_selection(ty, source.map(|source| source.mime_types())) {
+                warn!(?err, ?ty, "Failed to set Xwayland selection");
+            }
+        }
+    }
+
+    #[cfg(feature = "xwayland")]
+    fn send_selection(
+        &mut self,
+        ty: SelectionTarget,
+        mime_type: String,
+        fd: OwnedFd,
+        _seat: Seat<Self>,
+        _user_data: &(),
+    ) {
+        if let Some(xwm) = self.xwm.as_mut() {
+            if let Err(err) = xwm.send_selection(ty, mime_type, fd, self.handle.clone()) {
+                warn!(?err, "Failed to send primary (X11 -> Wayland)");
+            }
+        }
+    }
+}
+
+impl<BackendData: Backend> PrimarySelectionHandler for CompositronState<BackendData> {
+    fn primary_selection_state(&self) -> &PrimarySelectionState {
+        &self.primary_selection_state
+    }
+}
+delegate_primary_selection!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> DataControlHandler for CompositronState<BackendData> {
+    fn data_control_state(&self) -> &DataControlState {
+        &self.data_control_state
+    }
+}
+
+delegate_data_control!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> ShmHandler for CompositronState<BackendData> {
+    fn shm_state(&self) -> &ShmState {
+        &self.shm_state
+    }
+}
+delegate_shm!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> SeatHandler for CompositronState<BackendData> {
+    type KeyboardFocus = KeyboardFocusTarget;
+    type PointerFocus = PointerFocusTarget;
+    type TouchFocus = PointerFocusTarget;
+
+    fn seat_state(&mut self) -> &mut SeatState<CompositronState<BackendData>> {
+        &mut self.seat_state
+    }
+
+    fn focus_changed(&mut self, seat: &Seat<Self>, target: Option<&KeyboardFocusTarget>) {
+        if let Some(KeyboardFocusTarget::Window(window)) = target {
+            self.space.note_focus(Some(WindowElement(window.clone())));
+        }
+
+        let dh = &self.display_handle;
+
+        let wl_surface = target.and_then(WaylandFocus::wl_surface);
+
+        let focus = wl_surface.and_then(|s| dh.get_client(s.id()).ok());
+        set_data_device_focus(dh, seat, focus.clone());
+        set_primary_focus(dh, seat, focus);
+    }
+    fn cursor_image(&mut self, _seat: &Seat<Self>, image: CursorImageStatus) {
+        self.cursor_status = image;
+    }
+
+    fn led_state_changed(&mut self, _seat: &Seat<Self>, led_state: LedState) {
+        self.backend_data.update_led_state(led_state)
+    }
+}
+delegate_seat!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> TabletSeatHandler for CompositronState<BackendData> {
+    fn tablet_tool_image(&mut self, _tool: &TabletToolDescriptor, image: CursorImageStatus) {
+        // TODO: tablet tools should have their own cursors
+        self.cursor_status = image;
+    }
+}
+delegate_tablet_manager!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+delegate_text_input_manager!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> InputMethodHandler for CompositronState<BackendData> {
+    fn new_popup(&mut self, surface: PopupSurface) {
+        if let Err(err) = self.popups.track_popup(PopupKind::from(surface)) {
+            warn!("Failed to track popup: {}", err);
+        }
+    }
+
+    fn popup_repositioned(&mut self, _: PopupSurface) {}
+
+    fn dismiss_popup(&mut self, surface: PopupSurface) {
+        if let Some(parent) = surface.get_parent().map(|parent| parent.surface.clone()) {
+            let _ = PopupManager::dismiss_popup(&parent, &PopupKind::from(surface));
+        }
+    }
+
+    fn parent_geometry(&self, parent: &WlSurface) -> Rectangle<i32, smithay::utils::Logical> {
+        self.space
+            .elements()
+            .find_map(|window| {
+                (window.wl_surface().as_deref() == Some(parent)).then(|| window.geometry())
+            })
+            .unwrap_or_default()
+    }
+}
+
+delegate_input_method_manager!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> KeyboardShortcutsInhibitHandler for CompositronState<BackendData> {
+    fn keyboard_shortcuts_inhibit_state(&mut self) -> &mut KeyboardShortcutsInhibitState {
+        &mut self.keyboard_shortcuts_inhibit_state
+    }
+
+    fn new_inhibitor(&mut self, inhibitor: KeyboardShortcutsInhibitor) {
+        // Just grant the wish for everyone
+        inhibitor.activate();
+    }
+}
+
+delegate_keyboard_shortcuts_inhibit!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+delegate_virtual_keyboard_manager!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+delegate_pointer_gestures!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+delegate_relative_pointer!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> PointerConstraintsHandler for CompositronState<BackendData> {
+    fn new_constraint(&mut self, surface: &WlSurface, pointer: &PointerHandle<Self>) {
+        // XXX region
+        let Some(current_focus) = pointer.current_focus() else {
+            return;
+        };
+        if current_focus.wl_surface().as_deref() == Some(surface) {
+            with_pointer_constraint(surface, pointer, |constraint| {
+                constraint.unwrap().activate();
+            });
+        }
+    }
+
+    fn cursor_position_hint(
+        &mut self,
+        surface: &WlSurface,
+        pointer: &PointerHandle<Self>,
+        location: Point<f64, Logical>,
+    ) {
+        if with_pointer_constraint(surface, pointer, |constraint| {
+            constraint.is_some_and(|c| c.is_active())
+        }) {
+            let origin = self
+                .space
+                .elements()
+                .find_map(|window| {
+                    (window.wl_surface().as_deref() == Some(surface)).then(|| window.geometry())
+                })
+                .unwrap_or_default()
+                .loc
+                .to_f64();
+
+            pointer.set_location(origin + location);
+        }
+    }
+}
+delegate_pointer_constraints!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+delegate_viewporter!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> XdgActivationHandler for CompositronState<BackendData> {
+    fn activation_state(&mut self) -> &mut XdgActivationState {
+        &mut self.xdg_activation_state
+    }
+
+    fn token_created(&mut self, _token: XdgActivationToken, data: XdgActivationTokenData) -> bool {
+        if let Some((serial, seat)) = data.serial {
+            let keyboard = self.seat.get_keyboard().unwrap();
+            Seat::from_resource(&seat) == Some(self.seat.clone())
+                && keyboard
+                    .last_enter()
+                    .map(|last_enter| serial.is_no_older_than(&last_enter))
+                    .unwrap_or(false)
+        } else {
+            false
+        }
+    }
+
+    fn request_activation(
+        &mut self,
+        _token: XdgActivationToken,
+        token_data: XdgActivationTokenData,
+        surface: WlSurface,
+    ) {
+        if token_data.timestamp.elapsed().as_secs() < 10 {
+            // Just grant the wish
+            let w = self
+                .space
+                .elements()
+                .find(|window| window.wl_surface().map(|s| *s == surface).unwrap_or(false))
+                .cloned();
+            if let Some(window) = w {
+                self.space.raise_element(&window, true);
+            }
+        }
+    }
+}
+delegate_xdg_activation!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> XdgDecorationHandler for CompositronState<BackendData> {
+    fn new_decoration(&mut self, toplevel: ToplevelSurface) {
+        use xdg_decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode;
+        // Set the default to client side
+        toplevel.with_pending_state(|state| {
+            state.decoration_mode = Some(Mode::ClientSide);
+        });
+    }
+    fn request_mode(&mut self, toplevel: ToplevelSurface, mode: DecorationMode) {
+        use xdg_decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode;
+
+        toplevel.with_pending_state(|state| {
+            state.decoration_mode = Some(match mode {
+                DecorationMode::ServerSide => Mode::ServerSide,
+                _ => Mode::ClientSide,
+            });
+        });
+
+        if toplevel.is_initial_configure_sent() {
+            toplevel.send_pending_configure();
+        }
+    }
+    fn unset_mode(&mut self, toplevel: ToplevelSurface) {
+        use xdg_decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode;
+        toplevel.with_pending_state(|state| {
+            state.decoration_mode = Some(Mode::ClientSide);
+        });
+
+        if toplevel.is_initial_configure_sent() {
+            toplevel.send_pending_configure();
+        }
+    }
+}
+delegate_xdg_decoration!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+delegate_xdg_shell!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+delegate_layer_shell!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+delegate_presentation!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> FractionalScaleHandler for CompositronState<BackendData> {
+    fn new_fractional_scale(
+        &mut self,
+        surface: smithay::reexports::wayland_server::protocol::wl_surface::WlSurface,
+    ) {
+        // Here we can set the initial fractional scale
+        //
+        // First we look if the surface already has a primary scan-out output, if not
+        // we test if the surface is a subsurface and try to use the primary scan-out output
+        // of the root surface. If the root also has no primary scan-out output we just try
+        // to use the first output of the toplevel.
+        // If the surface is the root we also try to use the first output of the toplevel.
+        //
+        // If all the above tests do not lead to a output we just use the first output
+        // of the space (which in case of Compositron will also be the output a toplevel will
+        // initially be placed on)
+        #[allow(clippy::redundant_clone)]
+        let mut root = surface.clone();
+        while let Some(parent) = get_parent(&root) {
+            root = parent;
+        }
+
+        with_states(&surface, |states| {
+            let primary_scanout_output = surface_primary_scanout_output(&surface, states)
+                .or_else(|| {
+                    if root != surface {
+                        with_states(&root, |states| {
+                            surface_primary_scanout_output(&root, states).or_else(|| {
+                                self.window_for_surface(&root).and_then(|window| {
+                                    self.space.outputs_for_element(&window).first().cloned()
+                                })
+                            })
+                        })
+                    } else {
+                        self.window_for_surface(&root).and_then(|window| {
+                            self.space.outputs_for_element(&window).first().cloned()
+                        })
+                    }
+                })
+                .or_else(|| self.space.outputs().next().cloned());
+            if let Some(output) = primary_scanout_output {
+                with_fractional_scale(states, |fractional_scale| {
+                    fractional_scale.set_preferred_scale(output.current_scale().fractional_scale());
+                });
+            }
+        });
+    }
+}
+delegate_fractional_scale!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend + 'static> SecurityContextHandler for CompositronState<BackendData> {
+    fn context_created(
+        &mut self,
+        source: SecurityContextListenerSource,
+        security_context: SecurityContext,
+    ) {
+        self.handle
+            .insert_source(source, move |client_stream, _, data| {
+                let client_state = ClientState {
+                    security_context: Some(security_context.clone()),
+                    ..ClientState::default()
+                };
+                if let Err(err) = data
+                    .display_handle
+                    .insert_client(client_stream, Arc::new(client_state))
+                {
+                    warn!("Error adding wayland client: {}", err);
+                };
+            })
+            .expect("Failed to init wayland socket source");
+    }
+}
+delegate_security_context!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+#[cfg(feature = "xwayland")]
+impl<BackendData: Backend + 'static> XWaylandKeyboardGrabHandler for CompositronState<BackendData> {
+    fn keyboard_focus_for_xsurface(&self, surface: &WlSurface) -> Option<KeyboardFocusTarget> {
+        let elem = self
+            .space
+            .elements()
+            .find(|elem| elem.wl_surface().as_deref() == Some(surface))?;
+        Some(KeyboardFocusTarget::Window(elem.0.clone()))
+    }
+}
+#[cfg(feature = "xwayland")]
+delegate_xwayland_keyboard_grab!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+#[cfg(feature = "xwayland")]
+delegate_xwayland_shell!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend> XdgForeignHandler for CompositronState<BackendData> {
+    fn xdg_foreign_state(&mut self) -> &mut XdgForeignState {
+        &mut self.xdg_foreign_state
+    }
+}
+smithay::delegate_xdg_foreign!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+smithay::delegate_single_pixel_buffer!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+smithay::delegate_fifo!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+smithay::delegate_commit_timing!(@<BackendData: Backend + 'static> CompositronState<BackendData>);
+
+impl<BackendData: Backend + 'static> CompositronState<BackendData> {
+    pub fn init(
+        display: Display<CompositronState<BackendData>>,
+        handle: LoopHandle<'static, CompositronState<BackendData>>,
+        backend_data: BackendData,
+        listen_on_socket: bool,
+    ) -> CompositronState<BackendData> {
+        let dh = display.handle();
+
+        let clock = Clock::new();
+
+        // init wayland clients
+        let socket_name = if listen_on_socket {
+            let source = ListeningSocketSource::new_auto().unwrap();
+            let socket_name = source.socket_name().to_string_lossy().into_owned();
+            handle
+                .insert_source(source, |client_stream, _, data| {
+                    if let Err(err) = data
+                        .display_handle
+                        .insert_client(client_stream, Arc::new(ClientState::default()))
+                    {
+                        warn!("Error adding wayland client: {}", err);
+                    };
+                })
+                .expect("Failed to init wayland socket source");
+            info!(name = socket_name, "Listening on wayland socket");
+            Some(socket_name)
+        } else {
+            None
+        };
+        handle
+            .insert_source(
+                Generic::new(display, Interest::READ, Mode::Level),
+                |_, display, data| {
+                    profiling::scope!("dispatch_clients");
+                    // Safety: we don't drop the display
+                    unsafe {
+                        display.get_mut().dispatch_clients(data).unwrap();
+                    }
+                    Ok(PostAction::Continue)
+                },
+            )
+            .expect("Failed to init wayland server source");
+
+        // init globals
+        let compositor_state = CompositorState::new::<Self>(&dh);
+        let data_device_state = DataDeviceState::new::<Self>(&dh);
+        let layer_shell_state = WlrLayerShellState::new::<Self>(&dh);
+        let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&dh);
+        let primary_selection_state = PrimarySelectionState::new::<Self>(&dh);
+        let data_control_state =
+            DataControlState::new::<Self, _>(&dh, Some(&primary_selection_state), |_| true);
+        let mut seat_state = SeatState::new();
+        let shm_state = ShmState::new::<Self>(&dh, vec![]);
+        let viewporter_state = ViewporterState::new::<Self>(&dh);
+        let xdg_activation_state = XdgActivationState::new::<Self>(&dh);
+        let xdg_decoration_state = XdgDecorationState::new::<Self>(&dh);
+        let xdg_shell_state = XdgShellState::new::<Self>(&dh);
+        let presentation_state = PresentationState::new::<Self>(&dh, clock.id() as u32);
+        let fractional_scale_manager_state = FractionalScaleManagerState::new::<Self>(&dh);
+        let xdg_foreign_state = XdgForeignState::new::<Self>(&dh);
+        let single_pixel_buffer_state = SinglePixelBufferState::new::<Self>(&dh);
+        let fifo_manager_state = FifoManagerState::new::<Self>(&dh);
+        let commit_timing_manager_state = CommitTimingManagerState::new::<Self>(&dh);
+        TextInputManagerState::new::<Self>(&dh);
+        InputMethodManagerState::new::<Self, _>(&dh, |_client| true);
+        VirtualKeyboardManagerState::new::<Self, _>(&dh, |_client| true);
+        // Expose global only if backend supports relative motion events
+        if BackendData::HAS_RELATIVE_MOTION {
+            RelativePointerManagerState::new::<Self>(&dh);
+        }
+        PointerConstraintsState::new::<Self>(&dh);
+        if BackendData::HAS_GESTURES {
+            PointerGesturesState::new::<Self>(&dh);
+        }
+        TabletManagerState::new::<Self>(&dh);
+        SecurityContextState::new::<Self, _>(&dh, |client| {
+            client
+                .get_data::<ClientState>()
+                .is_none_or(|client_state| client_state.security_context.is_none())
+        });
+
+        // init input
+        let seat_name = backend_data.seat_name();
+        let mut seat = seat_state.new_wl_seat(&dh, seat_name.clone());
+
+        let pointer = seat.add_pointer();
+        seat.add_keyboard(XkbConfig::default(), 200, 25)
+            .expect("Failed to initialize the keyboard");
+
+        let config = Config::load();
+        let overview = Overview::new(&config);
+
+        let keyboard_shortcuts_inhibit_state = KeyboardShortcutsInhibitState::new::<Self>(&dh);
+
+        #[cfg(feature = "xwayland")]
+        let xwayland_shell_state = xwayland_shell::XWaylandShellState::new::<Self>(&dh.clone());
+
+        #[cfg(feature = "xwayland")]
+        XWaylandKeyboardGrabState::new::<Self>(&dh.clone());
+
+        CompositronState {
+            backend_data,
+            display_handle: dh,
+            socket_name,
+            running: Arc::new(AtomicBool::new(true)),
+            handle,
+            space: Workspaces::new(),
+            popups: PopupManager::default(),
+            compositor_state,
+            data_device_state,
+            layer_shell_state,
+            output_manager_state,
+            primary_selection_state,
+            data_control_state,
+            seat_state,
+            keyboard_shortcuts_inhibit_state,
+            shm_state,
+            viewporter_state,
+            xdg_activation_state,
+            xdg_decoration_state,
+            xdg_shell_state,
+            presentation_state,
+            fractional_scale_manager_state,
+            xdg_foreign_state,
+            single_pixel_buffer_state,
+            fifo_manager_state,
+            commit_timing_manager_state,
+            dnd_icon: None,
+            suppressed_keys: Vec::new(),
+            cursor_status: CursorImageStatus::default_named(),
+            seat_name,
+            seat,
+            pointer,
+            clock,
+            overview,
+            config,
+            super_tap_armed: false,
+            super_tap_used: false,
+            repeat_token: None,
+            repeat_action: None,
+            repeat_keysym: None,
+
+            #[cfg(feature = "xwayland")]
+            xwayland_shell_state,
+            #[cfg(feature = "xwayland")]
+            xwm: None,
+            #[cfg(feature = "xwayland")]
+            xdisplay: None,
+            #[cfg(feature = "debug")]
+            renderdoc: renderdoc::RenderDoc::new().ok(),
+            show_window_preview: false,
+        }
+    }
+
+    pub fn output_for_pointer(&self) -> Option<Output> {
+        self.space
+            .output_under(self.pointer.current_location())
+            .next()
+            .cloned()
+            .or_else(|| self.space.outputs().next().cloned())
+    }
+
+    pub fn focused_window(&self) -> Option<WindowElement> {
+        let keyboard = self.seat.get_keyboard()?;
+        let focus = keyboard.current_focus()?;
+        let surface = focus.wl_surface()?;
+        self.space
+            .elements()
+            .find(|window| window.wl_surface().as_deref() == Some(&surface))
+            .cloned()
+    }
+
+    fn refresh_pointer_focus(&mut self, serial: smithay::utils::Serial) {
+        let location = self.pointer.current_location();
+        let under = self.surface_under(location);
+        let pointer = self.pointer.clone();
+        pointer.motion(
+            self,
+            under,
+            &smithay::input::pointer::MotionEvent {
+                location,
+                serial,
+                time: self.clock.now().as_millis(),
+            },
+        );
+        pointer.frame(self);
+    }
+
+    fn restore_workspace_focus(&mut self) {
+        let serial = smithay::utils::SERIAL_COUNTER.next_serial();
+        let target = self.space.focus_candidate();
+        if let Some(keyboard) = self.seat.get_keyboard() {
+            keyboard.set_focus(self, target.map(KeyboardFocusTarget::from), serial);
+        }
+    }
+
+    pub fn focus_window(&mut self, window: &crate::shell::WindowElement) {
+        if self.overview.is_open() {
+            return;
+        }
+        let serial = smithay::utils::SERIAL_COUNTER.next_serial();
+        if let Some(keyboard) = self.seat.get_keyboard() {
+            keyboard.set_focus(self, Some(window.clone().into()), serial);
+        }
+    }
+
+    /// Clear focus from surfaces that were destroyed by their clients.
+    pub fn ensure_focus_valid(&mut self) {
+        let keyboard = self.seat.get_keyboard();
+        if let Some(keyboard) = keyboard {
+            if keyboard
+                .current_focus()
+                .map(|focus| !focus.alive())
+                .unwrap_or(false)
+            {
+                self.restore_workspace_focus();
+                self.refresh_pointer_focus(smithay::utils::SERIAL_COUNTER.next_serial());
+            }
+        }
+    }
+
+    /// Switch the active workspace and move input focus with it.
+    pub fn switch_workspace(&mut self, index: usize) -> bool {
+        let Some(output) = self.output_for_pointer() else {
+            return false;
+        };
+        if !self.space.switch_to(index, &output) {
+            return false;
+        }
+
+        self.restore_workspace_focus();
+        self.refresh_pointer_focus(smithay::utils::SERIAL_COUNTER.next_serial());
+        self.backend_data.reset_buffers(&output);
+        true
+    }
+
+    pub fn cycle_workspace(&mut self, delta: isize) -> bool {
+        let Some(output) = self.output_for_pointer() else {
+            return false;
+        };
+        if !self.space.cycle(delta, &output) {
+            return false;
+        }
+
+        self.restore_workspace_focus();
+        self.refresh_pointer_focus(smithay::utils::SERIAL_COUNTER.next_serial());
+        self.backend_data.reset_buffers(&output);
+        true
+    }
+
+    /// Move the focused window to another workspace, staying on the current one.
+    pub fn move_focused_window_to_workspace(&mut self, index: usize) -> bool {
+        let Some(window) = self.focused_window() else {
+            return false;
+        };
+        if !self.space.move_window(&window, index) {
+            return false;
+        }
+
+        self.restore_workspace_focus();
+        self.refresh_pointer_focus(smithay::utils::SERIAL_COUNTER.next_serial());
+        if let Some(output) = self.output_for_pointer() {
+            self.backend_data.reset_buffers(&output);
+        }
+        true
+    }
+
+    pub fn close_focused_window(&mut self) {
+        if let Some(window) = self.focused_window() {
+            if let Some(toplevel) = window.0.toplevel() {
+                toplevel.send_close();
+            }
+        }
+    }
+
+    pub fn overview_workspace_info(&self) -> (usize, [usize; 6]) {
+        (
+            self.space.active(),
+            std::array::from_fn(|index| self.space.window_count(index)),
+        )
+    }
+
+    pub fn overview_local(&self, location: Point<f64, Logical>) -> Option<(f64, f64)> {
+        let output = self.output_for_pointer()?;
+        let geometry = self.space.output_geometry(&output)?;
+        Some((
+            location.x - geometry.loc.x as f64,
+            location.y - geometry.loc.y as f64,
+        ))
+    }
+
+    pub(crate) fn repaint_overview(&mut self) {
+        if let Some(output) = self.output_for_pointer() {
+            self.backend_data.reset_buffers(&output);
+        }
+    }
+
+    pub fn open_overview(&mut self) {
+        if self.overview.is_open() {
+            return;
+        }
+        let Some(output) = self.output_for_pointer() else {
+            return;
+        };
+
+        self.cancel_overview_repeat();
+        self.overview.open();
+        self.cursor_status = CursorImageStatus::default_named();
+        let serial = smithay::utils::SERIAL_COUNTER.next_serial();
+        if let Some(keyboard) = self.seat.get_keyboard() {
+            keyboard.set_focus(self, None, serial);
+        }
+
+        let location = self.pointer.current_location();
+        let pointer = self.pointer.clone();
+        pointer.motion(
+            self,
+            None,
+            &smithay::input::pointer::MotionEvent {
+                location,
+                serial,
+                time: self.clock.now().as_millis(),
+            },
+        );
+        pointer.frame(self);
+        self.backend_data.reset_buffers(&output);
+    }
+
+    pub fn close_overview(&mut self) {
+        if !self.overview.is_open() {
+            return;
+        }
+        self.cancel_overview_repeat();
+        self.overview.close();
+        self.cursor_status = CursorImageStatus::default_named();
+        self.restore_workspace_focus();
+        self.refresh_pointer_focus(smithay::utils::SERIAL_COUNTER.next_serial());
+        self.repaint_overview();
+    }
+
+    pub fn toggle_overview(&mut self) {
+        if self.overview.is_open() {
+            self.close_overview();
+        } else {
+            self.open_overview();
+        }
+    }
+
+    pub fn handle_overview_action(&mut self, action: OverviewAction) {
+        match action {
+            OverviewAction::None => {}
+            OverviewAction::Close => self.close_overview(),
+            OverviewAction::SwitchWorkspace(index) => {
+                self.close_overview();
+                self.switch_workspace(index);
+            }
+            OverviewAction::Launch(index) => {
+                let Some(app) = self.overview.app(index).cloned() else {
+                    return;
+                };
+                let terminal = self.overview.terminal().clone();
+                match crate::apps::launch(&app, &terminal, self.socket_name.as_deref()) {
+                    Ok(()) => self.close_overview(),
+                    Err(err) => {
+                        self.overview.set_error(err);
+                        self.repaint_overview();
+                    }
+                }
+            }
+        }
+    }
+
+    pub fn overview_key_action(
+        &mut self,
+        key_state: smithay::backend::input::KeyState,
+        modifiers: &smithay::input::keyboard::ModifiersState,
+        handle: &smithay::input::keyboard::KeysymHandle<'_>,
+    ) -> OverviewAction {
+        use crate::overview::RepeatAction;
+        use smithay::{
+            backend::input::KeyState,
+            input::keyboard::{keysyms as xkb, Keysym},
+        };
+
+        let keysym = handle.modified_sym();
+        let raw_sym = handle
+            .raw_syms()
+            .first()
+            .copied()
+            .unwrap_or(Keysym::NoSymbol);
+        if matches!(key_state, KeyState::Released) {
+            if self.repeat_keysym == Some(keysym) {
+                self.cancel_overview_repeat();
+            }
+            return self.overview.handle_key(key_state, modifiers, keysym, "");
+        }
+
+        if modifiers.logo && keysym == Keysym::space {
+            self.cancel_overview_repeat();
+            return OverviewAction::Close;
+        }
+        if modifiers.logo && (xkb::KEY_1..=xkb::KEY_6).contains(&raw_sym.raw()) {
+            self.cancel_overview_repeat();
+            return OverviewAction::SwitchWorkspace((raw_sym.raw() - xkb::KEY_1) as usize);
+        }
+        if keysym == Keysym::Escape {
+            self.cancel_overview_repeat();
+            return OverviewAction::Close;
+        }
+
+        let text = if !modifiers.ctrl && !modifiers.alt && !modifiers.logo {
+            let xkb_state = handle.xkb().lock().unwrap();
+            // The state lives at least as long as the guard; this only
+            // materializes the current UTF-8 character.
+            unsafe { xkb_state.state().key_get_utf8(handle.raw_code()) }
+        } else {
+            String::new()
+        };
+
+        let repeat = if !modifiers.ctrl && !modifiers.alt && !modifiers.logo {
+            if !text.is_empty() && text.chars().count() == 1 && !text.chars().any(char::is_control)
+            {
+                Some(RepeatAction::Text(text.clone()))
+            } else {
+                match keysym {
+                    Keysym::BackSpace => Some(RepeatAction::Backspace),
+                    Keysym::Delete => Some(RepeatAction::Delete),
+                    Keysym::Left => Some(RepeatAction::CursorLeft),
+                    Keysym::Right => Some(RepeatAction::CursorRight),
+                    Keysym::Up => Some(RepeatAction::SelectionUp),
+                    Keysym::Down => Some(RepeatAction::SelectionDown),
+                    _ => None,
+                }
+            }
+        } else {
+            None
+        };
+
+        if let Some(repeat) = repeat {
+            self.arm_overview_repeat(keysym, repeat);
+        } else {
+            self.cancel_overview_repeat();
+        }
+
+        self.overview
+            .handle_key(key_state, modifiers, keysym, &text)
+    }
+
+    fn arm_overview_repeat(&mut self, keysym: Keysym, action: crate::overview::RepeatAction) {
+        self.cancel_overview_repeat();
+        let timer = Timer::from_duration(Duration::from_millis(420));
+        let token = self
+            .handle
+            .insert_source(timer, |_, _, data: &mut CompositronState<BackendData>| {
+                if let Some(action) = data.repeat_action.clone() {
+                    data.overview.apply_repeat(action);
+                    data.repaint_overview();
+                }
+                TimeoutAction::ToDuration(Duration::from_millis(35))
+            })
+            .ok();
+        self.repeat_token = token;
+        self.repeat_action = Some(action);
+        self.repeat_keysym = Some(keysym);
+    }
+
+    fn cancel_overview_repeat(&mut self) {
+        if let Some(token) = self.repeat_token.take() {
+            self.handle.remove(token);
+        }
+        self.repeat_action = None;
+        self.repeat_keysym = None;
+    }
+
+    pub fn cycle_focused_window(&mut self, forward: bool) {
+        let windows = self.space.elements().cloned().collect::<Vec<_>>();
+        if windows.len() < 2 {
+            return;
+        }
+
+        let current = self.focused_window();
+        let index = current.and_then(|window| windows.iter().position(|entry| entry == &window));
+        let target_index = match (index, forward) {
+            (Some(index), true) => (index + 1) % windows.len(),
+            (Some(index), false) => (index + windows.len() - 1) % windows.len(),
+            (None, true) => windows.len() - 1,
+            (None, false) => 0,
+        };
+
+        let target = windows[target_index].clone();
+        self.space.raise_element(&target, true);
+        let serial = smithay::utils::SERIAL_COUNTER.next_serial();
+        if let Some(keyboard) = self.seat.get_keyboard() {
+            keyboard.set_focus(self, Some(target.into()), serial);
+        }
+    }
+
+    pub fn snap_focused_window(&mut self, left: bool) {
+        let Some(output) = self.output_for_pointer() else {
+            return;
+        };
+        let Some(output_geometry) = self.space.output_geometry(&output) else {
+            return;
+        };
+        let Some(window) = self.focused_window() else {
+            return;
+        };
+        let Some(toplevel) = window.0.toplevel() else {
+            return;
+        };
+
+        if toplevel
+            .current_state()
+            .states
+            .contains(smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::State::Fullscreen)
+        {
+            self.unfullscreen_request(toplevel.clone());
+        }
+
+        let width = output_geometry.size.w / 2;
+        toplevel.with_pending_state(|state| {
+            state.states.unset(smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::State::Maximized);
+            state.size = Some(smithay::utils::Size::from((
+                width,
+                output_geometry.size.h,
+            )));
+        });
+        if toplevel.is_initial_configure_sent() {
+            toplevel.send_pending_configure();
+        }
+
+        let location = smithay::utils::Point::<i32, Logical>::from((
+            output_geometry.loc.x + if left { 0 } else { width },
+            output_geometry.loc.y,
+        ));
+        self.space.map_element(window, location, true);
+        self.backend_data.reset_buffers(&output);
+    }
+
+    #[cfg(feature = "xwayland")]
+    pub fn start_xwayland(&mut self) {
+        use std::process::Stdio;
+
+        use smithay::wayland::compositor::CompositorHandler;
+
+        let (xwayland, client) = XWayland::spawn(
+            &self.display_handle,
+            None,
+            std::iter::empty::<(String, String)>(),
+            true,
+            Stdio::null(),
+            Stdio::null(),
+            |_| (),
+        )
+        .expect("failed to start XWayland");
+
+        let ret = self
+            .handle
+            .insert_source(xwayland, move |event, _, data| match event {
+                XWaylandEvent::Ready {
+                    x11_socket,
+                    display_number,
+                } => {
+                    let xwayland_scale = std::env::var("ANVIL_XWAYLAND_SCALE")
+                        .ok()
+                        .and_then(|s| s.parse::<f64>().ok())
+                        .unwrap_or(1.);
+                    data.client_compositor_state(&client)
+                        .set_client_scale(xwayland_scale);
+                    let mut wm = X11Wm::start_wm(data.handle.clone(), x11_socket, client.clone())
+                        .expect("Failed to attach X11 Window Manager");
+
+                    let cursor = Cursor::load();
+                    let image = cursor.get_image(1, Duration::ZERO);
+                    wm.set_cursor(
+                        &image.pixels_rgba,
+                        Size::from((image.width as u16, image.height as u16)),
+                        Point::from((image.xhot as u16, image.yhot as u16)),
+                    )
+                    .expect("Failed to set xwayland default cursor");
+                    data.xwm = Some(wm);
+                    data.xdisplay = Some(display_number);
+                }
+                XWaylandEvent::Error => {
+                    warn!("XWayland crashed on startup");
+                }
+            });
+        if let Err(e) = ret {
+            tracing::error!(
+                "Failed to insert the XWaylandSource into the event loop: {}",
+                e
+            );
+        }
+    }
+}
+
+impl<BackendData: Backend + 'static> CompositronState<BackendData> {
+    pub fn pre_repaint(&mut self, output: &Output, frame_target: impl Into<Time<Monotonic>>) {
+        let frame_target = frame_target.into();
+
+        #[allow(clippy::mutable_key_type)]
+        let mut clients: HashMap<ClientId, Client> = HashMap::new();
+        self.space.elements().for_each(|window| {
+            window.with_surfaces(|surface, states| {
+                if let Some(mut commit_timer_state) = states
+                    .data_map
+                    .get::<CommitTimerBarrierStateUserData>()
+                    .map(|commit_timer| commit_timer.lock().unwrap())
+                {
+                    commit_timer_state.signal_until(frame_target);
+                    let client = surface.client().unwrap();
+                    clients.insert(client.id(), client);
+                }
+            });
+        });
+
+        let map = smithay::desktop::layer_map_for_output(output);
+        for layer_surface in map.layers() {
+            layer_surface.with_surfaces(|surface, states| {
+                if let Some(mut commit_timer_state) = states
+                    .data_map
+                    .get::<CommitTimerBarrierStateUserData>()
+                    .map(|commit_timer| commit_timer.lock().unwrap())
+                {
+                    commit_timer_state.signal_until(frame_target);
+                    let client = surface.client().unwrap();
+                    clients.insert(client.id(), client);
+                }
+            });
+        }
+        // Drop the lock to the layer map before calling blocker_cleared, which might end up
+        // calling the commit handler which in turn again could access the layer map.
+        std::mem::drop(map);
+
+        if let CursorImageStatus::Surface(ref surface) = self.cursor_status {
+            with_surfaces_surface_tree(surface, |surface, states| {
+                if let Some(mut commit_timer_state) = states
+                    .data_map
+                    .get::<CommitTimerBarrierStateUserData>()
+                    .map(|commit_timer| commit_timer.lock().unwrap())
+                {
+                    commit_timer_state.signal_until(frame_target);
+                    let client = surface.client().unwrap();
+                    clients.insert(client.id(), client);
+                }
+            });
+        }
+
+        if let Some(surface) = self.dnd_icon.as_ref().map(|icon| &icon.surface) {
+            with_surfaces_surface_tree(surface, |surface, states| {
+                if let Some(mut commit_timer_state) = states
+                    .data_map
+                    .get::<CommitTimerBarrierStateUserData>()
+                    .map(|commit_timer| commit_timer.lock().unwrap())
+                {
+                    commit_timer_state.signal_until(frame_target);
+                    let client = surface.client().unwrap();
+                    clients.insert(client.id(), client);
+                }
+            });
+        }
+
+        let dh = self.display_handle.clone();
+        for client in clients.into_values() {
+            self.client_compositor_state(&client)
+                .blocker_cleared(self, &dh);
+        }
+    }
+
+    pub fn post_repaint(
+        &mut self,
+        output: &Output,
+        time: impl Into<Duration>,
+        dmabuf_feedback: Option<SurfaceDmabufFeedback>,
+        render_element_states: &RenderElementStates,
+    ) {
+        let time = time.into();
+        let throttle = Some(Duration::from_secs(1));
+
+        #[allow(clippy::mutable_key_type)]
+        let mut clients: HashMap<ClientId, Client> = HashMap::new();
+
+        self.space.elements().for_each(|window| {
+            window.with_surfaces(|surface, states| {
+                let primary_scanout_output = surface_primary_scanout_output(surface, states);
+
+                if let Some(output) = primary_scanout_output.as_ref() {
+                    with_fractional_scale(states, |fraction_scale| {
+                        fraction_scale
+                            .set_preferred_scale(output.current_scale().fractional_scale());
+                    });
+                }
+
+                if primary_scanout_output
+                    .as_ref()
+                    .map(|o| o == output)
+                    .unwrap_or(true)
+                {
+                    let fifo_barrier = states
+                        .cached_state
+                        .get::<FifoBarrierCachedState>()
+                        .current()
+                        .barrier
+                        .take();
+
+                    if let Some(fifo_barrier) = fifo_barrier {
+                        fifo_barrier.signal();
+                        let client = surface.client().unwrap();
+                        clients.insert(client.id(), client);
+                    }
+                }
+            });
+
+            if self.space.outputs_for_element(window).contains(output) {
+                window.send_frame(output, time, throttle, surface_primary_scanout_output);
+                if let Some(dmabuf_feedback) = dmabuf_feedback.as_ref() {
+                    window.send_dmabuf_feedback(
+                        output,
+                        surface_primary_scanout_output,
+                        |surface, _| {
+                            select_dmabuf_feedback(
+                                surface,
+                                render_element_states,
+                                &dmabuf_feedback.render_feedback,
+                                &dmabuf_feedback.scanout_feedback,
+                            )
+                        },
+                    );
+                }
+            }
+        });
+        let map = smithay::desktop::layer_map_for_output(output);
+        for layer_surface in map.layers() {
+            layer_surface.with_surfaces(|surface, states| {
+                let primary_scanout_output = surface_primary_scanout_output(surface, states);
+
+                if let Some(output) = primary_scanout_output.as_ref() {
+                    with_fractional_scale(states, |fraction_scale| {
+                        fraction_scale
+                            .set_preferred_scale(output.current_scale().fractional_scale());
+                    });
+                }
+
+                if primary_scanout_output
+                    .as_ref()
+                    .map(|o| o == output)
+                    .unwrap_or(true)
+                {
+                    let fifo_barrier = states
+                        .cached_state
+                        .get::<FifoBarrierCachedState>()
+                        .current()
+                        .barrier
+                        .take();
+
+                    if let Some(fifo_barrier) = fifo_barrier {
+                        fifo_barrier.signal();
+                        let client = surface.client().unwrap();
+                        clients.insert(client.id(), client);
+                    }
+                }
+            });
+
+            layer_surface.send_frame(output, time, throttle, surface_primary_scanout_output);
+            if let Some(dmabuf_feedback) = dmabuf_feedback.as_ref() {
+                layer_surface.send_dmabuf_feedback(
+                    output,
+                    surface_primary_scanout_output,
+                    |surface, _| {
+                        select_dmabuf_feedback(
+                            surface,
+                            render_element_states,
+                            &dmabuf_feedback.render_feedback,
+                            &dmabuf_feedback.scanout_feedback,
+                        )
+                    },
+                );
+            }
+        }
+        // Drop the lock to the layer map before calling blocker_cleared, which might end up
+        // calling the commit handler which in turn again could access the layer map.
+        std::mem::drop(map);
+
+        if let CursorImageStatus::Surface(ref surface) = self.cursor_status {
+            with_surfaces_surface_tree(surface, |surface, states| {
+                let primary_scanout_output = surface_primary_scanout_output(surface, states);
+
+                if let Some(output) = primary_scanout_output.as_ref() {
+                    with_fractional_scale(states, |fraction_scale| {
+                        fraction_scale
+                            .set_preferred_scale(output.current_scale().fractional_scale());
+                    });
+                }
+
+                if primary_scanout_output
+                    .as_ref()
+                    .map(|o| o == output)
+                    .unwrap_or(true)
+                {
+                    let fifo_barrier = states
+                        .cached_state
+                        .get::<FifoBarrierCachedState>()
+                        .current()
+                        .barrier
+                        .take();
+
+                    if let Some(fifo_barrier) = fifo_barrier {
+                        fifo_barrier.signal();
+                        let client = surface.client().unwrap();
+                        clients.insert(client.id(), client);
+                    }
+                }
+            });
+        }
+
+        if let Some(surface) = self.dnd_icon.as_ref().map(|icon| &icon.surface) {
+            with_surfaces_surface_tree(surface, |surface, states| {
+                let primary_scanout_output = surface_primary_scanout_output(surface, states);
+
+                if let Some(output) = primary_scanout_output.as_ref() {
+                    with_fractional_scale(states, |fraction_scale| {
+                        fraction_scale
+                            .set_preferred_scale(output.current_scale().fractional_scale());
+                    });
+                }
+
+                if primary_scanout_output
+                    .as_ref()
+                    .map(|o| o == output)
+                    .unwrap_or(true)
+                {
+                    let fifo_barrier = states
+                        .cached_state
+                        .get::<FifoBarrierCachedState>()
+                        .current()
+                        .barrier
+                        .take();
+
+                    if let Some(fifo_barrier) = fifo_barrier {
+                        fifo_barrier.signal();
+                        let client = surface.client().unwrap();
+                        clients.insert(client.id(), client);
+                    }
+                }
+            });
+        }
+
+        let dh = self.display_handle.clone();
+        for client in clients.into_values() {
+            self.client_compositor_state(&client)
+                .blocker_cleared(self, &dh);
+        }
+    }
+}
+
+pub fn update_primary_scanout_output(
+    space: &Space<WindowElement>,
+    output: &Output,
+    dnd_icon: &Option<DndIcon>,
+    cursor_status: &CursorImageStatus,
+    render_element_states: &RenderElementStates,
+) {
+    space.elements().for_each(|window| {
+        window.with_surfaces(|surface, states| {
+            update_surface_primary_scanout_output(
+                surface,
+                output,
+                states,
+                render_element_states,
+                default_primary_scanout_output_compare,
+            );
+        });
+    });
+    let map = smithay::desktop::layer_map_for_output(output);
+    for layer_surface in map.layers() {
+        layer_surface.with_surfaces(|surface, states| {
+            update_surface_primary_scanout_output(
+                surface,
+                output,
+                states,
+                render_element_states,
+                default_primary_scanout_output_compare,
+            );
+        });
+    }
+
+    if let CursorImageStatus::Surface(ref surface) = cursor_status {
+        with_surfaces_surface_tree(surface, |surface, states| {
+            update_surface_primary_scanout_output(
+                surface,
+                output,
+                states,
+                render_element_states,
+                default_primary_scanout_output_compare,
+            );
+        });
+    }
+
+    if let Some(surface) = dnd_icon.as_ref().map(|icon| &icon.surface) {
+        with_surfaces_surface_tree(surface, |surface, states| {
+            update_surface_primary_scanout_output(
+                surface,
+                output,
+                states,
+                render_element_states,
+                default_primary_scanout_output_compare,
+            );
+        });
+    }
+}
+
+#[derive(Debug, Clone)]
+pub struct SurfaceDmabufFeedback {
+    pub render_feedback: DmabufFeedback,
+    pub scanout_feedback: DmabufFeedback,
+}
+
+#[profiling::function]
+pub fn take_presentation_feedback(
+    output: &Output,
+    space: &Space<WindowElement>,
+    render_element_states: &RenderElementStates,
+) -> OutputPresentationFeedback {
+    let mut output_presentation_feedback = OutputPresentationFeedback::new(output);
+
+    space.elements().for_each(|window| {
+        if space.outputs_for_element(window).contains(output) {
+            window.take_presentation_feedback(
+                &mut output_presentation_feedback,
+                surface_primary_scanout_output,
+                |surface, _| {
+                    surface_presentation_feedback_flags_from_states(surface, render_element_states)
+                },
+            );
+        }
+    });
+    let map = smithay::desktop::layer_map_for_output(output);
+    for layer_surface in map.layers() {
+        layer_surface.take_presentation_feedback(
+            &mut output_presentation_feedback,
+            surface_primary_scanout_output,
+            |surface, _| {
+                surface_presentation_feedback_flags_from_states(surface, render_element_states)
+            },
+        );
+    }
+
+    output_presentation_feedback
+}
+
+pub trait Backend {
+    const HAS_RELATIVE_MOTION: bool = false;
+    const HAS_GESTURES: bool = false;
+    fn seat_name(&self) -> String;
+    fn reset_buffers(&mut self, output: &Output);
+    fn early_import(&mut self, surface: &WlSurface);
+    fn update_led_state(&mut self, led_state: LedState);
+}

+ 203 - 0
src/text.rs

@@ -0,0 +1,203 @@
+//! Small text rendering helper for compositor-drawn UI.
+//!
+//! cosmic-text handles shaping and font fallback; glyphs are composited
+//! directly into a tiny-skia pixmap in premultiplied RGBA format.
+
+use std::collections::HashMap;
+
+use cosmic_text::{
+    Attrs, Buffer, Color, Ellipsize, EllipsizeHeightLimit, Family, FontSystem, Metrics, Shaping,
+    SwashCache, Wrap,
+};
+use tiny_skia::Pixmap;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct TextStyle {
+    pub size_bits: u32,
+    pub color: [u8; 4],
+    pub max_width_bits: u32,
+}
+
+impl TextStyle {
+    pub fn new(size: f32, color: [u8; 4], max_width: Option<f32>) -> Self {
+        Self {
+            size_bits: size.to_bits(),
+            color,
+            max_width_bits: max_width.unwrap_or(f32::INFINITY).to_bits(),
+        }
+    }
+
+    fn size(self) -> f32 {
+        f32::from_bits(self.size_bits)
+    }
+
+    fn max_width(self) -> Option<f32> {
+        let value = f32::from_bits(self.max_width_bits);
+        value.is_finite().then_some(value)
+    }
+}
+
+#[derive(Debug)]
+pub struct TextImage {
+    pub pixmap: Pixmap,
+    pub width: f32,
+    pub height: f32,
+}
+
+pub struct TextRenderer {
+    font_system: FontSystem,
+    swash_cache: SwashCache,
+    family: Option<String>,
+    cache: HashMap<(String, TextStyle), TextImage>,
+}
+
+impl TextRenderer {
+    pub fn new(family: Option<String>) -> Self {
+        Self {
+            font_system: FontSystem::new(),
+            swash_cache: SwashCache::new(),
+            family,
+            cache: HashMap::new(),
+        }
+    }
+
+    pub fn set_family(&mut self, family: Option<String>) {
+        if family != self.family {
+            self.family = family;
+            self.cache.clear();
+        }
+    }
+
+    pub fn clear_cache(&mut self) {
+        self.cache.clear();
+    }
+
+    /// Render one line of text, ellipsized to `max_width`.
+    pub fn render(&mut self, text: &str, style: TextStyle) -> &TextImage {
+        let key = (text.to_string(), style);
+        if !self.cache.contains_key(&key) {
+            let image = self.render_uncached(text, style);
+            self.cache.insert(key.clone(), image);
+        }
+        self.cache.get(&key).expect("text was just inserted")
+    }
+
+    fn render_uncached(&mut self, text: &str, style: TextStyle) -> TextImage {
+        let font_size = style.size().max(1.0);
+        let line_height = (font_size * 1.25).max(font_size);
+        let metrics = Metrics::new(font_size, line_height);
+        let mut buffer = Buffer::new(&mut self.font_system, metrics);
+
+        let attrs = match self.family.as_deref() {
+            Some(family) if !family.is_empty() => Attrs::new().family(Family::Name(family)),
+            _ => Attrs::new().family(Family::SansSerif),
+        };
+        buffer.set_text(text, &attrs, Shaping::Advanced, None);
+        buffer.set_wrap(Wrap::None);
+        buffer.set_ellipsize(Ellipsize::End(EllipsizeHeightLimit::Lines(1)));
+        buffer.set_size(Some(style.max_width().unwrap_or(4096.0)), Some(line_height));
+        buffer.shape_until_scroll(&mut self.font_system, false);
+
+        let width = buffer
+            .layout_runs()
+            .next()
+            .map(|run| run.line_w)
+            .unwrap_or(0.0)
+            .min(style.max_width().unwrap_or(f32::INFINITY))
+            .max(1.0);
+        let width_px = width.ceil().max(1.0) as u32;
+        let height_px = (line_height.ceil() + 4.0).max(1.0) as u32;
+        let mut pixmap = Pixmap::new(width_px, height_px).expect("valid text bitmap size");
+
+        let color = Color::rgba(
+            style.color[0],
+            style.color[1],
+            style.color[2],
+            style.color[3],
+        );
+        let padding = 2;
+        buffer.draw(
+            &mut self.font_system,
+            &mut self.swash_cache,
+            color,
+            |x, y, width, height, color| {
+                fill_premultiplied(&mut pixmap, x, y + padding, width, height, color.as_rgba())
+            },
+        );
+
+        TextImage {
+            pixmap,
+            width,
+            height: height_px as f32,
+        }
+    }
+}
+
+fn fill_premultiplied(
+    pixmap: &mut Pixmap,
+    x: i32,
+    y: i32,
+    width: u32,
+    height: u32,
+    color: [u8; 4],
+) {
+    if color[3] == 0 || width == 0 || height == 0 {
+        return;
+    }
+    let alpha = color[3] as u32;
+    let src = [
+        ((color[0] as u32 * alpha) / 255) as u8,
+        ((color[1] as u32 * alpha) / 255) as u8,
+        ((color[2] as u32 * alpha) / 255) as u8,
+        color[3],
+    ];
+
+    let pixmap_width = pixmap.width() as i32;
+    let pixmap_height = pixmap.height() as i32;
+    let x_start = x.max(0);
+    let y_start = y.max(0);
+    let x_end = (x + width as i32).min(pixmap_width);
+    let y_end = (y + height as i32).min(pixmap_height);
+    if x_start >= x_end || y_start >= y_end {
+        return;
+    }
+
+    let data = pixmap.data_mut();
+    for py in y_start..y_end {
+        for px in x_start..x_end {
+            let offset = ((py * pixmap_width + px) * 4) as usize;
+            let inverse = 255 - src[3] as u32;
+            data[offset] = (src[0] as u32 + (data[offset] as u32 * inverse) / 255) as u8;
+            data[offset + 1] = (src[1] as u32 + (data[offset + 1] as u32 * inverse) / 255) as u8;
+            data[offset + 2] = (src[2] as u32 + (data[offset + 2] as u32 * inverse) / 255) as u8;
+            data[offset + 3] = (src[3] as u32 + (data[offset + 3] as u32 * inverse) / 255) as u8;
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn renders_non_empty_bitmap() {
+        let mut renderer = TextRenderer::new(None);
+        let image = renderer.render(
+            "Compositron",
+            TextStyle::new(18.0, [255, 255, 255, 255], Some(300.0)),
+        );
+        assert!(image.width > 0.0);
+        assert!(image.pixmap.width() > 1);
+        assert!(image.pixmap.data().iter().any(|byte| *byte != 0));
+    }
+
+    #[test]
+    fn ellipsizes_long_text() {
+        let mut renderer = TextRenderer::new(None);
+        let image = renderer.render(
+            "An extremely long application name that should be cut off",
+            TextStyle::new(14.0, [255, 255, 255, 255], Some(80.0)),
+        );
+        assert!(image.width <= 81.0);
+    }
+}

+ 1783 - 0
src/udev.rs

@@ -0,0 +1,1783 @@
+use std::{
+    collections::hash_map::HashMap,
+    io,
+    ops::Not,
+    path::Path,
+    sync::{atomic::Ordering, Mutex, Once},
+    time::{Duration, Instant},
+};
+
+use crate::{
+    drawing::*,
+    render::*,
+    shell::WindowElement,
+    state::{take_presentation_feedback, update_primary_scanout_output, Backend, CompositronState},
+};
+use crate::{
+    shell::WindowRenderElement,
+    state::{DndIcon, SurfaceDmabufFeedback},
+};
+#[cfg(feature = "renderer_sync")]
+use smithay::backend::drm::compositor::PrimaryPlaneElement;
+#[cfg(feature = "egl")]
+use smithay::backend::renderer::ImportEgl;
+#[cfg(feature = "debug")]
+use smithay::backend::renderer::{multigpu::MultiTexture, ImportMem};
+use smithay::{
+    backend::{
+        allocator::{
+            dmabuf::Dmabuf,
+            format::FormatSet,
+            gbm::{GbmAllocator, GbmBufferFlags, GbmDevice},
+            Fourcc, Modifier,
+        },
+        drm::{
+            compositor::{DrmCompositor, FrameFlags},
+            exporter::gbm::GbmFramebufferExporter,
+            output::{DrmOutput, DrmOutputManager, DrmOutputRenderElements},
+            CreateDrmNodeError, DrmAccessError, DrmDevice, DrmDeviceFd, DrmError, DrmEvent,
+            DrmEventMetadata, DrmEventTime, DrmNode, DrmSurface, GbmBufferedSurface, NodeType,
+        },
+        egl::{self, context::ContextPriority, EGLDevice, EGLDisplay},
+        input::InputEvent,
+        libinput::{LibinputInputBackend, LibinputSessionInterface},
+        renderer::{
+            damage::Error as OutputDamageTrackerError,
+            element::{memory::MemoryRenderBuffer, AsRenderElements, RenderElementStates},
+            gles::GlesRenderer,
+            multigpu::{gbm::GbmGlesBackend, GpuManager, MultiRenderer},
+            DebugFlags, ImportDma, ImportMemWl,
+        },
+        session::{
+            libseat::{self, LibSeatSession},
+            Event as SessionEvent, Session,
+        },
+        udev::{all_gpus, primary_gpu, UdevBackend, UdevEvent},
+        SwapBuffersError,
+    },
+    delegate_dmabuf, delegate_drm_lease,
+    desktop::{
+        space::{Space, SurfaceTree},
+        utils::OutputPresentationFeedback,
+    },
+    input::{
+        keyboard::LedState,
+        pointer::{CursorImageAttributes, CursorImageStatus},
+    },
+    output::{Mode as WlMode, Output, PhysicalProperties, Scale as OutputScale},
+    reexports::{
+        calloop::{
+            timer::{TimeoutAction, Timer},
+            EventLoop, RegistrationToken,
+        },
+        drm::{
+            control::{connector, crtc, Device, ModeTypeFlags},
+            Device as _,
+        },
+        input::{DeviceCapability, Libinput},
+        rustix::fs::OFlags,
+        wayland_protocols::wp::{
+            linux_dmabuf::zv1::server::zwp_linux_dmabuf_feedback_v1,
+            presentation_time::server::wp_presentation_feedback,
+        },
+        wayland_server::{backend::GlobalId, protocol::wl_surface, Display, DisplayHandle},
+    },
+    utils::{DeviceFd, IsAlive, Logical, Monotonic, Point, Scale, Time, Transform},
+    wayland::{
+        compositor,
+        dmabuf::{DmabufFeedbackBuilder, DmabufGlobal, DmabufHandler, DmabufState, ImportNotifier},
+        drm_lease::{
+            DrmLease, DrmLeaseBuilder, DrmLeaseHandler, DrmLeaseRequest, DrmLeaseState,
+            LeaseRejected,
+        },
+        drm_syncobj::{supports_syncobj_eventfd, DrmSyncobjHandler, DrmSyncobjState},
+        presentation::Refresh,
+    },
+};
+use smithay_drm_extras::drm_scanner::{DrmScanEvent, DrmScanner};
+use tracing::{debug, error, info, trace, warn};
+
+// we cannot simply pick the first supported format of the intersection of *all* formats, because:
+// - we do not want something like Abgr4444, which looses color information, if something better is available
+// - some formats might perform terribly
+// - we might need some work-arounds, if one supports modifiers, but the other does not
+//
+// So lets just pick `ARGB2101010` (10-bit) or `ARGB8888` (8-bit) for now, they are widely supported.
+const SUPPORTED_FORMATS: &[Fourcc] = &[
+    Fourcc::Abgr2101010,
+    Fourcc::Argb2101010,
+    Fourcc::Abgr8888,
+    Fourcc::Argb8888,
+];
+const SUPPORTED_FORMATS_8BIT_ONLY: &[Fourcc] = &[Fourcc::Abgr8888, Fourcc::Argb8888];
+
+type UdevRenderer<'a> = MultiRenderer<
+    'a,
+    'a,
+    GbmGlesBackend<GlesRenderer, DrmDeviceFd>,
+    GbmGlesBackend<GlesRenderer, DrmDeviceFd>,
+>;
+
+#[derive(Debug, PartialEq)]
+struct UdevOutputId {
+    device_id: DrmNode,
+    crtc: crtc::Handle,
+}
+
+pub struct UdevData {
+    pub session: LibSeatSession,
+    dh: DisplayHandle,
+    dmabuf_state: Option<(DmabufState, DmabufGlobal)>,
+    syncobj_state: Option<DrmSyncobjState>,
+    primary_gpu: DrmNode,
+    gpus: GpuManager<GbmGlesBackend<GlesRenderer, DrmDeviceFd>>,
+    backends: HashMap<DrmNode, BackendData>,
+    pointer_images: Vec<(xcursor::parser::Image, MemoryRenderBuffer)>,
+    pointer_element: PointerElement,
+    #[cfg(feature = "debug")]
+    fps_texture: Option<MultiTexture>,
+    pointer_image: crate::cursor::Cursor,
+    debug_flags: DebugFlags,
+    keyboards: Vec<smithay::reexports::input::Device>,
+}
+
+impl UdevData {
+    pub fn set_debug_flags(&mut self, flags: DebugFlags) {
+        if self.debug_flags != flags {
+            self.debug_flags = flags;
+
+            for (_, backend) in self.backends.iter_mut() {
+                for (_, surface) in backend.surfaces.iter_mut() {
+                    surface.drm_output.set_debug_flags(flags);
+                }
+            }
+        }
+    }
+
+    pub fn debug_flags(&self) -> DebugFlags {
+        self.debug_flags
+    }
+}
+
+impl DmabufHandler for CompositronState<UdevData> {
+    fn dmabuf_state(&mut self) -> &mut DmabufState {
+        &mut self.backend_data.dmabuf_state.as_mut().unwrap().0
+    }
+
+    fn dmabuf_imported(
+        &mut self,
+        _global: &DmabufGlobal,
+        dmabuf: Dmabuf,
+        notifier: ImportNotifier,
+    ) {
+        if self
+            .backend_data
+            .gpus
+            .single_renderer(&self.backend_data.primary_gpu)
+            .and_then(|mut renderer| renderer.import_dmabuf(&dmabuf, None))
+            .is_ok()
+        {
+            dmabuf.set_node(self.backend_data.primary_gpu);
+            let _ = notifier.successful::<CompositronState<UdevData>>();
+        } else {
+            notifier.failed();
+        }
+    }
+}
+delegate_dmabuf!(CompositronState<UdevData>);
+
+impl Backend for UdevData {
+    const HAS_RELATIVE_MOTION: bool = true;
+    const HAS_GESTURES: bool = true;
+
+    fn seat_name(&self) -> String {
+        self.session.seat()
+    }
+
+    fn reset_buffers(&mut self, output: &Output) {
+        if let Some(id) = output.user_data().get::<UdevOutputId>() {
+            if let Some(gpu) = self.backends.get_mut(&id.device_id) {
+                if let Some(surface) = gpu.surfaces.get_mut(&id.crtc) {
+                    surface.drm_output.reset_buffers();
+                }
+            }
+        }
+    }
+
+    fn early_import(&mut self, surface: &wl_surface::WlSurface) {
+        if let Err(err) = self.gpus.early_import(self.primary_gpu, surface) {
+            warn!("Early buffer import failed: {}", err);
+        }
+    }
+
+    fn update_led_state(&mut self, led_state: LedState) {
+        for keyboard in self.keyboards.iter_mut() {
+            keyboard.led_update(led_state.into());
+        }
+    }
+}
+
+pub fn run_udev() {
+    let mut event_loop = EventLoop::try_new().unwrap();
+    let display = Display::new().unwrap();
+    let mut display_handle = display.handle();
+
+    /*
+     * Initialize session
+     */
+    let (session, notifier) = match LibSeatSession::new() {
+        Ok(ret) => ret,
+        Err(err) => {
+            error!("Could not initialize a session: {}", err);
+            return;
+        }
+    };
+
+    /*
+     * Initialize the compositor
+     */
+    let primary_gpu = if let Ok(var) = std::env::var("ANVIL_DRM_DEVICE") {
+        DrmNode::from_path(var).expect("Invalid drm device path")
+    } else {
+        primary_gpu(session.seat())
+            .unwrap()
+            .and_then(|x| {
+                DrmNode::from_path(x)
+                    .ok()?
+                    .node_with_type(NodeType::Render)?
+                    .ok()
+            })
+            .unwrap_or_else(|| {
+                all_gpus(session.seat())
+                    .unwrap()
+                    .into_iter()
+                    .find_map(|x| DrmNode::from_path(x).ok())
+                    .expect("No GPU!")
+            })
+    };
+    info!("Using {} as primary gpu.", primary_gpu);
+
+    let gpus =
+        GpuManager::new(GbmGlesBackend::with_context_priority(ContextPriority::High)).unwrap();
+
+    let data = UdevData {
+        dh: display_handle.clone(),
+        dmabuf_state: None,
+        syncobj_state: None,
+        session,
+        primary_gpu,
+        gpus,
+        backends: HashMap::new(),
+        pointer_image: crate::cursor::Cursor::load(),
+        pointer_images: Vec::new(),
+        pointer_element: PointerElement::default(),
+        #[cfg(feature = "debug")]
+        fps_texture: None,
+        debug_flags: DebugFlags::empty(),
+        keyboards: Vec::new(),
+    };
+    let mut state = CompositronState::init(display, event_loop.handle(), data, true);
+
+    /*
+     * Initialize the udev backend
+     */
+    let udev_backend = match UdevBackend::new(&state.seat_name) {
+        Ok(ret) => ret,
+        Err(err) => {
+            error!(error = ?err, "Failed to initialize udev backend");
+            return;
+        }
+    };
+
+    /*
+     * Initialize libinput backend
+     */
+    let mut libinput_context = Libinput::new_with_udev::<LibinputSessionInterface<LibSeatSession>>(
+        state.backend_data.session.clone().into(),
+    );
+    libinput_context.udev_assign_seat(&state.seat_name).unwrap();
+    let libinput_backend = LibinputInputBackend::new(libinput_context.clone());
+
+    /*
+     * Bind all our objects that get driven by the event loop
+     */
+    event_loop
+        .handle()
+        .insert_source(libinput_backend, move |mut event, _, data| {
+            let dh = data.backend_data.dh.clone();
+            if let InputEvent::DeviceAdded { device } = &mut event {
+                if device.has_capability(DeviceCapability::Keyboard) {
+                    if let Some(led_state) = data
+                        .seat
+                        .get_keyboard()
+                        .map(|keyboard| keyboard.led_state())
+                    {
+                        device.led_update(led_state.into());
+                    }
+                    data.backend_data.keyboards.push(device.clone());
+                }
+            } else if let InputEvent::DeviceRemoved { ref device } = event {
+                if device.has_capability(DeviceCapability::Keyboard) {
+                    data.backend_data.keyboards.retain(|item| item != device);
+                }
+            }
+
+            data.process_input_event(&dh, event)
+        })
+        .unwrap();
+
+    event_loop
+        .handle()
+        .insert_source(notifier, move |event, &mut (), data| match event {
+            SessionEvent::PauseSession => {
+                libinput_context.suspend();
+                info!("pausing session");
+
+                for backend in data.backend_data.backends.values_mut() {
+                    backend.drm_output_manager.pause();
+                    backend.active_leases.clear();
+                    if let Some(lease_global) = backend.leasing_global.as_mut() {
+                        lease_global.suspend();
+                    }
+                }
+            }
+            SessionEvent::ActivateSession => {
+                info!("resuming session");
+
+                if let Err(err) = libinput_context.resume() {
+                    error!("Failed to resume libinput context: {:?}", err);
+                }
+                for (node, backend) in data
+                    .backend_data
+                    .backends
+                    .iter_mut()
+                    .map(|(handle, backend)| (*handle, backend))
+                {
+                    // if we do not care about flicking (caused by modesetting) we could just
+                    // pass true for disable connectors here. this would make sure our drm
+                    // device is in a known state (all connectors and planes disabled).
+                    // but for demonstration we choose a more optimistic path by leaving the
+                    // state as is and assume it will just work. If this assumption fails
+                    // we will try to reset the state when trying to queue a frame.
+                    backend
+                        .drm_output_manager
+                        .activate(false)
+                        .expect("failed to activate drm backend");
+                    if let Some(lease_global) = backend.leasing_global.as_mut() {
+                        lease_global.resume::<CompositronState<UdevData>>();
+                    }
+                    data.handle
+                        .insert_idle(move |data| data.render(node, None, data.clock.now()));
+                }
+            }
+        })
+        .unwrap();
+
+    // We try to initialize the primary node before others to make sure
+    // any display only node can fall back to the primary node for rendering
+    let primary_node = primary_gpu
+        .node_with_type(NodeType::Primary)
+        .and_then(|node| node.ok());
+    let primary_device = udev_backend.device_list().find(|(device_id, _)| {
+        primary_node
+            .map(|primary_node| *device_id == primary_node.dev_id())
+            .unwrap_or(false)
+            || *device_id == primary_gpu.dev_id()
+    });
+
+    if let Some((device_id, path)) = primary_device {
+        let node = DrmNode::from_dev_id(device_id).expect("failed to get primary node");
+        state
+            .device_added(node, path)
+            .expect("failed to initialize primary node");
+    }
+
+    let primary_device_id = primary_device.map(|(device_id, _)| device_id);
+    for (device_id, path) in udev_backend.device_list() {
+        if Some(device_id) == primary_device_id {
+            continue;
+        }
+
+        if let Err(err) = DrmNode::from_dev_id(device_id)
+            .map_err(DeviceAddError::DrmNode)
+            .and_then(|node| state.device_added(node, path))
+        {
+            error!("Skipping device {device_id}: {err}");
+        }
+    }
+    state.shm_state.update_formats(
+        state
+            .backend_data
+            .gpus
+            .single_renderer(&primary_gpu)
+            .unwrap()
+            .shm_formats(),
+    );
+
+    #[cfg_attr(not(feature = "egl"), allow(unused_mut))]
+    let mut renderer = state
+        .backend_data
+        .gpus
+        .single_renderer(&primary_gpu)
+        .unwrap();
+
+    #[cfg(feature = "debug")]
+    {
+        #[allow(deprecated)]
+        let fps_image = image::io::Reader::with_format(
+            std::io::Cursor::new(FPS_NUMBERS_PNG),
+            image::ImageFormat::Png,
+        )
+        .decode()
+        .unwrap();
+        let fps_texture = renderer
+            .import_memory(
+                &fps_image.to_rgba8(),
+                Fourcc::Abgr8888,
+                (fps_image.width() as i32, fps_image.height() as i32).into(),
+                false,
+            )
+            .expect("Unable to upload FPS texture");
+
+        for backend in state.backend_data.backends.values_mut() {
+            for surface in backend.surfaces.values_mut() {
+                surface.fps_element = Some(FpsElement::new(fps_texture.clone()));
+            }
+        }
+        state.backend_data.fps_texture = Some(fps_texture);
+    }
+
+    #[cfg(feature = "egl")]
+    {
+        info!(
+            ?primary_gpu,
+            "Trying to initialize EGL Hardware Acceleration",
+        );
+        match renderer.bind_wl_display(&display_handle) {
+            Ok(_) => info!("EGL hardware-acceleration enabled"),
+            Err(err) => info!(?err, "Failed to initialize EGL hardware-acceleration"),
+        }
+    }
+
+    // init dmabuf support with format list from our primary gpu
+    let dmabuf_formats = renderer.dmabuf_formats();
+    let default_feedback = DmabufFeedbackBuilder::new(primary_gpu.dev_id(), dmabuf_formats)
+        .build()
+        .unwrap();
+    let mut dmabuf_state = DmabufState::new();
+    let global = dmabuf_state.create_global_with_default_feedback::<CompositronState<UdevData>>(
+        &display_handle,
+        &default_feedback,
+    );
+    state.backend_data.dmabuf_state = Some((dmabuf_state, global));
+
+    let gpus = &mut state.backend_data.gpus;
+    state
+        .backend_data
+        .backends
+        .iter_mut()
+        .for_each(|(node, backend_data)| {
+            // Update the per drm surface dmabuf feedback
+            backend_data.surfaces.values_mut().for_each(|surface_data| {
+                surface_data.dmabuf_feedback = surface_data.dmabuf_feedback.take().or_else(|| {
+                    surface_data.drm_output.with_compositor(|compositor| {
+                        get_surface_dmabuf_feedback(
+                            primary_gpu,
+                            surface_data.render_node,
+                            *node,
+                            gpus,
+                            compositor.surface(),
+                        )
+                    })
+                });
+            });
+        });
+
+    // Expose syncobj protocol if supported by primary GPU
+    if let Some(primary_node) = state
+        .backend_data
+        .primary_gpu
+        .node_with_type(NodeType::Primary)
+        .and_then(|x| x.ok())
+    {
+        if let Some(backend) = state.backend_data.backends.get(&primary_node) {
+            let import_device = backend.drm_output_manager.device().device_fd().clone();
+            if supports_syncobj_eventfd(&import_device) {
+                let syncobj_state = DrmSyncobjState::new::<CompositronState<UdevData>>(
+                    &display_handle,
+                    import_device,
+                );
+                state.backend_data.syncobj_state = Some(syncobj_state);
+            }
+        }
+    }
+
+    event_loop
+        .handle()
+        .insert_source(udev_backend, move |event, _, data| match event {
+            UdevEvent::Added { device_id, path } => {
+                if let Err(err) = DrmNode::from_dev_id(device_id)
+                    .map_err(DeviceAddError::DrmNode)
+                    .and_then(|node| data.device_added(node, &path))
+                {
+                    error!("Skipping device {device_id}: {err}");
+                }
+            }
+            UdevEvent::Changed { device_id } => {
+                if let Ok(node) = DrmNode::from_dev_id(device_id) {
+                    data.device_changed(node)
+                }
+            }
+            UdevEvent::Removed { device_id } => {
+                if let Ok(node) = DrmNode::from_dev_id(device_id) {
+                    data.device_removed(node)
+                }
+            }
+        })
+        .unwrap();
+
+    /*
+     * Start XWayland if supported
+     */
+    #[cfg(feature = "xwayland")]
+    state.start_xwayland();
+
+    /*
+     * And run our loop
+     */
+
+    while state.running.load(Ordering::SeqCst) {
+        let result = event_loop.dispatch(Some(Duration::from_millis(16)), &mut state);
+        if result.is_err() {
+            state.running.store(false, Ordering::SeqCst);
+        } else {
+            state.space.refresh();
+            state.ensure_focus_valid();
+            state.popups.cleanup();
+            display_handle.flush_clients().unwrap();
+        }
+    }
+}
+
+impl DrmLeaseHandler for CompositronState<UdevData> {
+    fn drm_lease_state(&mut self, node: DrmNode) -> &mut DrmLeaseState {
+        self.backend_data
+            .backends
+            .get_mut(&node)
+            .unwrap()
+            .leasing_global
+            .as_mut()
+            .unwrap()
+    }
+
+    fn lease_request(
+        &mut self,
+        node: DrmNode,
+        request: DrmLeaseRequest,
+    ) -> Result<DrmLeaseBuilder, LeaseRejected> {
+        let backend = self
+            .backend_data
+            .backends
+            .get(&node)
+            .ok_or(LeaseRejected::default())?;
+
+        let drm_device = backend.drm_output_manager.device();
+        let mut builder = DrmLeaseBuilder::new(drm_device);
+        for conn in request.connectors {
+            if let Some((_, crtc)) = backend
+                .non_desktop_connectors
+                .iter()
+                .find(|(handle, _)| *handle == conn)
+            {
+                builder.add_connector(conn);
+                builder.add_crtc(*crtc);
+                let planes = drm_device.planes(crtc).map_err(LeaseRejected::with_cause)?;
+                let (primary_plane, primary_plane_claim) = planes
+                    .primary
+                    .iter()
+                    .find_map(|plane| {
+                        drm_device
+                            .claim_plane(plane.handle, *crtc)
+                            .map(|claim| (plane, claim))
+                    })
+                    .ok_or_else(LeaseRejected::default)?;
+                builder.add_plane(primary_plane.handle, primary_plane_claim);
+                if let Some((cursor, claim)) = planes.cursor.iter().find_map(|plane| {
+                    drm_device
+                        .claim_plane(plane.handle, *crtc)
+                        .map(|claim| (plane, claim))
+                }) {
+                    builder.add_plane(cursor.handle, claim);
+                }
+            } else {
+                tracing::warn!(
+                    ?conn,
+                    "Lease requested for desktop connector, denying request"
+                );
+                return Err(LeaseRejected::default());
+            }
+        }
+
+        Ok(builder)
+    }
+
+    fn new_active_lease(&mut self, node: DrmNode, lease: DrmLease) {
+        let backend = self.backend_data.backends.get_mut(&node).unwrap();
+        backend.active_leases.push(lease);
+    }
+
+    fn lease_destroyed(&mut self, node: DrmNode, lease: u32) {
+        let backend = self.backend_data.backends.get_mut(&node).unwrap();
+        backend.active_leases.retain(|l| l.id() != lease);
+    }
+}
+
+delegate_drm_lease!(CompositronState<UdevData>);
+
+impl DrmSyncobjHandler for CompositronState<UdevData> {
+    fn drm_syncobj_state(&mut self) -> Option<&mut DrmSyncobjState> {
+        self.backend_data.syncobj_state.as_mut()
+    }
+}
+smithay::delegate_drm_syncobj!(CompositronState<UdevData>);
+
+pub type RenderSurface =
+    GbmBufferedSurface<GbmAllocator<DrmDeviceFd>, Option<OutputPresentationFeedback>>;
+
+pub type GbmDrmCompositor = DrmCompositor<
+    GbmAllocator<DrmDeviceFd>,
+    GbmDevice<DrmDeviceFd>,
+    Option<OutputPresentationFeedback>,
+    DrmDeviceFd,
+>;
+
+struct SurfaceData {
+    dh: DisplayHandle,
+    device_id: DrmNode,
+    render_node: Option<DrmNode>,
+    global: Option<GlobalId>,
+    drm_output: DrmOutput<
+        GbmAllocator<DrmDeviceFd>,
+        GbmFramebufferExporter<DrmDeviceFd>,
+        Option<OutputPresentationFeedback>,
+        DrmDeviceFd,
+    >,
+    disable_direct_scanout: bool,
+    #[cfg(feature = "debug")]
+    fps: fps_ticker::Fps,
+    #[cfg(feature = "debug")]
+    fps_element: Option<FpsElement<MultiTexture>>,
+    dmabuf_feedback: Option<SurfaceDmabufFeedback>,
+    last_presentation_time: Option<Time<Monotonic>>,
+    vblank_throttle_timer: Option<RegistrationToken>,
+}
+
+impl Drop for SurfaceData {
+    fn drop(&mut self) {
+        if let Some(global) = self.global.take() {
+            self.dh.remove_global::<CompositronState<UdevData>>(global);
+        }
+    }
+}
+
+struct BackendData {
+    surfaces: HashMap<crtc::Handle, SurfaceData>,
+    non_desktop_connectors: Vec<(connector::Handle, crtc::Handle)>,
+    leasing_global: Option<DrmLeaseState>,
+    active_leases: Vec<DrmLease>,
+    drm_output_manager: DrmOutputManager<
+        GbmAllocator<DrmDeviceFd>,
+        GbmFramebufferExporter<DrmDeviceFd>,
+        Option<OutputPresentationFeedback>,
+        DrmDeviceFd,
+    >,
+    drm_scanner: DrmScanner,
+    render_node: Option<DrmNode>,
+    registration_token: RegistrationToken,
+}
+
+#[derive(Debug, thiserror::Error)]
+enum DeviceAddError {
+    #[error("Failed to open device using libseat: {0}")]
+    DeviceOpen(libseat::Error),
+    #[error("Failed to initialize drm device: {0}")]
+    DrmDevice(DrmError),
+    #[error("Failed to initialize gbm device: {0}")]
+    GbmDevice(std::io::Error),
+    #[error("Failed to access drm node: {0}")]
+    DrmNode(CreateDrmNodeError),
+    #[error("Failed to add device to GpuManager: {0}")]
+    AddNode(egl::Error),
+    #[error("The device has no render node")]
+    NoRenderNode,
+    #[error("Primary GPU is missing")]
+    PrimaryGpuMissing,
+}
+
+fn get_surface_dmabuf_feedback(
+    primary_gpu: DrmNode,
+    render_node: Option<DrmNode>,
+    scanout_node: DrmNode,
+    gpus: &mut GpuManager<GbmGlesBackend<GlesRenderer, DrmDeviceFd>>,
+    surface: &DrmSurface,
+) -> Option<SurfaceDmabufFeedback> {
+    let primary_formats = gpus.single_renderer(&primary_gpu).ok()?.dmabuf_formats();
+    let render_formats = if let Some(render_node) = render_node {
+        gpus.single_renderer(&render_node).ok()?.dmabuf_formats()
+    } else {
+        FormatSet::default()
+    };
+
+    let all_render_formats = primary_formats
+        .iter()
+        .chain(render_formats.iter())
+        .copied()
+        .collect::<FormatSet>();
+
+    let planes = surface.planes().clone();
+
+    // We limit the scan-out tranche to formats we can also render from
+    // so that there is always a fallback render path available in case
+    // the supplied buffer can not be scanned out directly
+    let planes_formats = surface
+        .plane_info()
+        .formats
+        .iter()
+        .copied()
+        .chain(planes.overlay.into_iter().flat_map(|p| p.formats))
+        .collect::<FormatSet>()
+        .intersection(&all_render_formats)
+        .copied()
+        .collect::<FormatSet>();
+
+    let builder = DmabufFeedbackBuilder::new(primary_gpu.dev_id(), primary_formats);
+    let render_feedback = if let Some(render_node) = render_node {
+        builder
+            .clone()
+            .add_preference_tranche(render_node.dev_id(), None, render_formats.clone())
+            .build()
+            .unwrap()
+    } else {
+        builder.clone().build().unwrap()
+    };
+
+    let scanout_feedback = builder
+        .add_preference_tranche(
+            surface.device_fd().dev_id().unwrap(),
+            Some(zwp_linux_dmabuf_feedback_v1::TrancheFlags::Scanout),
+            planes_formats,
+        )
+        .add_preference_tranche(scanout_node.dev_id(), None, render_formats)
+        .build()
+        .unwrap();
+
+    Some(SurfaceDmabufFeedback {
+        render_feedback,
+        scanout_feedback,
+    })
+}
+
+impl CompositronState<UdevData> {
+    fn device_added(&mut self, node: DrmNode, path: &Path) -> Result<(), DeviceAddError> {
+        // Try to open the device
+        let fd = self
+            .backend_data
+            .session
+            .open(
+                path,
+                OFlags::RDWR | OFlags::CLOEXEC | OFlags::NOCTTY | OFlags::NONBLOCK,
+            )
+            .map_err(DeviceAddError::DeviceOpen)?;
+
+        let fd = DrmDeviceFd::new(DeviceFd::from(fd));
+
+        let (drm, notifier) =
+            DrmDevice::new(fd.clone(), true).map_err(DeviceAddError::DrmDevice)?;
+        let gbm = GbmDevice::new(fd).map_err(DeviceAddError::GbmDevice)?;
+
+        let registration_token = self
+            .handle
+            .insert_source(
+                notifier,
+                move |event, metadata, data: &mut CompositronState<_>| match event {
+                    DrmEvent::VBlank(crtc) => {
+                        profiling::scope!("vblank", &format!("{crtc:?}"));
+                        data.frame_finish(node, crtc, metadata);
+                    }
+                    DrmEvent::Error(error) => {
+                        error!("{:?}", error);
+                    }
+                },
+            )
+            .unwrap();
+
+        let mut try_initialize_gpu = || {
+            let display = unsafe { EGLDisplay::new(gbm.clone()).map_err(DeviceAddError::AddNode)? };
+            let egl_device =
+                EGLDevice::device_for_display(&display).map_err(DeviceAddError::AddNode)?;
+
+            if egl_device.is_software() {
+                return Err(DeviceAddError::NoRenderNode);
+            }
+
+            let render_node = egl_device
+                .try_get_render_node()
+                .ok()
+                .flatten()
+                .unwrap_or(node);
+            self.backend_data
+                .gpus
+                .as_mut()
+                .add_node(render_node, gbm.clone())
+                .map_err(DeviceAddError::AddNode)?;
+
+            std::result::Result::<DrmNode, DeviceAddError>::Ok(render_node)
+        };
+
+        let render_node = try_initialize_gpu()
+            .inspect_err(|err| {
+                warn!(?err, "failed to initialize gpu");
+            })
+            .ok();
+
+        let allocator = render_node
+            .is_some()
+            .then(|| {
+                GbmAllocator::new(
+                    gbm.clone(),
+                    GbmBufferFlags::RENDERING | GbmBufferFlags::SCANOUT,
+                )
+            })
+            .or_else(|| {
+                self.backend_data
+                    .backends
+                    .get(&self.backend_data.primary_gpu)
+                    .or_else(|| {
+                        self.backend_data.backends.values().find(|backend| {
+                            backend.render_node == Some(self.backend_data.primary_gpu)
+                        })
+                    })
+                    .map(|backend| backend.drm_output_manager.allocator().clone())
+            })
+            .ok_or(DeviceAddError::PrimaryGpuMissing)?;
+
+        let framebuffer_exporter = GbmFramebufferExporter::new(gbm.clone(), render_node);
+
+        let color_formats = if std::env::var("ANVIL_DISABLE_10BIT").is_ok() {
+            SUPPORTED_FORMATS_8BIT_ONLY
+        } else {
+            SUPPORTED_FORMATS
+        };
+        let mut renderer = self
+            .backend_data
+            .gpus
+            .single_renderer(&render_node.unwrap_or(self.backend_data.primary_gpu))
+            .unwrap();
+        let render_formats = renderer
+            .as_mut()
+            .egl_context()
+            .dmabuf_render_formats()
+            .iter()
+            .filter(|format| render_node.is_some() || format.modifier == Modifier::Linear)
+            .copied()
+            .collect::<FormatSet>();
+
+        let drm_output_manager = DrmOutputManager::new(
+            drm,
+            allocator,
+            framebuffer_exporter,
+            Some(gbm),
+            color_formats.iter().copied(),
+            render_formats,
+        );
+
+        self.backend_data.backends.insert(
+            node,
+            BackendData {
+                registration_token,
+                drm_output_manager,
+                drm_scanner: DrmScanner::new(),
+                non_desktop_connectors: Vec::new(),
+                render_node,
+                surfaces: HashMap::new(),
+                leasing_global: DrmLeaseState::new::<CompositronState<UdevData>>(
+                    &self.display_handle,
+                    &node,
+                )
+                .inspect_err(|err| {
+                    warn!(?err, "Failed to initialize drm lease global for: {}", node);
+                })
+                .ok(),
+                active_leases: Vec::new(),
+            },
+        );
+
+        self.device_changed(node);
+
+        Ok(())
+    }
+
+    fn connector_connected(
+        &mut self,
+        node: DrmNode,
+        connector: connector::Info,
+        crtc: crtc::Handle,
+    ) {
+        let device = if let Some(device) = self.backend_data.backends.get_mut(&node) {
+            device
+        } else {
+            return;
+        };
+
+        let render_node = device.render_node.unwrap_or(self.backend_data.primary_gpu);
+        let mut renderer = self
+            .backend_data
+            .gpus
+            .single_renderer(&render_node)
+            .unwrap();
+
+        let output_name = format!(
+            "{}-{}",
+            connector.interface().as_str(),
+            connector.interface_id()
+        );
+        info!(?crtc, "Trying to setup connector {}", output_name,);
+
+        let drm_device = device.drm_output_manager.device();
+
+        let non_desktop = drm_device
+            .get_properties(connector.handle())
+            .ok()
+            .and_then(|props| {
+                let (info, value) = props
+                    .into_iter()
+                    .filter_map(|(handle, value)| {
+                        let info = drm_device.get_property(handle).ok()?;
+
+                        Some((info, value))
+                    })
+                    .find(|(info, _)| info.name().to_str() == Ok("non-desktop"))?;
+
+                info.value_type().convert_value(value).as_boolean()
+            })
+            .unwrap_or(false);
+
+        // libdisplay-info is optional upstream. We only need a human-readable
+        // label here, so avoid an extra system library dependency.
+        let make = "Unknown".to_string();
+        let model = output_name.clone();
+
+        if non_desktop {
+            info!(
+                "Connector {} is non-desktop, setting up for leasing",
+                output_name
+            );
+            device
+                .non_desktop_connectors
+                .push((connector.handle(), crtc));
+            if let Some(lease_state) = device.leasing_global.as_mut() {
+                lease_state.add_connector::<CompositronState<UdevData>>(
+                    connector.handle(),
+                    output_name,
+                    format!("{} {}", make, model),
+                );
+            }
+        } else {
+            let mode_id = connector
+                .modes()
+                .iter()
+                .position(|mode| mode.mode_type().contains(ModeTypeFlags::PREFERRED))
+                .unwrap_or(0);
+
+            let drm_mode = connector.modes()[mode_id];
+            let wl_mode = WlMode::from(drm_mode);
+
+            let (phys_w, phys_h) = connector.size().unwrap_or((0, 0));
+            let output = Output::new(
+                output_name,
+                PhysicalProperties {
+                    size: (phys_w as i32, phys_h as i32).into(),
+                    subpixel: connector.subpixel().into(),
+                    make,
+                    model,
+                },
+            );
+            let global = output.create_global::<CompositronState<UdevData>>(&self.display_handle);
+
+            let x = self.space.outputs().fold(0, |acc, o| {
+                acc + self.space.output_geometry(o).unwrap().size.w
+            });
+            let position = (x, 0).into();
+
+            output.set_preferred(wl_mode);
+            output.change_current_state(
+                Some(wl_mode),
+                None,
+                Some(OutputScale::Fractional(self.config.output_scale())),
+                Some(position),
+            );
+            self.space.map_output(&output, position);
+
+            output.user_data().insert_if_missing(|| UdevOutputId {
+                crtc,
+                device_id: node,
+            });
+
+            #[cfg(feature = "debug")]
+            let fps_element = self.backend_data.fps_texture.clone().map(FpsElement::new);
+
+            let driver = match drm_device.get_driver() {
+                Ok(driver) => driver,
+                Err(err) => {
+                    warn!("Failed to query drm driver: {}", err);
+                    return;
+                }
+            };
+
+            let mut planes = match drm_device.planes(&crtc) {
+                Ok(planes) => planes,
+                Err(err) => {
+                    warn!("Failed to query crtc planes: {}", err);
+                    return;
+                }
+            };
+
+            // Using an overlay plane on a nvidia card breaks
+            if driver
+                .name()
+                .to_string_lossy()
+                .to_lowercase()
+                .contains("nvidia")
+                || driver
+                    .description()
+                    .to_string_lossy()
+                    .to_lowercase()
+                    .contains("nvidia")
+            {
+                planes.overlay = vec![];
+            }
+
+            let drm_output = match device
+                .drm_output_manager
+                .initialize_output::<_, OutputRenderElements<UdevRenderer<'_>, WindowRenderElement<UdevRenderer<'_>>>>(
+                    crtc,
+                    drm_mode,
+                    &[connector.handle()],
+                    &output,
+                    Some(planes),
+                    &mut renderer,
+                    &DrmOutputRenderElements::default(),
+                ) {
+                Ok(drm_output) => drm_output,
+                Err(err) => {
+                    warn!("Failed to initialize drm output: {}", err);
+                    return;
+                }
+            };
+
+            let disable_direct_scanout = std::env::var("ANVIL_DISABLE_DIRECT_SCANOUT").is_ok();
+
+            let dmabuf_feedback = drm_output.with_compositor(|compositor| {
+                compositor.set_debug_flags(self.backend_data.debug_flags);
+
+                get_surface_dmabuf_feedback(
+                    self.backend_data.primary_gpu,
+                    device.render_node,
+                    node,
+                    &mut self.backend_data.gpus,
+                    compositor.surface(),
+                )
+            });
+
+            let surface = SurfaceData {
+                dh: self.display_handle.clone(),
+                device_id: node,
+                render_node: device.render_node,
+                global: Some(global),
+                drm_output,
+                disable_direct_scanout,
+                #[cfg(feature = "debug")]
+                fps: fps_ticker::Fps::default(),
+                #[cfg(feature = "debug")]
+                fps_element,
+                dmabuf_feedback,
+                last_presentation_time: None,
+                vblank_throttle_timer: None,
+            };
+
+            device.surfaces.insert(crtc, surface);
+
+            // kick-off rendering
+            self.handle.insert_idle(move |state| {
+                state.render_surface(node, crtc, state.clock.now());
+            });
+        }
+    }
+
+    fn connector_disconnected(
+        &mut self,
+        node: DrmNode,
+        connector: connector::Info,
+        crtc: crtc::Handle,
+    ) {
+        let device = if let Some(device) = self.backend_data.backends.get_mut(&node) {
+            device
+        } else {
+            return;
+        };
+
+        if let Some(pos) = device
+            .non_desktop_connectors
+            .iter()
+            .position(|(handle, _)| *handle == connector.handle())
+        {
+            let _ = device.non_desktop_connectors.remove(pos);
+            if let Some(leasing_state) = device.leasing_global.as_mut() {
+                leasing_state.withdraw_connector(connector.handle());
+            }
+        } else {
+            device.surfaces.remove(&crtc);
+
+            let output = self
+                .space
+                .outputs()
+                .find(|o| {
+                    o.user_data()
+                        .get::<UdevOutputId>()
+                        .map(|id| id.device_id == node && id.crtc == crtc)
+                        .unwrap_or(false)
+                })
+                .cloned();
+
+            if let Some(output) = output {
+                self.space.output_destroyed(&output);
+            }
+        }
+
+        let render_node = device.render_node.unwrap_or(self.backend_data.primary_gpu);
+        let mut renderer = self
+            .backend_data
+            .gpus
+            .single_renderer(&render_node)
+            .unwrap();
+        let _ = device.drm_output_manager.try_to_restore_modifiers::<_, OutputRenderElements<
+            UdevRenderer<'_>,
+            WindowRenderElement<UdevRenderer<'_>>,
+        >>(
+            &mut renderer,
+            // FIXME: For a flicker free operation we should return the actual elements for this output..
+            // Instead we just use black to "simulate" a modeset :)
+            &DrmOutputRenderElements::default(),
+        );
+    }
+
+    fn device_changed(&mut self, node: DrmNode) {
+        let device = if let Some(device) = self.backend_data.backends.get_mut(&node) {
+            device
+        } else {
+            return;
+        };
+
+        let scan_result = match device
+            .drm_scanner
+            .scan_connectors(device.drm_output_manager.device())
+        {
+            Ok(scan_result) => scan_result,
+            Err(err) => {
+                tracing::warn!(?err, "Failed to scan connectors");
+                return;
+            }
+        };
+
+        for event in scan_result {
+            match event {
+                DrmScanEvent::Connected {
+                    connector,
+                    crtc: Some(crtc),
+                } => {
+                    self.connector_connected(node, connector, crtc);
+                }
+                DrmScanEvent::Disconnected {
+                    connector,
+                    crtc: Some(crtc),
+                } => {
+                    self.connector_disconnected(node, connector, crtc);
+                }
+                _ => {}
+            }
+        }
+
+        // fixup window coordinates
+        crate::shell::fixup_positions(&mut self.space, self.pointer.current_location());
+    }
+
+    fn device_removed(&mut self, node: DrmNode) {
+        let device = if let Some(device) = self.backend_data.backends.get_mut(&node) {
+            device
+        } else {
+            return;
+        };
+
+        let crtcs: Vec<_> = device
+            .drm_scanner
+            .crtcs()
+            .map(|(info, crtc)| (info.clone(), crtc))
+            .collect();
+
+        for (connector, crtc) in crtcs {
+            self.connector_disconnected(node, connector, crtc);
+        }
+
+        debug!("Surfaces dropped");
+
+        // drop the backends on this side
+        if let Some(mut backend_data) = self.backend_data.backends.remove(&node) {
+            if let Some(mut leasing_global) = backend_data.leasing_global.take() {
+                leasing_global.disable_global::<CompositronState<UdevData>>();
+            }
+
+            if let Some(render_node) = backend_data.render_node {
+                self.backend_data.gpus.as_mut().remove_node(&render_node);
+            }
+
+            self.handle.remove(backend_data.registration_token);
+
+            debug!("Dropping device");
+        }
+
+        crate::shell::fixup_positions(&mut self.space, self.pointer.current_location());
+    }
+
+    fn frame_finish(
+        &mut self,
+        dev_id: DrmNode,
+        crtc: crtc::Handle,
+        metadata: &mut Option<DrmEventMetadata>,
+    ) {
+        profiling::scope!("frame_finish", &format!("{crtc:?}"));
+
+        let device_backend = match self.backend_data.backends.get_mut(&dev_id) {
+            Some(backend) => backend,
+            None => {
+                error!("Trying to finish frame on non-existent backend {}", dev_id);
+                return;
+            }
+        };
+
+        let surface = match device_backend.surfaces.get_mut(&crtc) {
+            Some(surface) => surface,
+            None => {
+                error!("Trying to finish frame on non-existent crtc {:?}", crtc);
+                return;
+            }
+        };
+
+        if let Some(timer_token) = surface.vblank_throttle_timer.take() {
+            self.handle.remove(timer_token);
+        }
+
+        let output = if let Some(output) = self.space.outputs().find(|o| {
+            o.user_data().get::<UdevOutputId>()
+                == Some(&UdevOutputId {
+                    device_id: surface.device_id,
+                    crtc,
+                })
+        }) {
+            output.clone()
+        } else {
+            // somehow we got called with an invalid output
+            return;
+        };
+
+        let Some(frame_duration) = output
+            .current_mode()
+            .map(|mode| Duration::from_secs_f64(1_000f64 / mode.refresh as f64))
+        else {
+            return;
+        };
+
+        let tp = metadata.as_ref().and_then(|metadata| match metadata.time {
+            smithay::backend::drm::DrmEventTime::Monotonic(tp) => tp.is_zero().not().then_some(tp),
+            smithay::backend::drm::DrmEventTime::Realtime(_) => None,
+        });
+
+        let seq = metadata
+            .as_ref()
+            .map(|metadata| metadata.sequence)
+            .unwrap_or(0);
+
+        let (clock, flags) = if let Some(tp) = tp {
+            (
+                tp.into(),
+                wp_presentation_feedback::Kind::Vsync
+                    | wp_presentation_feedback::Kind::HwClock
+                    | wp_presentation_feedback::Kind::HwCompletion,
+            )
+        } else {
+            (self.clock.now(), wp_presentation_feedback::Kind::Vsync)
+        };
+
+        let vblank_remaining_time = surface
+            .last_presentation_time
+            .map(|last_presentation_time| {
+                frame_duration.saturating_sub(Time::elapsed(&last_presentation_time, clock))
+            });
+
+        if let Some(vblank_remaining_time) = vblank_remaining_time {
+            if vblank_remaining_time > frame_duration / 2 {
+                static WARN_ONCE: Once = Once::new();
+                WARN_ONCE.call_once(|| {
+                    warn!("display running faster than expected, throttling vblanks and disabling HwClock")
+                });
+                let throttled_time = tp
+                    .map(|tp| tp.saturating_add(vblank_remaining_time))
+                    .unwrap_or(Duration::ZERO);
+                let throttled_metadata = DrmEventMetadata {
+                    sequence: seq,
+                    time: DrmEventTime::Monotonic(throttled_time),
+                };
+                let timer_token = self
+                    .handle
+                    .insert_source(
+                        Timer::from_duration(vblank_remaining_time),
+                        move |_, _, data| {
+                            data.frame_finish(dev_id, crtc, &mut Some(throttled_metadata));
+                            TimeoutAction::Drop
+                        },
+                    )
+                    .expect("failed to register vblank throttle timer");
+                surface.vblank_throttle_timer = Some(timer_token);
+                return;
+            }
+        }
+        surface.last_presentation_time = Some(clock);
+
+        let submit_result = surface
+            .drm_output
+            .frame_submitted()
+            .map_err(Into::<SwapBuffersError>::into);
+
+        let schedule_render = match submit_result {
+            Ok(user_data) => {
+                if let Some(mut feedback) = user_data.flatten() {
+                    feedback.presented(clock, Refresh::fixed(frame_duration), seq as u64, flags);
+                }
+
+                true
+            }
+            Err(err) => {
+                warn!("Error during rendering: {:?}", err);
+                match err {
+                    SwapBuffersError::AlreadySwapped => true,
+                    // If the device has been deactivated do not reschedule, this will be done
+                    // by session resume
+                    SwapBuffersError::TemporaryFailure(err)
+                        if matches!(
+                            err.downcast_ref::<DrmError>(),
+                            Some(&DrmError::DeviceInactive)
+                        ) =>
+                    {
+                        false
+                    }
+                    SwapBuffersError::TemporaryFailure(err) => matches!(
+                        err.downcast_ref::<DrmError>(),
+                        Some(DrmError::Access(DrmAccessError {
+                            source,
+                            ..
+                        })) if source.kind() == io::ErrorKind::PermissionDenied
+                    ),
+                    SwapBuffersError::ContextLost(err) => panic!("Rendering loop lost: {}", err),
+                }
+            }
+        };
+
+        if schedule_render {
+            let next_frame_target = clock + frame_duration;
+
+            // What are we trying to solve by introducing a delay here:
+            //
+            // Basically it is all about latency of client provided buffers.
+            // A client driven by frame callbacks will wait for a frame callback
+            // to repaint and submit a new buffer. As we send frame callbacks
+            // as part of the repaint in the compositor the latency would always
+            // be approx. 2 frames. By introducing a delay before we repaint in
+            // the compositor we can reduce the latency to approx. 1 frame + the
+            // remaining duration from the repaint to the next VBlank.
+            //
+            // With the delay it is also possible to further reduce latency if
+            // the client is driven by presentation feedback. As the presentation
+            // feedback is directly sent after a VBlank the client can submit a
+            // new buffer during the repaint delay that can hit the very next
+            // VBlank, thus reducing the potential latency to below one frame.
+            //
+            // Choosing a good delay is a topic on its own so we just implement
+            // a simple strategy here. We just split the duration between two
+            // VBlanks into two steps, one for the client repaint and one for the
+            // compositor repaint. Theoretically the repaint in the compositor should
+            // be faster so we give the client a bit more time to repaint. On a typical
+            // modern system the repaint in the compositor should not take more than 2ms
+            // so this should be safe for refresh rates up to at least 120 Hz. For 120 Hz
+            // this results in approx. 3.33ms time for repainting in the compositor.
+            // A too big delay could result in missing the next VBlank in the compositor.
+            //
+            // A more complete solution could work on a sliding window analyzing past repaints
+            // and do some prediction for the next repaint.
+            let repaint_delay = Duration::from_secs_f64(frame_duration.as_secs_f64() * 0.6f64);
+
+            let timer = if surface
+                .render_node
+                .map(|render_node| render_node != self.backend_data.primary_gpu)
+                .unwrap_or(true)
+            {
+                // However, if we need to do a copy, that might not be enough.
+                // (And without actual comparision to previous frames we cannot really know.)
+                // So lets ignore that in those cases to avoid thrashing performance.
+                trace!("scheduling repaint timer immediately on {:?}", crtc);
+                Timer::immediate()
+            } else {
+                trace!(
+                    "scheduling repaint timer with delay {:?} on {:?}",
+                    repaint_delay,
+                    crtc
+                );
+                Timer::from_duration(repaint_delay)
+            };
+
+            self.handle
+                .insert_source(timer, move |_, _, data| {
+                    data.render(dev_id, Some(crtc), next_frame_target);
+                    TimeoutAction::Drop
+                })
+                .expect("failed to schedule frame timer");
+        }
+    }
+
+    // If crtc is `Some()`, render it, else render all crtcs
+    fn render(&mut self, node: DrmNode, crtc: Option<crtc::Handle>, frame_target: Time<Monotonic>) {
+        let device_backend = match self.backend_data.backends.get_mut(&node) {
+            Some(backend) => backend,
+            None => {
+                error!("Trying to render on non-existent backend {}", node);
+                return;
+            }
+        };
+
+        if let Some(crtc) = crtc {
+            self.render_surface(node, crtc, frame_target);
+        } else {
+            let crtcs: Vec<_> = device_backend.surfaces.keys().copied().collect();
+            for crtc in crtcs {
+                self.render_surface(node, crtc, frame_target);
+            }
+        };
+    }
+
+    fn render_surface(&mut self, node: DrmNode, crtc: crtc::Handle, frame_target: Time<Monotonic>) {
+        profiling::scope!("render_surface", &format!("{crtc:?}"));
+
+        let output = if let Some(output) = self.space.outputs().find(|o| {
+            o.user_data().get::<UdevOutputId>()
+                == Some(&UdevOutputId {
+                    device_id: node,
+                    crtc,
+                })
+        }) {
+            output.clone()
+        } else {
+            // somehow we got called with an invalid output
+            return;
+        };
+
+        self.pre_repaint(&output, frame_target);
+
+        let device = if let Some(device) = self.backend_data.backends.get_mut(&node) {
+            device
+        } else {
+            return;
+        };
+
+        let surface = if let Some(surface) = device.surfaces.get_mut(&crtc) {
+            surface
+        } else {
+            return;
+        };
+
+        let start = Instant::now();
+
+        // Choose cursor images based on the actual output scale.
+        let cursor_scale = output.current_scale().integer_scale().max(1) as u32;
+        let frame = self
+            .backend_data
+            .pointer_image
+            .get_image(cursor_scale, self.clock.now().into());
+
+        let primary_gpu = self.backend_data.primary_gpu;
+        let render_node = surface.render_node.unwrap_or(primary_gpu);
+        let mut renderer = if primary_gpu == render_node {
+            self.backend_data.gpus.single_renderer(&render_node)
+        } else {
+            let format = surface.drm_output.format();
+            self.backend_data
+                .gpus
+                .renderer(&primary_gpu, &render_node, format)
+        }
+        .unwrap();
+
+        let pointer_images = &mut self.backend_data.pointer_images;
+        let pointer_image = pointer_images
+            .iter()
+            .find_map(|(image, texture)| {
+                if image == &frame {
+                    Some(texture.clone())
+                } else {
+                    None
+                }
+            })
+            .unwrap_or_else(|| {
+                let buffer = MemoryRenderBuffer::from_slice(
+                    &frame.pixels_rgba,
+                    Fourcc::Argb8888,
+                    (frame.width as i32, frame.height as i32),
+                    1,
+                    Transform::Normal,
+                    None,
+                );
+                pointer_images.push((frame, buffer.clone()));
+                buffer
+            });
+
+        self.overview.set_workspace_info(
+            self.space.active(),
+            std::array::from_fn(|index| self.space.window_count(index)),
+        );
+
+        let result = render_surface(
+            surface,
+            &mut renderer,
+            &self.space,
+            &output,
+            self.pointer.current_location(),
+            &pointer_image,
+            &mut self.backend_data.pointer_element,
+            &self.dnd_icon,
+            &mut self.cursor_status,
+            &mut self.overview,
+            self.show_window_preview,
+        );
+        let reschedule = match result {
+            Ok((has_rendered, states)) => {
+                let dmabuf_feedback = surface.dmabuf_feedback.clone();
+                self.post_repaint(&output, frame_target, dmabuf_feedback, &states);
+                !has_rendered
+            }
+            Err(err) => {
+                warn!("Error during rendering: {:#?}", err);
+                match err {
+                    SwapBuffersError::AlreadySwapped => false,
+                    SwapBuffersError::TemporaryFailure(err) => match err.downcast_ref::<DrmError>()
+                    {
+                        Some(DrmError::DeviceInactive) => true,
+                        Some(DrmError::Access(DrmAccessError { source, .. })) => {
+                            source.kind() == io::ErrorKind::PermissionDenied
+                        }
+                        _ => false,
+                    },
+                    SwapBuffersError::ContextLost(err) => match err.downcast_ref::<DrmError>() {
+                        Some(DrmError::TestFailed(_)) => {
+                            // reset the complete state, disabling all connectors and planes in case we hit a test failed
+                            // most likely we hit this after a tty switch when a foreign master changed CRTC <-> connector bindings
+                            // and we run in a mismatch
+                            device
+                                .drm_output_manager
+                                .device_mut()
+                                .reset_state()
+                                .expect("failed to reset drm device");
+                            true
+                        }
+                        _ => panic!("Rendering loop lost: {}", err),
+                    },
+                }
+            }
+        };
+
+        if reschedule {
+            let output_refresh = match output.current_mode() {
+                Some(mode) => mode.refresh,
+                None => return,
+            };
+
+            // If reschedule is true we either hit a temporary failure or more likely rendering
+            // did not cause any damage on the output. In this case we just re-schedule a repaint
+            // after approx. one frame to re-test for damage.
+            let next_frame_target =
+                frame_target + Duration::from_millis(1_000_000 / output_refresh as u64);
+            let reschedule_timeout =
+                Duration::from(next_frame_target).saturating_sub(self.clock.now().into());
+            trace!(
+                "reschedule repaint timer with delay {:?} on {:?}",
+                reschedule_timeout,
+                crtc,
+            );
+            let timer = Timer::from_duration(reschedule_timeout);
+            self.handle
+                .insert_source(timer, move |_, _, data| {
+                    data.render(node, Some(crtc), next_frame_target);
+                    TimeoutAction::Drop
+                })
+                .expect("failed to schedule frame timer");
+        } else {
+            let elapsed = start.elapsed();
+            tracing::trace!(?elapsed, "rendered surface");
+        }
+
+        profiling::finish_frame!();
+    }
+}
+
+#[allow(clippy::too_many_arguments)]
+#[profiling::function]
+fn render_surface<'a>(
+    surface: &'a mut SurfaceData,
+    renderer: &mut UdevRenderer<'a>,
+    space: &Space<WindowElement>,
+    output: &Output,
+    pointer_location: Point<f64, Logical>,
+    pointer_image: &MemoryRenderBuffer,
+    pointer_element: &mut PointerElement,
+    dnd_icon: &Option<DndIcon>,
+    cursor_status: &mut CursorImageStatus,
+    overview: &mut crate::overview::Overview,
+    show_window_preview: bool,
+) -> Result<(bool, RenderElementStates), SwapBuffersError> {
+    let output_geometry = space.output_geometry(output).unwrap();
+    let scale = Scale::from(output.current_scale().fractional_scale());
+
+    let mut custom_elements: Vec<CustomRenderElements<_>> = Vec::new();
+
+    if output_geometry.to_f64().contains(pointer_location) {
+        let cursor_hotspot = if let CursorImageStatus::Surface(ref surface) = cursor_status {
+            compositor::with_states(surface, |states| {
+                states
+                    .data_map
+                    .get::<Mutex<CursorImageAttributes>>()
+                    .unwrap()
+                    .lock()
+                    .unwrap()
+                    .hotspot
+            })
+        } else {
+            (0, 0).into()
+        };
+        let cursor_pos = pointer_location - output_geometry.loc.to_f64();
+
+        // set cursor
+        pointer_element.set_buffer(pointer_image.clone());
+
+        // draw the cursor as relevant
+        {
+            // reset the cursor if the surface is no longer alive
+            let mut reset = false;
+            if let CursorImageStatus::Surface(ref surface) = *cursor_status {
+                reset = !surface.alive();
+            }
+            if reset {
+                *cursor_status = CursorImageStatus::default_named();
+            }
+
+            pointer_element.set_status(cursor_status.clone());
+        }
+
+        custom_elements.extend(
+            pointer_element.render_elements(
+                renderer,
+                (cursor_pos - cursor_hotspot.to_f64())
+                    .to_physical(scale)
+                    .to_i32_round(),
+                scale,
+                1.0,
+            ),
+        );
+
+        // draw the dnd icon if applicable
+        {
+            if let Some(icon) = dnd_icon.as_ref() {
+                let dnd_icon_pos = (cursor_pos + icon.offset.to_f64())
+                    .to_physical(scale)
+                    .to_i32_round();
+                if icon.surface.alive() {
+                    custom_elements.extend(AsRenderElements::<UdevRenderer<'a>>::render_elements(
+                        &SurfaceTree::from_surface(&icon.surface),
+                        renderer,
+                        dnd_icon_pos,
+                        scale,
+                        1.0,
+                    ));
+                }
+            }
+        }
+    }
+
+    #[cfg(feature = "debug")]
+    if let Some(element) = surface.fps_element.as_mut() {
+        element.update_fps(surface.fps.avg().round() as u32);
+        surface.fps.tick();
+        custom_elements.push(CustomRenderElements::Fps(element.clone()));
+    }
+
+    if let Some(element) = overview.render_element(
+        renderer,
+        output,
+        output_geometry
+            .loc
+            .to_f64()
+            .to_physical(scale)
+            .to_i32_round(),
+    ) {
+        custom_elements.push(CustomRenderElements::Overview(element));
+    }
+
+    let (elements, clear_color) = output_elements(
+        output,
+        space,
+        custom_elements,
+        renderer,
+        show_window_preview,
+    );
+
+    let frame_mode = if surface.disable_direct_scanout {
+        FrameFlags::empty()
+    } else {
+        FrameFlags::DEFAULT
+    };
+    let (rendered, states) = surface
+        .drm_output
+        .render_frame(renderer, &elements, clear_color, frame_mode)
+        .map(|render_frame_result| {
+            #[cfg(feature = "renderer_sync")]
+            if let PrimaryPlaneElement::Swapchain(element) = render_frame_result.primary_element {
+                element.sync.wait();
+            }
+            (!render_frame_result.is_empty, render_frame_result.states)
+        })
+        .map_err(|err| match err {
+            smithay::backend::drm::compositor::RenderFrameError::PrepareFrame(err) => {
+                SwapBuffersError::from(err)
+            }
+            smithay::backend::drm::compositor::RenderFrameError::RenderFrame(
+                OutputDamageTrackerError::Rendering(err),
+            ) => SwapBuffersError::from(err),
+            _ => unreachable!(),
+        })?;
+
+    update_primary_scanout_output(space, output, dnd_icon, cursor_status, &states);
+
+    if rendered {
+        let output_presentation_feedback = take_presentation_feedback(output, space, &states);
+        surface
+            .drm_output
+            .queue_frame(Some(output_presentation_feedback))
+            .map_err(Into::<SwapBuffersError>::into)?;
+    }
+
+    Ok((rendered, states))
+}

+ 513 - 0
src/winit.rs

@@ -0,0 +1,513 @@
+use std::{
+    sync::{atomic::Ordering, Mutex},
+    time::Duration,
+};
+
+#[cfg(feature = "egl")]
+use smithay::backend::renderer::ImportEgl;
+#[cfg(feature = "debug")]
+use smithay::{
+    backend::{allocator::Fourcc, renderer::ImportMem},
+    reexports::winit::raw_window_handle::{HasWindowHandle, RawWindowHandle},
+};
+
+use smithay::{
+    backend::{
+        allocator::dmabuf::Dmabuf,
+        egl::EGLDevice,
+        renderer::{
+            damage::{Error as OutputDamageTrackerError, OutputDamageTracker},
+            element::AsRenderElements,
+            gles::GlesRenderer,
+            ImportDma, ImportMemWl,
+        },
+        winit::{self, WinitEvent, WinitGraphicsBackend},
+        SwapBuffersError,
+    },
+    delegate_dmabuf,
+    input::{
+        keyboard::LedState,
+        pointer::{CursorImageAttributes, CursorImageStatus},
+    },
+    output::{Mode, Output, PhysicalProperties, Scale as OutputScale, Subpixel},
+    reexports::{
+        calloop::EventLoop,
+        wayland_protocols::wp::presentation_time::server::wp_presentation_feedback,
+        wayland_server::{protocol::wl_surface, Display},
+        winit::platform::pump_events::PumpStatus,
+    },
+    utils::{IsAlive, Scale, Transform},
+    wayland::{
+        compositor,
+        dmabuf::{
+            DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal, DmabufHandler, DmabufState,
+            ImportNotifier,
+        },
+        presentation::Refresh,
+    },
+};
+use tracing::{error, info, warn};
+
+use crate::state::{take_presentation_feedback, Backend, CompositronState};
+use crate::{drawing::*, render::*};
+
+pub const OUTPUT_NAME: &str = "winit";
+
+pub struct WinitData {
+    backend: WinitGraphicsBackend<GlesRenderer>,
+    damage_tracker: OutputDamageTracker,
+    dmabuf_state: (DmabufState, DmabufGlobal, Option<DmabufFeedback>),
+    full_redraw: u8,
+    #[cfg(feature = "debug")]
+    pub fps: fps_ticker::Fps,
+}
+
+impl DmabufHandler for CompositronState<WinitData> {
+    fn dmabuf_state(&mut self) -> &mut DmabufState {
+        &mut self.backend_data.dmabuf_state.0
+    }
+
+    fn dmabuf_imported(
+        &mut self,
+        _global: &DmabufGlobal,
+        dmabuf: Dmabuf,
+        notifier: ImportNotifier,
+    ) {
+        if self
+            .backend_data
+            .backend
+            .renderer()
+            .import_dmabuf(&dmabuf, None)
+            .is_ok()
+        {
+            let _ = notifier.successful::<CompositronState<WinitData>>();
+        } else {
+            notifier.failed();
+        }
+    }
+}
+delegate_dmabuf!(CompositronState<WinitData>);
+
+impl Backend for WinitData {
+    fn seat_name(&self) -> String {
+        String::from("winit")
+    }
+    fn reset_buffers(&mut self, _output: &Output) {
+        self.full_redraw = 4;
+    }
+    fn early_import(&mut self, _surface: &wl_surface::WlSurface) {}
+    fn update_led_state(&mut self, _led_state: LedState) {}
+}
+
+pub fn run_winit() {
+    let mut event_loop = EventLoop::try_new().unwrap();
+    let display = Display::new().unwrap();
+    let mut display_handle = display.handle();
+
+    #[cfg_attr(not(feature = "egl"), allow(unused_mut))]
+    let (mut backend, mut winit) = match winit::init::<GlesRenderer>() {
+        Ok(ret) => ret,
+        Err(err) => {
+            error!("Failed to initialize Winit backend: {}", err);
+            return;
+        }
+    };
+    let size = backend.window_size();
+    let scale_factor = backend.scale_factor();
+    backend.window().set_title("Compositron");
+
+    let mode = Mode {
+        size,
+        refresh: 60_000,
+    };
+    let output = Output::new(
+        OUTPUT_NAME.to_string(),
+        PhysicalProperties {
+            size: (0, 0).into(),
+            subpixel: Subpixel::Unknown,
+            make: "Smithay".into(),
+            model: "Winit".into(),
+        },
+    );
+    let _global = output.create_global::<CompositronState<WinitData>>(&display.handle());
+    output.change_current_state(
+        Some(mode),
+        Some(Transform::Flipped180),
+        Some(OutputScale::Fractional(scale_factor)),
+        Some((0, 0).into()),
+    );
+    output.set_preferred(mode);
+
+    #[cfg(feature = "debug")]
+    #[allow(deprecated)]
+    let fps_image = image::io::Reader::with_format(
+        std::io::Cursor::new(FPS_NUMBERS_PNG),
+        image::ImageFormat::Png,
+    )
+    .decode()
+    .unwrap();
+    #[cfg(feature = "debug")]
+    let fps_texture = backend
+        .renderer()
+        .import_memory(
+            &fps_image.to_rgba8(),
+            Fourcc::Abgr8888,
+            (fps_image.width() as i32, fps_image.height() as i32).into(),
+            false,
+        )
+        .expect("Unable to upload FPS texture");
+    #[cfg(feature = "debug")]
+    let mut fps_element = FpsElement::new(fps_texture);
+
+    let render_node = EGLDevice::device_for_display(backend.renderer().egl_context().display())
+        .and_then(|device| device.try_get_render_node());
+
+    let dmabuf_default_feedback = match render_node {
+        Ok(Some(node)) => {
+            let dmabuf_formats = backend.renderer().dmabuf_formats();
+            let dmabuf_default_feedback = DmabufFeedbackBuilder::new(node.dev_id(), dmabuf_formats)
+                .build()
+                .unwrap();
+            Some(dmabuf_default_feedback)
+        }
+        Ok(None) => {
+            warn!("failed to query render node, dmabuf will use v3");
+            None
+        }
+        Err(err) => {
+            warn!(?err, "failed to egl device for display, dmabuf will use v3");
+            None
+        }
+    };
+
+    // if we failed to build dmabuf feedback we fall back to dmabuf v3
+    // Note: egl on Mesa requires either v4 or wl_drm (initialized with bind_wl_display)
+    let dmabuf_state = if let Some(default_feedback) = dmabuf_default_feedback {
+        let mut dmabuf_state = DmabufState::new();
+        let dmabuf_global = dmabuf_state
+            .create_global_with_default_feedback::<CompositronState<WinitData>>(
+                &display.handle(),
+                &default_feedback,
+            );
+        (dmabuf_state, dmabuf_global, Some(default_feedback))
+    } else {
+        let dmabuf_formats = backend.renderer().dmabuf_formats();
+        let mut dmabuf_state = DmabufState::new();
+        let dmabuf_global = dmabuf_state
+            .create_global::<CompositronState<WinitData>>(&display.handle(), dmabuf_formats);
+        (dmabuf_state, dmabuf_global, None)
+    };
+
+    #[cfg(feature = "egl")]
+    if backend
+        .renderer()
+        .bind_wl_display(&display.handle())
+        .is_ok()
+    {
+        info!("EGL hardware-acceleration enabled");
+    };
+
+    let data = {
+        let damage_tracker = OutputDamageTracker::from_output(&output);
+
+        WinitData {
+            backend,
+            damage_tracker,
+            dmabuf_state,
+            full_redraw: 30,
+            #[cfg(feature = "debug")]
+            fps: fps_ticker::Fps::default(),
+        }
+    };
+    let mut state = CompositronState::init(display, event_loop.handle(), data, true);
+    state
+        .shm_state
+        .update_formats(state.backend_data.backend.renderer().shm_formats());
+    state.space.map_output(&output, (0, 0));
+    let _ = state.backend_data.backend.window().request_inner_size(
+        smithay::reexports::winit::dpi::LogicalSize::new(1400.0, 900.0),
+    );
+    state.backend_data.backend.window().request_redraw();
+
+    // A nested compositor cannot receive GNOME's Super shortcuts. Start with
+    // the launcher visible so the window has useful content immediately.
+    state.open_overview();
+    state.backend_data.backend.window().request_redraw();
+
+    #[cfg(feature = "xwayland")]
+    state.start_xwayland();
+
+    info!("Initialization completed, starting the main loop.");
+
+    let mut pointer_element = PointerElement::default();
+
+    while state.running.load(Ordering::SeqCst) {
+        let status = winit.dispatch_new_events(|event| match event {
+            WinitEvent::Resized { size, scale_factor } => {
+                // We only have one output
+                let output = state.space.outputs().next().unwrap().clone();
+                let mode = Mode {
+                    size,
+                    refresh: 60_000,
+                };
+                output.change_current_state(
+                    Some(mode),
+                    None,
+                    Some(OutputScale::Fractional(scale_factor)),
+                    None,
+                );
+                output.set_preferred(mode);
+                state.space.map_output(&output, (0, 0));
+                crate::shell::fixup_positions(&mut state.space, state.pointer.current_location());
+                state.backend_data.reset_buffers(&output);
+            }
+            WinitEvent::Input(event) => state.process_input_event_windowed(event, OUTPUT_NAME),
+            _ => (),
+        });
+
+        if let PumpStatus::Exit(_) = status {
+            state.running.store(false, Ordering::SeqCst);
+            break;
+        }
+
+        // drawing logic
+        {
+            let now = state.clock.now();
+            let frame_target = now
+                + output
+                    .current_mode()
+                    .map(|mode| Duration::from_secs_f64(1_000f64 / mode.refresh as f64))
+                    .unwrap_or_default();
+            state.pre_repaint(&output, frame_target);
+
+            let backend = &mut state.backend_data.backend;
+
+            // draw the cursor as relevant
+            // reset the cursor if the surface is no longer alive
+            let mut reset = false;
+            if let CursorImageStatus::Surface(ref surface) = state.cursor_status {
+                reset = !surface.alive();
+            }
+            if reset {
+                state.cursor_status = CursorImageStatus::default_named();
+            }
+            let cursor_visible = !matches!(state.cursor_status, CursorImageStatus::Surface(_));
+
+            pointer_element.set_status(state.cursor_status.clone());
+
+            #[cfg(feature = "debug")]
+            let fps = state.backend_data.fps.avg().round() as u32;
+            #[cfg(feature = "debug")]
+            fps_element.update_fps(fps);
+
+            let full_redraw = &mut state.backend_data.full_redraw;
+            *full_redraw = full_redraw.saturating_sub(1);
+            let space = &mut state.space;
+            let damage_tracker = &mut state.backend_data.damage_tracker;
+            let show_window_preview = state.show_window_preview;
+
+            let dnd_icon = state.dnd_icon.as_ref();
+
+            let scale = Scale::from(output.current_scale().fractional_scale());
+            let overview_location = space
+                .output_geometry(&output)
+                .map(|geometry| geometry.loc.to_f64().to_physical(scale).to_i32_round())
+                .unwrap_or_default();
+            state.overview.set_workspace_info(
+                space.active(),
+                std::array::from_fn(|index| space.window_count(index)),
+            );
+            let cursor_hotspot =
+                if let CursorImageStatus::Surface(ref surface) = state.cursor_status {
+                    compositor::with_states(surface, |states| {
+                        states
+                            .data_map
+                            .get::<Mutex<CursorImageAttributes>>()
+                            .unwrap()
+                            .lock()
+                            .unwrap()
+                            .hotspot
+                    })
+                } else {
+                    (0, 0).into()
+                };
+            let cursor_pos = state.pointer.current_location();
+
+            #[cfg(feature = "debug")]
+            let mut renderdoc = state.renderdoc.as_mut();
+
+            let age = if *full_redraw > 0 {
+                0
+            } else {
+                backend.buffer_age().unwrap_or(0)
+            };
+            #[cfg(feature = "debug")]
+            let window_handle = backend
+                .window()
+                .window_handle()
+                .map(|handle| {
+                    if let RawWindowHandle::Wayland(handle) = handle.as_raw() {
+                        handle.surface.as_ptr()
+                    } else {
+                        std::ptr::null_mut()
+                    }
+                })
+                .unwrap_or_else(|_| std::ptr::null_mut());
+            let render_res = backend.bind().and_then(|(renderer, mut fb)| {
+                #[cfg(feature = "debug")]
+                if let Some(renderdoc) = renderdoc.as_mut() {
+                    renderdoc.start_frame_capture(
+                        renderer.egl_context().get_context_handle(),
+                        window_handle,
+                    );
+                }
+
+                let mut elements = Vec::<CustomRenderElements<GlesRenderer>>::new();
+
+                elements.extend(
+                    pointer_element.render_elements(
+                        renderer,
+                        (cursor_pos - cursor_hotspot.to_f64())
+                            .to_physical(scale)
+                            .to_i32_round(),
+                        scale,
+                        1.0,
+                    ),
+                );
+
+                // draw the dnd icon if any
+                if let Some(icon) = dnd_icon {
+                    let dnd_icon_pos = (cursor_pos + icon.offset.to_f64())
+                        .to_physical(scale)
+                        .to_i32_round();
+                    if icon.surface.alive() {
+                        elements.extend(AsRenderElements::<GlesRenderer>::render_elements(
+                            &smithay::desktop::space::SurfaceTree::from_surface(&icon.surface),
+                            renderer,
+                            dnd_icon_pos,
+                            scale,
+                            1.0,
+                        ));
+                    }
+                }
+
+                #[cfg(feature = "debug")]
+                elements.push(CustomRenderElements::Fps(fps_element.clone()));
+
+                if let Some(element) =
+                    state
+                        .overview
+                        .render_element(renderer, &output, overview_location)
+                {
+                    elements.push(CustomRenderElements::Overview(element));
+                }
+
+                let res = render_output(
+                    &output,
+                    space,
+                    elements,
+                    renderer,
+                    &mut fb,
+                    damage_tracker,
+                    age,
+                    show_window_preview,
+                )
+                .map_err(|err| match err {
+                    OutputDamageTrackerError::Rendering(err) => err.into(),
+                    _ => unreachable!(),
+                });
+
+                res
+            });
+
+            match render_res {
+                Ok(render_output_result) => {
+                    let has_rendered = render_output_result.damage.is_some();
+                    if let Some(damage) = render_output_result.damage {
+                        if let Err(err) = backend.submit(Some(damage)) {
+                            warn!("Failed to submit buffer: {}", err);
+                        }
+                    }
+
+                    #[cfg(feature = "debug")]
+                    if let Some(renderdoc) = renderdoc.as_mut() {
+                        renderdoc.end_frame_capture(
+                            backend.renderer().egl_context().get_context_handle(),
+                            backend
+                                .window()
+                                .window_handle()
+                                .map(|handle| {
+                                    if let RawWindowHandle::Wayland(handle) = handle.as_raw() {
+                                        handle.surface.as_ptr()
+                                    } else {
+                                        std::ptr::null_mut()
+                                    }
+                                })
+                                .unwrap_or_else(|_| std::ptr::null_mut()),
+                        );
+                    }
+
+                    backend.window().set_cursor_visible(cursor_visible);
+
+                    let states = render_output_result.states;
+                    if has_rendered {
+                        let mut output_presentation_feedback =
+                            take_presentation_feedback(&output, &state.space, &states);
+                        output_presentation_feedback.presented(
+                            frame_target,
+                            output
+                                .current_mode()
+                                .map(|mode| {
+                                    Refresh::fixed(Duration::from_secs_f64(
+                                        1_000f64 / mode.refresh as f64,
+                                    ))
+                                })
+                                .unwrap_or(Refresh::Unknown),
+                            0,
+                            wp_presentation_feedback::Kind::Vsync,
+                        )
+                    }
+
+                    // Send frame events so that client start drawing their next frame
+                    state.post_repaint(&output, frame_target, None, &states);
+                }
+                Err(SwapBuffersError::ContextLost(err)) => {
+                    #[cfg(feature = "debug")]
+                    if let Some(renderdoc) = renderdoc.as_mut() {
+                        renderdoc.discard_frame_capture(
+                            backend.renderer().egl_context().get_context_handle(),
+                            backend
+                                .window()
+                                .window_handle()
+                                .map(|handle| {
+                                    if let RawWindowHandle::Wayland(handle) = handle.as_raw() {
+                                        handle.surface.as_ptr()
+                                    } else {
+                                        std::ptr::null_mut()
+                                    }
+                                })
+                                .unwrap_or_else(|_| std::ptr::null_mut()),
+                        );
+                    }
+
+                    error!("Critical Rendering Error: {}", err);
+                    state.running.store(false, Ordering::SeqCst);
+                }
+                Err(err) => warn!("Rendering error: {}", err),
+            }
+        }
+
+        let result = event_loop.dispatch(Some(Duration::from_millis(1)), &mut state);
+        if result.is_err() {
+            state.running.store(false, Ordering::SeqCst);
+        } else {
+            state.space.refresh();
+            state.ensure_focus_valid();
+            state.popups.cleanup();
+            display_handle.flush_clients().unwrap();
+        }
+
+        #[cfg(feature = "debug")]
+        state.backend_data.fps.tick();
+    }
+}

+ 198 - 0
src/workspaces.rs

@@ -0,0 +1,198 @@
+//! Six fixed virtual desktop workspaces.
+//!
+//! Each workspace owns its own [`Space`]. Only the active workspace has the
+//! output mapped; switching transfers the output mapping. This keeps windows
+//! on inactive workspaces alive while making sure only the active workspace
+//! participates in rendering, input focus and output enter/leave events.
+
+use std::ops::{Deref, DerefMut};
+
+use smithay::{
+    desktop::Space,
+    output::Output,
+    utils::{IsAlive, Logical, Point},
+};
+
+use crate::shell::{FullscreenSurface, WindowElement};
+
+pub const WORKSPACE_COUNT: usize = 6;
+
+#[derive(Debug)]
+pub struct Workspaces {
+    spaces: Vec<Space<WindowElement>>,
+    active: usize,
+    last_focus: Vec<Option<WindowElement>>,
+    fullscreen: Vec<Option<WindowElement>>,
+}
+
+impl Workspaces {
+    pub fn new() -> Self {
+        Self {
+            spaces: (0..WORKSPACE_COUNT).map(|_| Space::default()).collect(),
+            active: 0,
+            last_focus: vec![None; WORKSPACE_COUNT],
+            fullscreen: vec![None; WORKSPACE_COUNT],
+        }
+    }
+
+    pub fn active(&self) -> usize {
+        self.active
+    }
+
+    pub fn count(&self) -> usize {
+        WORKSPACE_COUNT
+    }
+
+    pub fn window_count(&self, index: usize) -> usize {
+        self.spaces
+            .get(index)
+            .map(|space| space.elements().count())
+            .unwrap_or(0)
+    }
+
+    /// Save the output's fullscreen surface into the active workspace.
+    ///
+    /// Called before hiding a workspace. The output-level fullscreen marker is
+    /// the one consumed by the render and focus paths.
+    pub fn save_fullscreen(&mut self, output: &Output) {
+        if let Some(current) = output.user_data().get::<FullscreenSurface>() {
+            if let Some(window) = current.clear() {
+                self.fullscreen[self.active] = Some(window);
+            }
+        }
+    }
+
+    fn restore_fullscreen(&mut self, output: &Output) {
+        let saved = self.fullscreen[self.active]
+            .as_ref()
+            .filter(|window| window.alive())
+            .cloned();
+        output
+            .user_data()
+            .insert_if_missing(FullscreenSurface::default);
+        if let Some(window) = saved {
+            if let Some(fullscreen) = output.user_data().get::<FullscreenSurface>() {
+                fullscreen.set(window);
+            }
+        }
+    }
+
+    /// Switch to a workspace, transferring the output mapping.
+    ///
+    /// Returns true when the active workspace changed.
+    pub fn switch_to(&mut self, target: usize, output: &Output) -> bool {
+        if target >= self.spaces.len() || target == self.active {
+            return false;
+        }
+
+        let location = self.spaces[self.active]
+            .output_geometry(output)
+            .map(|geometry| geometry.loc)
+            .unwrap_or_else(|| Point::<i32, Logical>::from((0, 0)));
+
+        self.save_fullscreen(output);
+        self.spaces[self.active].unmap_output(output);
+        self.spaces[self.active].refresh();
+
+        self.active = target;
+        self.spaces[self.active].map_output(output, location);
+        self.spaces[self.active].refresh();
+        self.restore_fullscreen(output);
+        true
+    }
+
+    pub fn cycle(&mut self, delta: isize, output: &Output) -> bool {
+        let target = (self.active as isize + delta).rem_euclid(WORKSPACE_COUNT as isize) as usize;
+        self.switch_to(target, output)
+    }
+
+    pub fn note_focus(&mut self, window: Option<WindowElement>) {
+        if let Some(window) = window {
+            self.last_focus[self.active] = Some(window);
+        }
+    }
+
+    pub fn focus_candidate(&self) -> Option<WindowElement> {
+        self.last_focus[self.active]
+            .as_ref()
+            .filter(|window| window.alive())
+            .cloned()
+            .or_else(|| self.spaces[self.active].elements().next_back().cloned())
+    }
+
+    /// Move a window to another workspace without changing the active one.
+    pub fn move_window(&mut self, window: &WindowElement, target: usize) -> bool {
+        if target >= self.spaces.len() || target == self.active {
+            return false;
+        }
+        let Some(location) = self.spaces[self.active].element_location(window) else {
+            return false;
+        };
+
+        // Moving the focused window between workspaces changes the fullscreen
+        // ownership too; leaving fullscreen avoids rendering it over the target
+        // workspace without a valid output state.
+        if self.fullscreen[self.active]
+            .as_ref()
+            .map(|fullscreen| fullscreen == window)
+            .unwrap_or(false)
+        {
+            self.fullscreen[self.active] = None;
+        }
+
+        self.spaces[self.active].unmap_elem(window);
+        self.spaces[target].map_element(window.clone(), location, false);
+        self.spaces[target].refresh();
+
+        if self.last_focus[self.active]
+            .as_ref()
+            .map(|focused| focused == window)
+            .unwrap_or(false)
+        {
+            self.last_focus[self.active] = None;
+        }
+        true
+    }
+
+    /// Remove a window from whichever workspace it lives on.
+    pub fn forget_window(&mut self, window: &WindowElement) {
+        for space in &mut self.spaces {
+            space.unmap_elem(window);
+        }
+        for fullscreen in &mut self.fullscreen {
+            if fullscreen.as_ref() == Some(window) {
+                *fullscreen = None;
+            }
+        }
+    }
+
+    pub fn output_destroyed(&mut self, output: &Output) {
+        for space in &mut self.spaces {
+            space.unmap_output(output);
+            space.refresh();
+        }
+        self.fullscreen
+            .iter_mut()
+            .for_each(|fullscreen| *fullscreen = None);
+    }
+}
+
+impl Default for Workspaces {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl Deref for Workspaces {
+    type Target = Space<WindowElement>;
+
+    fn deref(&self) -> &Self::Target {
+        &self.spaces[self.active]
+    }
+}
+
+impl DerefMut for Workspaces {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.spaces[self.active]
+    }
+}