diff --git a/Cargo.toml b/Cargo.toml index 294fddf77f..acaec13fda 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,9 @@ members = [ "examples/wgpu_texture", "examples/wasm_hello", ] -exclude = ["sites"] +# The winit backends dioxus-native pins, patched (patches/*/PATCH.md): taken +# by consumers through [patch.crates-io], not built here. +exclude = ["sites", "patches", "examples/ios-a11y"] resolver = "2" [workspace.package] diff --git a/FORK.md b/FORK.md index f09e13ad02..5c192d244a 100644 --- a/FORK.md +++ b/FORK.md @@ -7,7 +7,8 @@ carries what we need now. ## Branches -- **`leaf`**: the branch we build against. It starts at the release tag +- **`leaf`**: the branch every org app builds its Blitz stack from, leaf's + and others' (the name is where it began). It starts at the release tag dioxus-native pins exactly (`v0.3.0-beta.4` for dioxus-native 0.8.0-alpha.3), so its crates keep that version and can replace the published ones through `[patch.crates-io]`; our changes are commits on top. @@ -24,6 +25,9 @@ blitz-paint = { git = "https://github.com/diaryx-org/blitz", branch = "leaf" } stylo_taffy = { git = "https://github.com/diaryx-org/blitz", branch = "leaf" } debug_timer = { git = "https://github.com/diaryx-org/blitz", branch = "leaf" } # and blitz-net, blitz-html, accesskit_xplat where the graph has them +# The winit backends, patched (patches/*/PATCH.md), for the platforms built: +winit-appkit = { git = "https://github.com/diaryx-org/blitz", branch = "leaf" } +winit-uikit = { git = "https://github.com/diaryx-org/blitz", branch = "leaf" } ``` Patch **every** crate of this repository that is in the graph, not only the @@ -39,18 +43,37 @@ older line (0.7) than the published 0.8 alphas, which stay crates.io's. - **An upstream fix** we want before its release is cherry-picked with `-x`, its author kept, and a note in its message of what the backport changed. - **A new Blitz release** that dioxus-native moves to: `leaf` is rebased onto - its tag. A change upstream now has is dropped then. + its tag. A change upstream now has is dropped then. The winit backends in + `patches/` move with it, to the winit that release pins; each goes when + its fix is in that winit. +- **A winit fix** goes upstream to winit, not Blitz (each `PATCH.md` says + where it stands). - Commits follow the diaryx-org rules: Conventional Commits, a `Behavioural-change:` trailer where a caller would notice. ## What is on `leaf` -Accessibility, found in leaf's Mac app and an iOS spike -(`spikes/blitz-ios-a11y` in leaf), where with these VoiceOver and agents read -and press a page: +Accessibility, found in leaf's Mac app and an iOS spike (now +`examples/ios-a11y`), where with these VoiceOver and agents read and press a +page: - Bounds on every AccessKit node (DioxusLabs/blitz#842, cherry-picked), and the viewport's for the document node. - A page's text as static text (a `Label`, its text the value); elements with no semantics as `GenericContainer`. - The click action on buttons, links, menu items and choices. +- ARIA's states: checked and pressed as toggled, a value and its range, + modal, orientation; the roles switch and separator. +- An action request carried out: a click as a click, through the window's + own events (`View::click_events`, `View::accessibility_action_events`). + +Events and layout, found by diaryx-org/unit's gallery: + +- A press focuses what it lands on when that can be focused, and a click goes + to the nearest element the press and the release share. +- A node removed under `display: none` is forgotten by its layout parent. + +And the winit backends dioxus-native pins, patched, in `patches/`: +`winit-appkit` (the Mac's text input client answers about the text round the +caret: accents, the emoji picker, dictation) and `winit-uikit` (the UIScene +lifecycle iOS 27 requires). They came from leaf's `patches/`. diff --git a/examples/ios-a11y/.gitignore b/examples/ios-a11y/.gitignore new file mode 100644 index 0000000000..84a3ee8925 --- /dev/null +++ b/examples/ios-a11y/.gitignore @@ -0,0 +1,2 @@ +/target +/uitest/ReadTree.xcodeproj diff --git a/examples/ios-a11y/Cargo.lock b/examples/ios-a11y/Cargo.lock new file mode 100644 index 0000000000..aea91c00d2 --- /dev/null +++ b/examples/ios-a11y/Cargo.lock @@ -0,0 +1,5667 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "accesskit" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_consumer" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" +dependencies = [ + "accesskit", + "hashbrown 0.17.1", +] + +[[package]] +name = "accesskit_ios" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28e539d64b27fd4c14de8f78ada8f7c944c092f52f7e49fb63316507a57f6937" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags", + "cc", + "jni 0.22.4", + "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 = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "anyrender" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1755d0ef8e00e87b6b825dfbe5a35d34d3b302e97e80a48e93f9cd361fbada06" +dependencies = [ + "kurbo", + "peniko", + "raw-window-handle", + "smallvec", +] + +[[package]] +name = "anyrender_vello" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04d545f71a3f13b1099d5787c44cfeb00322cebbebbf90c4f8cdae78bee423f7" +dependencies = [ + "anyrender", + "debug_timer", + "futures-channel", + "kurbo", + "peniko", + "pollster", + "rustc-hash 2.1.3", + "vello", + "wasm-bindgen-futures", + "wgpu 30.0.1", + "wgpu_context", +] + +[[package]] +name = "anyrender_vello_cpu" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a09d9356dd2b2f032345711a350c0e2326a854cb5070f899265bc80fb33884b1" +dependencies = [ + "anyrender", + "bytemuck", + "color", + "debug_timer", + "glifo", + "kurbo", + "peniko", + "pixels_window_renderer", + "softbuffer_window_renderer", + "vello_common", + "vello_cpu", +] + +[[package]] +name = "app_units" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "467b60e4ee6761cd6fd4e03ea58acefc8eec0d1b1def995c1b3b783fa7be8a60" +dependencies = [ + "num-traits", + "serde", +] + +[[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 = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atomic_refcell" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4" + +[[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 = "bit-set" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34ddef2995421ab6a5c779542c81ee77c115206f4ad9d5a8e05f4ff49716a3dd" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blitz-dom" +version = "0.3.0-beta.4" +dependencies = [ + "accesskit", + "anyrender", + "app_units", + "atomic_refcell", + "bitflags", + "blitz-traits", + "color", + "cssparser", + "cursor-icon", + "debug_timer", + "euclid", + "html-escape", + "icu_casemap", + "icu_locale_core", + "icu_properties", + "icu_segmenter", + "image", + "keyboard-types", + "kurbo", + "linebender_resource_handle", + "markup5ever", + "objc2 0.6.5", + "parley", + "percent-encoding", + "rayon", + "selectors", + "skrifa", + "slotmap", + "smallvec", + "stylo", + "stylo_dom", + "stylo_static_prefs", + "stylo_taffy", + "stylo_traits", + "svgtypes", + "taffy", + "thin-vec", + "thread_local", + "url", + "usvg", + "web-time", + "writeable", +] + +[[package]] +name = "blitz-ios-a11y" +version = "0.0.0" +dependencies = [ + "accesskit", + "accesskit_ios", + "anyrender_vello_cpu", + "blitz-dom", + "blitz-shell", + "blitz-traits", + "dioxus", + "dioxus-native", + "objc2 0.6.5", + "objc2-foundation 0.3.2", + "raw-window-handle", +] + +[[package]] +name = "blitz-paint" +version = "0.3.0-beta.4" +dependencies = [ + "anyrender", + "blitz-dom", + "blitz-traits", + "bytemuck", + "color", + "euclid", + "kurbo", + "parley", + "peniko", + "skrifa", + "smallvec", + "stylo", + "taffy", +] + +[[package]] +name = "blitz-shell" +version = "0.3.0-beta.4" +dependencies = [ + "android-activity", + "anyrender", + "atomic_refcell", + "blitz-dom", + "blitz-paint", + "blitz-traits", + "futures-util", + "keyboard-types", + "wasm-bindgen", + "web-sys", + "web-time", + "winit", +] + +[[package]] +name = "blitz-traits" +version = "0.3.0-beta.4" +dependencies = [ + "atomic_refcell", + "bitflags", + "bytes", + "cursor-icon", + "http", + "keyboard-types", + "serde", + "smol_str", + "url", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "bytes", + "cfg_aliases", +] + +[[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" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[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.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" +dependencies = [ + "bitflags", + "polling", + "rustix 1.1.5", + "tracing", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" +dependencies = [ + "calloop", + "rustix 1.1.5", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfb" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f" +dependencies = [ + "byteorder", + "fnv", + "uuid", +] + +[[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 = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[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 = "const_format" +version = "0.2.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4481a617ad9a412be3b97c5d403fef8ed023103368908b9c50af598ff467cc1e" +dependencies = [ + "const_format_proc_macros", + "konst", +] + +[[package]] +name = "const_format_proc_macros" +version = "0.2.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "convert_case" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaaa0ecca5b51987b9423ccdc971514dd8b0bb7b4060b983d3664dad3f1f89f" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[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-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "cssparser" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11119743ad110e8c1bdccd930d7f5c30c99e5fc76a7b63ec9807e84eef0c5f59" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf", + "serde", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" +dependencies = [ + "quote", + "syn 3.0.9", +] + +[[package]] +name = "ctor" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83cf0d42651b16c6dfe68685716d18480d18a9c39c62d76e8cf3eb6ed5d8bcbf" +dependencies = [ + "dtor", +] + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" +dependencies = [ + "darling_core 0.21.3", + "darling_macro 0.21.3", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_core" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core 0.20.11", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +dependencies = [ + "darling_core 0.21.3", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + +[[package]] +name = "debug_timer" +version = "0.1.3" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "dioxus" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a20d22ba8ac0eb0267459cfe6dcd3fd57158c37497ef422ba1940c34c5b04524" +dependencies = [ + "dioxus-config-macros", + "dioxus-core", + "dioxus-core-macro", + "dioxus-hooks", + "dioxus-html", + "dioxus-signals", + "dioxus-stores", + "subsecond", +] + +[[package]] +name = "dioxus-asset-resolver" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3405f8b33c91ddb71cd21c103cec7dde122d3c3e81702f59fa54241c996e9ad8" +dependencies = [ + "dioxus-cli-config", + "http", + "infer", + "jni 0.21.1", + "ndk", + "ndk-context", + "ndk-sys", + "percent-encoding", + "thiserror 2.0.21", + "tokio", +] + +[[package]] +name = "dioxus-cli-config" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "594aecf5eaea72c8d6c27fb582cdd882fbbe3d270539888b3e19cdeec0e414b5" + +[[package]] +name = "dioxus-config-macros" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84024d6dfd2ed560c84d874c57435f829daad9edbca907838581e541bebf1224" + +[[package]] +name = "dioxus-const-vec" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09d24d174a15ddf07d157f4644d2f6417f66278d1b90b9aeb45f73d86cbdc157" + +[[package]] +name = "dioxus-core" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44545e820910646b5ea476f913892dfc0302c146d1a8481f7fca75d80b8c6b41" +dependencies = [ + "anyhow", + "const_format", + "dioxus-const-vec", + "dioxus-core-macro", + "dioxus-core-template", + "dioxus-core-types", + "futures-channel", + "futures-util", + "generational-box", + "longest-increasing-subsequence", + "rustc-hash 2.1.3", + "rustversion", + "slab", + "slotmap", + "subsecond", + "tracing", + "xxhash-rust", +] + +[[package]] +name = "dioxus-core-macro" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13611b6d67fef8f6638e4658547106eaa15d6b5f0e142bf8bb738345e55a3a1c" +dependencies = [ + "convert_case", + "dioxus-rsx", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dioxus-core-template" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b111b4b1656abff7b086fc4aee6f1c2fb62473a01a5dba5a94c2024e8640e1c" +dependencies = [ + "dioxus-const-vec", + "xxhash-rust", +] + +[[package]] +name = "dioxus-core-types" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f1dab6f5671686cbf7f95231180d0937b04198bb5beb55753e1cca5b032f875" + +[[package]] +name = "dioxus-document" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "977047888cad56804a70fc89ae59c5e19c112507b18979b48757524bfac2ed73" +dependencies = [ + "dioxus-core", + "dioxus-core-macro", + "dioxus-core-types", + "dioxus-html", + "futures-channel", + "futures-util", + "generational-box", + "lazy-js-bundle", + "serde", + "serde_json", + "tracing", +] + +[[package]] +name = "dioxus-history" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e03ffeb1cc75a1254d3fae17a5b79413041c8a15d8c247a37a2218d23976a630" +dependencies = [ + "dioxus-core", + "tracing", +] + +[[package]] +name = "dioxus-hooks" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d11c3c292681dee1be9c8826e219b1edbaec6f510e867121dc92707384a631a" +dependencies = [ + "dioxus-core", + "dioxus-signals", + "futures-channel", + "futures-util", + "generational-box", + "rustversion", + "slab", + "tracing", +] + +[[package]] +name = "dioxus-html" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c23776aad7ba2effcc0efcb8a4df9adf2f9c3c705fa7695f2efc060ad62681ff" +dependencies = [ + "async-trait", + "bytes", + "dioxus-core", + "dioxus-core-macro", + "dioxus-core-types", + "dioxus-hooks", + "dioxus-html-internal-macro", + "enumset", + "euclid", + "futures-channel", + "futures-util", + "generational-box", + "keyboard-types", + "lazy-js-bundle", + "rustversion", + "tracing", +] + +[[package]] +name = "dioxus-html-internal-macro" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "965ae5c5b855cc803b173fa6acbab284057ed0af87f6193f6ab083770756bbb5" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dioxus-native" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd1cb86fdf731605cbeaf33c8a0a4752ee012f5c6a61ee506ba5963a4a1c8b3" +dependencies = [ + "android-activity", + "anyrender", + "anyrender_vello", + "anyrender_vello_cpu", + "blitz-dom", + "blitz-shell", + "blitz-traits", + "cfg-if", + "dioxus-asset-resolver", + "dioxus-cli-config", + "dioxus-core", + "dioxus-document", + "dioxus-history", + "dioxus-html", + "dioxus-native-dom", + "futures-util", + "keyboard-types", + "peniko", + "rustc-hash 2.1.3", + "slotmap", + "webbrowser", + "wgpu_context", + "winit", +] + +[[package]] +name = "dioxus-native-dom" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200d283bd0e6ecdd4a7542e081e44c1bf83f8aba7bc478837b918ff8dc9c0c5f" +dependencies = [ + "blitz-dom", + "blitz-traits", + "dioxus-core", + "dioxus-html", + "futures-util", + "keyboard-types", + "rustc-hash 2.1.3", +] + +[[package]] +name = "dioxus-rsx" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09dff31689498efc0001c8188d549b1ef81775093b269c774fab524bc39405be" +dependencies = [ + "dioxus-core-template", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "dioxus-signals" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0093b1cfc9c7e7d9c3ef3fbf79f83ab1de1463f9715fb438328ecefbbfbc7188" +dependencies = [ + "dioxus-core", + "futures-channel", + "futures-util", + "generational-box", + "parking_lot", + "rustc-hash 2.1.3", + "tracing", + "warnings", +] + +[[package]] +name = "dioxus-stores" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5a8a869da06b6137e008b953812f1e131fe5c02ff1ff56a7bb8317b0be93695" +dependencies = [ + "dioxus-core", + "dioxus-signals", + "dioxus-stores-macro", + "generational-box", +] + +[[package]] +name = "dioxus-stores-macro" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f0e94b059e1b809ca044dc1b6556f19e03e9eaaf0476beae486011ef9866bd3" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags", + "objc2 0.6.5", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[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", + "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 = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dtor" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "enumset" +version = "1.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccc5801fd11762e24d1e420d01d2ac518f2a2ca4329d4fbb6639f2412b6204e0" +dependencies = [ + "enumset_derive", +] + +[[package]] +name = "enumset_derive" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bd536557b58c682b217b8fb199afdff47cd3eff260623f19e77074eb073d63a" +dependencies = [ + "darling 0.21.3", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[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", + "serde", +] + +[[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 = "fearless_simd" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4beca3cb2444e3304ac30843cc091f44ed58932353cd492ce740067bfce6b12" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[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" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[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.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", +] + +[[package]] +name = "fontique" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbf1df16263783918b7da396077521f92b729ef7c429444dfcf03581f1448b77" +dependencies = [ + "hashbrown 0.17.1", + "linebender_resource_handle", + "memmap2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-text", + "objc2-foundation 0.3.2", + "parlance", + "read-fonts", + "roxmltree 0.21.1", + "smallvec", + "windows", + "windows-core", + "yeslogic-fontconfig-sys", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[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-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generational-box" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee2a83dd38383542a7494b942bde9cd0c5efd919402a19ca78fa323f5d351bb9" +dependencies = [ + "parking_lot", + "tracing", +] + +[[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.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[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 = "glifo" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1218dedd5348c1b166ec3b8b3cbca49d2f527bd43b3fa072ea5123c523ed3f" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.1", + "log", + "peniko", + "skrifa", + "smallvec", + "vello_common", +] + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "gpu-descriptor" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca" +dependencies = [ + "bitflags", + "gpu-descriptor-types", + "hashbrown 0.15.5", +] + +[[package]] +name = "gpu-descriptor-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91" +dependencies = [ + "bitflags", +] + +[[package]] +name = "guillotiere" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab" +dependencies = [ + "euclid", + "svg_fmt", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hexf-parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" + +[[package]] +name = "html-escape" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9356095b4b41197bba32173600e1582792cda618f65d12f68e2e77d273413c5" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "icu_casemap" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2edfd120d8445de853cf53a1abec916f638f933a70a6f4bf8f7e2d7b7f884e9" +dependencies = [ + "icu_casemap_data", + "icu_collections", + "icu_locale_core", + "icu_properties", + "icu_provider", + "potential_utf", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_casemap_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "059fcda0fc8d33effc6633a8cf0d8a3c17caf7d7c91918fba9918744f501e4e8" + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "serde", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db" +dependencies = [ + "core_maths", + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[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", +] + +[[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 0.17.1", +] + +[[package]] +name = "infer" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7" +dependencies = [ + "cfb", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.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", + "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 = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags", + "serde", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "konst" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" +dependencies = [ + "konst_macro_rules", +] + +[[package]] +name = "konst_macro_rules" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" + +[[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-js-bundle" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c79f0c69caec3210fc12f3cb250f3e2179bb76b52edfec846983c5b236fb68b" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[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", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[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 = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "longest-increasing-subsequence" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3bd0dd2cd90571056fdb71f6275fada10131182f84899f4b2a916e565d81d86" + +[[package]] +name = "malloc_size_of_derive" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f44db74bde26fdf427af23f1d146c211aed857c59e3be750cf2617f6b0b05c94" +dependencies = [ + "proc-macro2", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "markup5ever" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842" +dependencies = [ + "log", + "tendril", + "web_atoms", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memfd" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57804b2c9b69967f1536a56f86297e367a33b19e98852ed624b84551cdbc0d90" +dependencies = [ + "rustix 1.1.5", +] + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[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 = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "naga" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2bf919621e7975acb27d881bae2fb993e0d45c8e0446e85e6272971e00dc8df" +dependencies = [ + "arrayvec", + "bit-set 0.9.1", + "bitflags", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.16.1", + "hexf-parse", + "indexmap", + "libm", + "log", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set 0.10.0", + "bitflags", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags", + "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 = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[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-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" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "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", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", + "block2 0.6.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags", + "dispatch2", + "libc", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[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", + "block2 0.5.1", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags", + "block2 0.6.2", + "libc", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "orbclient" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01f140a738f180203d7912dfd369936fff2fb0ad6f426c0aa007ed3e2b443e6b" +dependencies = [ + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +dependencies = [ + "num-traits", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "parlance" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "parley" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61bd0c0c1737f0b3d3726dc06b225083af213b61913e4fbae1670613a106c6ce" +dependencies = [ + "fontique", + "hashbrown 0.17.1", + "linebender_resource_handle", + "parlance", + "parley_engine", + "smallvec", +] + +[[package]] +name = "parley_data" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c43b63f808f6cc8f4a3b07de0d62a977bddd2e0bb5c232bd9e93ba8ef92e5e4b" +dependencies = [ + "icu_collections", + "icu_properties", +] + +[[package]] +name = "parley_emoji" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c4482d912d7671a7cd2089794f90ef3bb5f5f8c738230fb0fcd50fa020f0ed3" + +[[package]] +name = "parley_engine" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74c0d373e462e504ad4436710a39f099e18e848e1ee711f70cd2dcd5a69b290" +dependencies = [ + "fontique", + "harfrust", + "hashbrown 0.17.1", + "icu_locale_core", + "icu_normalizer", + "icu_properties", + "icu_segmenter", + "linebender_resource_handle", + "parlance", + "parley_data", + "parley_emoji", + "skrifa", +] + +[[package]] +name = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo", + "linebender_resource_handle", + "smallvec", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[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 = "pixels" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27af78f16789b973b8b340fe3f68cc2ec9f5e6f4aea64e4d794d5833ac9ca52e" +dependencies = [ + "bytemuck", + "pollster", + "raw-window-handle", + "thiserror 2.0.21", + "ultraviolet", + "wgpu 29.0.4", +] + +[[package]] +name = "pixels_window_renderer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31c2ba47171f8376a1cd74f8d575f1d729c033fc007f59a9da3688c31187264b" +dependencies = [ + "anyrender", + "debug_timer", + "pixels", +] + +[[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", + "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", + "pin-project-lite", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[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 = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "version_check", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[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 = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "redox_event" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5018d583d6d2f5499352aea8d177e9067d1eb03ab17c78169d5ba7a30001b15" +dependencies = [ + "bitflags", + "libredox", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags", +] + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[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 = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[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", + "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", + "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 = "safe_arch" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323" +dependencies = [ + "bytemuck", +] + +[[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 = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sctk-adwaita" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f8ea028b7cb32e2f577b0a55a7b54cb206376bdb1221bd5c81dcf20b68db1fb" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit", + "tiny-skia", +] + +[[package]] +name = "selectors" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8322aebea94a6cc288ff884e8a49bdbceef60206c400c6c46d22e62fc4fd91a6" +dependencies = [ + "bitflags", + "cssparser", + "derive_more", + "log", + "new_debug_unreachable", + "precomputed-hash", + "rustc-hash 2.1.3", + "servo_arc", + "smallvec", + "to_shmem", + "to_shmem_derive", +] + +[[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_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[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 = "servo_arc" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4eceb519ec34d8290aaf6e46f435102f2bfa63f22b05a144fb16ab266d3b198" +dependencies = [ + "serde", + "stable_deref_trait", +] + +[[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.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[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 = [ + "serde", + "version_check", +] + +[[package]] +name = "smallbitvec" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b0e903ee191d8f7a8fbf0d712c3a1699d19e04ceba5ad1eb673053c7d938a09" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "smithay-client-toolkit" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dc9ee14b0fdcb535f9556141bacac070c994a977d2240ee455d7438a617f00" +dependencies = [ + "bitflags", + "calloop", + "calloop-wayland-source", + "cursor-icon", + "log", + "memmap2", + "rustix 1.1.5", + "thiserror 2.0.21", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-experimental", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa7368fcf4852a4c2dd92df0cace6a71f2091ca0a23391ce7f3a31833f1523" +dependencies = [ + "borsh", + "serde_core", +] + +[[package]] +name = "softbuffer" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" +dependencies = [ + "as-raw-xcb-connection", + "bytemuck", + "drm", + "fastrand", + "js-sys", + "memmap2", + "ndk", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "raw-window-handle", + "redox_syscall 0.5.18", + "rustix 1.1.5", + "tiny-xlib", + "tracing", + "wasm-bindgen", + "wayland-backend", + "wayland-client", + "wayland-sys", + "web-sys", + "windows-sys 0.61.2", + "x11rb", +] + +[[package]] +name = "softbuffer_window_renderer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "809f260e686014e0222158362d571a7813cd836a27b7e51ed7e1dcf39ce08378" +dependencies = [ + "anyrender", + "debug_timer", + "kurbo", + "peniko", + "softbuffer", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[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 = "string_cache" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared", + "precomputed-hash", + "serde", +] + +[[package]] +name = "string_cache_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", +] + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "stylo" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a255e46af2478628c48daab3774090caabd7812b1dd3ca98801c2b9c53491ed" +dependencies = [ + "app_units", + "arrayvec", + "atomic_refcell", + "bitflags", + "byteorder", + "cssparser", + "derive_more", + "encoding_rs", + "euclid", + "icu_segmenter", + "indexmap", + "itertools", + "itoa", + "log", + "malloc_size_of_derive", + "mime", + "new_debug_unreachable", + "num-derive", + "num-integer", + "num-traits", + "num_cpus", + "parking_lot", + "precomputed-hash", + "rayon", + "rayon-core", + "rustc-hash 2.1.3", + "selectors", + "serde", + "servo_arc", + "smallbitvec", + "smallvec", + "static_assertions", + "string_cache", + "strum", + "strum_macros", + "stylo_atoms", + "stylo_derive", + "stylo_dom", + "stylo_malloc_size_of", + "stylo_static_prefs", + "stylo_traits", + "thin-vec", + "to_shmem", + "to_shmem_derive", + "uluru", + "url", + "void", + "walkdir", + "web_atoms", +] + +[[package]] +name = "stylo_atoms" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee1771588fd747ef16f8b1990061b6f37c7d3251a0f9b74f405a44c0c5fb8966" +dependencies = [ + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "stylo_derive" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ee5c550c2e00a0b3c046bef84a9ee217e04e7c014142eeb96f9e48781c5cfd3" +dependencies = [ + "darling 0.20.11", + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "stylo_dom" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9febcb03f2b669ef06b3e8a5209e6280971ed55cecf83fbf3c0562fcf2aa2ec6" +dependencies = [ + "bitflags", + "stylo_malloc_size_of", +] + +[[package]] +name = "stylo_malloc_size_of" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83ed69d55ee907599f093221004a28371925236f09f20961963020abf38bab6a" +dependencies = [ + "app_units", + "cssparser", + "euclid", + "parking_lot", + "selectors", + "servo_arc", + "smallbitvec", + "smallvec", + "string_cache", + "thin-vec", + "void", +] + +[[package]] +name = "stylo_static_prefs" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6767c48a1590461db79f8b434ccc5a2d65600a3b716751f7999b35ccead1e024" +dependencies = [ + "toml", +] + +[[package]] +name = "stylo_taffy" +version = "0.3.0-beta.4" +dependencies = [ + "bitflags", + "stylo", + "stylo_atoms", + "taffy", +] + +[[package]] +name = "stylo_traits" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "645d6bfe40eb6e86ebe9f2d2adadcbced41bfa96175de7cb13d4d178d27bc83d" +dependencies = [ + "app_units", + "bitflags", + "cssparser", + "euclid", + "malloc_size_of_derive", + "selectors", + "serde", + "servo_arc", + "stylo_atoms", + "stylo_malloc_size_of", + "thin-vec", + "to_shmem", + "to_shmem_derive", + "url", +] + +[[package]] +name = "subsecond" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f21c1509f00df90c330f868b677ea22a7f7138e7649b0f125e95041bdf84d48f" +dependencies = [ + "js-sys", + "libc", + "libloading", + "memfd", + "memmap2", + "serde", + "subsecond-types", + "thiserror 2.0.21", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "subsecond-types" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f9ef2c7a2a28761e9291172753ff82ec56cf46f1d90c808c6bba924f5295057" +dependencies = [ + "serde", +] + +[[package]] +name = "svg_fmt" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb" + +[[package]] +name = "svgtypes" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "695b5790b3131dafa99b3bbfd25a216edb3d216dad9ca208d4657bfb8f2abc3d" +dependencies = [ + "kurbo", + "siphasher", +] + +[[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 = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "taffy" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa" +dependencies = [ + "serde", + "slotmap", + "smallvec", +] + +[[package]] +name = "tendril" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" +dependencies = [ + "new_debug_unreachable", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thin-vec" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6a4b9ba8738cb4a4f399d37e266becfd475e75eb73425b87a05a2f2039ba63e" + +[[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", + "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 = "tiny-xlib" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a90a0ca3ee6a69f2ad28fd11621a4c3f03b371f366be500b64df260c4ffbafb4" +dependencies = [ + "as-raw-xcb-connection", + "ctor", + "libloading", + "pkg-config", + "tracing", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "to_shmem" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbf077da8dd01cc18453bd7d9bc3a945c262f5f344562e5f6deb3914b4dd6f14" +dependencies = [ + "cssparser", + "servo_arc", + "smallbitvec", + "smallvec", + "string_cache", + "thin-vec", +] + +[[package]] +name = "to_shmem_derive" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f8e91a023810fd2019648410d00eea13a71f21d849e71d6d9ed936fb8061174" +dependencies = [ + "darling 0.20.11", + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "tokio" +version = "1.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[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", + "toml_parser", + "winnow", +] + +[[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", +] + +[[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", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "ultraviolet" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea519dad475ee0446b8172793c3c327e4fc81dafdaf05aaac510e630000b6296" +dependencies = [ + "wide", +] + +[[package]] +name = "uluru" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c8a2469e56e6e5095c82ccd3afb98dad95f7af7929aab6d8ba8d6e0f73657da" +dependencies = [ + "arrayvec", +] + +[[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-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 = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[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", + "harfrust", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree 0.21.1", + "simplecss", + "siphasher", + "skrifa", + "strict-num", + "svgtypes", + "tiny-skia-path", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "vello" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913abde56cab6131b62c0cc69b1a93b671d3c34b3097beb3714fd1dc93be8115" +dependencies = [ + "bytemuck", + "futures-intrusive", + "log", + "peniko", + "png", + "skrifa", + "static_assertions", + "thiserror 2.0.21", + "vello_encoding", + "vello_shaders", + "wgpu 30.0.1", +] + +[[package]] +name = "vello_common" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73c2fbe53548bcd25c8ff42f75a93770a8611a16b37bee56d7ef7b44e36027f1" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "log", + "peniko", + "png", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_cpu" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed1fec424fbba6acf6cbc78bb526447eb77590d95f40419d598870fe37535212" +dependencies = [ + "bytemuck", + "glifo", + "hashbrown 0.17.1", + "vello_common", +] + +[[package]] +name = "vello_encoding" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1fb9548d2b46b0f79137b5b1d208ecbd76d432f74e7a2ba838615d117f11532" +dependencies = [ + "bytemuck", + "guillotiere", + "peniko", + "skrifa", + "smallvec", +] + +[[package]] +name = "vello_shaders" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e653222cee49f2571729c3e4b0fa99bc4f826c6bb9487dbb88b825d552b3a27" +dependencies = [ + "bytemuck", + "log", + "naga 30.0.1", + "thiserror 2.0.21", + "vello_encoding", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" + +[[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 = "warnings" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64f68998838dab65727c9b30465595c6f7c953313559371ca8bf31759b3680ad" +dependencies = [ + "pin-project", + "tracing", + "warnings-macro", +] + +[[package]] +name = "warnings-macro" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59195a1db0e95b920366d949ba5e0d3fc0e70b67c09be15ce5abb790106b0571" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[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", + "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", + "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-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-experimental" +version = "20251230.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c6c3e7178e553d093d46999032bc79aafea9dedd71dd702c8ace7bbc25cf13" +dependencies = [ + "bitflags", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags", + "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", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[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-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "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 = "web_atoms" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada" +dependencies = [ + "phf", + "phf_codegen", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "webbrowser" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94" +dependencies = [ + "jni 0.22.4", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + +[[package]] +name = "wgpu" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76e8840e1ba2881d4cbb18d2147627a56af426ff064c0401eb0c8410c6325d07" +dependencies = [ + "arrayvec", + "bitflags", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.16.1", + "js-sys", + "log", + "naga 29.0.4", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core 29.0.4", + "wgpu-hal 29.0.4", + "wgpu-types 29.0.4", +] + +[[package]] +name = "wgpu" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e" +dependencies = [ + "arrayvec", + "bitflags", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "naga 30.0.1", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core 30.0.1", + "wgpu-hal 30.0.1", + "wgpu-types 30.0.1", +] + +[[package]] +name = "wgpu-core" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f519832254e56965a9940c4af57dcb75f702b6f6fa4a0b172f685395843a4d7" +dependencies = [ + "arrayvec", + "bit-set 0.9.1", + "bit-vec", + "bitflags", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.16.1", + "indexmap", + "log", + "naga 29.0.4", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple 29.0.4", + "wgpu-core-deps-emscripten 29.0.4", + "wgpu-core-deps-wasm", + "wgpu-core-deps-windows-linux-android 29.0.4", + "wgpu-hal 29.0.4", + "wgpu-naga-bridge 29.0.4", + "wgpu-types 29.0.4", +] + +[[package]] +name = "wgpu-core" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" +dependencies = [ + "arrayvec", + "bit-set 0.10.0", + "bit-vec", + "bitflags", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga 30.0.1", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple 30.0.1", + "wgpu-core-deps-emscripten 30.0.1", + "wgpu-core-deps-windows-linux-android 30.0.1", + "wgpu-hal 30.0.1", + "wgpu-naga-bridge 30.0.1", + "wgpu-types 30.0.1", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e39e26c4c0e07589e67d18546cf79ff45383659fc72fca4dd293358a0347f3" +dependencies = [ + "wgpu-hal 29.0.4", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68" +dependencies = [ + "wgpu-hal 30.0.1", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01e09be551dc939498bdd5f6b2c66e55ab275dad25825267a08605a80fc9f0af" +dependencies = [ + "wgpu-hal 29.0.4", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86" +dependencies = [ + "wgpu-hal 30.0.1", +] + +[[package]] +name = "wgpu-core-deps-wasm" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1fb1798be2a912497d4c224f72d39bb0cb34af50e8bcc29865bc339c943059" +dependencies = [ + "wgpu-hal 29.0.4", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e592c1bbef6ad047647ae6e666ebd8cee7a32bb4544d9700ec96cbf73230257" +dependencies = [ + "wgpu-hal 29.0.4", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f" +dependencies = [ + "wgpu-hal 30.0.1", +] + +[[package]] +name = "wgpu-hal" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97ace1c17727311c22a46e4e3faf56ea6de81af99dcc839bdfb54857b94d448d" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set 0.9.1", + "bitflags", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "gpu-descriptor", + "hashbrown 0.16.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga 29.0.4", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge 29.0.4", + "wgpu-types 29.0.4", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set 0.10.0", + "bitflags", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga 30.0.1", + "naga-types", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge 30.0.1", + "wgpu-types 30.0.1", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95226013f547544b223281cd16a4fb549aa9dcb562adbda0faae4c73ffbbc161" +dependencies = [ + "naga 29.0.4", + "wgpu-types 29.0.4", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga 30.0.1", + "wgpu-types 30.0.1", +] + +[[package]] +name = "wgpu-types" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84bf84cd9ca8ca45e2b223a3868f1adf9bfc0c66aeac212e76ee7e40fdadf8f5" +dependencies = [ + "bitflags", + "bytemuck", + "js-sys", + "log", + "raw-window-handle", + "web-sys", +] + +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "wgpu_context" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5277f9d30e7087f1eeb0034206dce7d3377e76da017fdceb8aa4faebb1df68e2" +dependencies = [ + "futures-intrusive", + "wgpu 30.0.1", +] + +[[package]] +name = "wide" +version = "0.7.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03" +dependencies = [ + "bytemuck", + "safe_arch", +] + +[[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 = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[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-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[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.31.0-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f431156a3e4f0f1b35eaaf37674e55838e3652908c8088f570466274d1902e2b" +dependencies = [ + "bitflags", + "cfg_aliases", + "cursor-icon", + "dpi", + "libc", + "raw-window-handle", + "rustix 1.1.5", + "smol_str", + "tracing", + "winit-android", + "winit-appkit", + "winit-common", + "winit-core", + "winit-orbital", + "winit-uikit", + "winit-wayland", + "winit-web", + "winit-win32", + "winit-x11", +] + +[[package]] +name = "winit-android" +version = "0.31.0-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5d60d944a564986b9311e325334cc22e7e4cf726dd0ff7475fd925404215af4" +dependencies = [ + "android-activity", + "bitflags", + "dpi", + "ndk", + "raw-window-handle", + "smol_str", + "tracing", + "winit-core", +] + +[[package]] +name = "winit-appkit" +version = "0.31.0-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23343ec0ea7ac6aa72f38009a6ff66fb63bcf6395e0622fba72794d2a762ab42" +dependencies = [ + "bitflags", + "block2 0.6.2", + "dispatch2", + "dpi", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-video", + "objc2-foundation 0.3.2", + "raw-window-handle", + "smol_str", + "tracing", + "winit-common", + "winit-core", +] + +[[package]] +name = "winit-common" +version = "0.31.0-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e90422ff1c04502aaaac1dad1d099791c2bbb3fbb3f823019e0ce5cdeee04025" +dependencies = [ + "block2 0.6.2", + "dpi", + "memmap2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "smol_str", + "tracing", + "winit-core", + "x11-dl", + "xkbcommon-dl", +] + +[[package]] +name = "winit-core" +version = "0.31.0-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8af6307236c51847199950c15cf80e0481a250bb96ce9132f5026df4ad3d0f9" +dependencies = [ + "bitflags", + "cursor-icon", + "dpi", + "keyboard-types", + "raw-window-handle", + "smol_str", + "url", + "web-time", +] + +[[package]] +name = "winit-orbital" +version = "0.31.0-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "278a8ae837902a3bc95dd2fd696d680da33f32130eecc29905358c9089cf6c50" +dependencies = [ + "bitflags", + "dpi", + "libredox", + "orbclient", + "raw-window-handle", + "redox_event", + "smol_str", + "tracing", + "winit-core", +] + +[[package]] +name = "winit-uikit" +version = "0.31.0-beta.3" +dependencies = [ + "bitflags", + "block2 0.6.2", + "dispatch2", + "dpi", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-ui-kit 0.3.2", + "raw-window-handle", + "smol_str", + "tracing", + "winit-common", + "winit-core", +] + +[[package]] +name = "winit-wayland" +version = "0.31.0-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b64ceed06de0c45886eef05102106abe1413e703384e337bc57c7e95b71f803" +dependencies = [ + "bitflags", + "calloop", + "cursor-icon", + "dpi", + "foldhash 0.2.0", + "libc", + "memmap2", + "percent-encoding", + "raw-window-handle", + "rustix 1.1.5", + "sctk-adwaita", + "smithay-client-toolkit", + "smol_str", + "tracing", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "winit-common", + "winit-core", +] + +[[package]] +name = "winit-web" +version = "0.31.0-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f539be45f95cc297bdfb80569aef38d925d64aec4133852a4d3fc5cb3660f1c9" +dependencies = [ + "atomic-waker", + "bitflags", + "concurrent-queue", + "cursor-icon", + "dpi", + "js-sys", + "pin-project", + "raw-window-handle", + "smol_str", + "tracing", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "winit-core", +] + +[[package]] +name = "winit-win32" +version = "0.31.0-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25fb480c41df01d351f656cbf3ad74013f8a9d22bb5b2dcab59f9167e7a0b6ec" +dependencies = [ + "bitflags", + "cursor-icon", + "dpi", + "raw-window-handle", + "smol_str", + "tracing", + "unicode-segmentation", + "url", + "windows-sys 0.61.2", + "winit-common", + "winit-core", +] + +[[package]] +name = "winit-x11" +version = "0.31.0-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb5746cd907e514b7895491a1c6f7d0cb70077f9e16928cd74ae6f987ffd96aa" +dependencies = [ + "bitflags", + "bytemuck", + "calloop", + "cursor-icon", + "dpi", + "libc", + "percent-encoding", + "raw-window-handle", + "rustix 1.1.5", + "smol_str", + "tracing", + "winit-common", + "winit-core", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[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", + "once_cell", + "rustix 1.1.5", + "x11rb-protocol", + "xcursor", +] + +[[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 = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags", + "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 = "xxhash-rust" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure 0.14.0", +] + +[[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 = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure 0.14.0", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/examples/ios-a11y/Cargo.toml b/examples/ios-a11y/Cargo.toml new file mode 100644 index 0000000000..fe62ed9df7 --- /dev/null +++ b/examples/ios-a11y/Cargo.toml @@ -0,0 +1,51 @@ +# Does VoiceOver on iOS read a Blitz page, through AccessKit's iOS adapter? +# (Begun as leaf's spikes/blitz-ios-a11y, 2026-10-19.) A one-window Dioxus page on blitz-shell, its accessibility tree +# built by blitz-dom and handed to `accesskit_ios`, whose `SubclassingAdapter` +# takes over winit's UIView. Run with `scripts/run.sh` (README.md). +[workspace] + +[package] +name = "blitz-ios-a11y" +version = "0.0.0" +edition = "2024" +publish = false + +[[bin]] +name = "BlitzA11y" +path = "src/main.rs" + +[dependencies] +dioxus = { version = "0.8.0-alpha.3", default-features = false, features = ["macro", "html", "signals", "hooks"] } +dioxus-native = { version = "0.8.0-alpha.3", default-features = false, features = ["system-fonts", "vello"] } +blitz-shell = { version = "=0.3.0-beta.4", default-features = false } +# `accessibility` here only: blitz-shell's would bring accesskit_xplat, which +# has no iOS adapter and does nothing there. +blitz-dom = { version = "=0.3.0-beta.4", default-features = false, features = ["accessibility", "system-fonts"] } +blitz-traits = "=0.3.0-beta.4" +# The CPU renderer: Vello on the GPU needs indirect execution, which the +# simulator's Metal lacks. +anyrender_vello_cpu = { version = "0.18", features = ["softbuffer_window_renderer"] } +accesskit = "0.25" +accesskit_ios = "0.2.1" +raw-window-handle = "0.6" +# The self-test (`BLITZ_A11Y_ACTIVATE`): UIKit's accessibility calls, as VoiceOver makes them. +objc2 = "0.6" +objc2-foundation = { version = "0.3", features = ["NSArray", "NSString"] } + +[patch.crates-io] +# This repository's Blitz, and its winit-uikit: 0.31.0-beta.3 with +# rust-windowing/winit#4723 (the UIScene lifecycle), without which an app +# built with the iOS 27 SDK does not launch (patches/winit-uikit/PATCH.md). +# Every Blitz crate in the graph comes from here: they depend on each other +# by path, so one from crates.io beside them would be a second copy. +winit-uikit = { path = "../../patches/winit-uikit" } +blitz-dom = { path = "../../packages/blitz-dom" } +blitz-traits = { path = "../../packages/blitz-traits" } +blitz-shell = { path = "../../packages/blitz-shell" } +blitz-paint = { path = "../../packages/blitz-paint" } +stylo_taffy = { path = "../../packages/stylo_taffy" } +debug_timer = { path = "../../packages/debug_timer" } + +# Blitz is unusably slow unoptimised; this crate stays debuggable. +[profile.dev.package."*"] +opt-level = 3 diff --git a/examples/ios-a11y/README.md b/examples/ios-a11y/README.md new file mode 100644 index 0000000000..b7f25659c7 --- /dev/null +++ b/examples/ios-a11y/README.md @@ -0,0 +1,80 @@ +# VoiceOver on a Blitz page, on iOS + +Begun as leaf's `spikes/blitz-ios-a11y` (2026-10-19) and kept here, where +the Blitz and the winit-uikit it tests are. + +Does iOS's accessibility (VoiceOver, XCUITest, an agent) reach a page drawn by +Blitz? Yes, with AccessKit's iOS adapter and four small changes to Blitz's +tree. Verified on an iPhone 17 simulator, iOS 27. + +```sh +scripts/run.sh # build, bundle, run on agent-blitz-a11y +SIMCTL_CHILD_BLITZ_A11Y_ACTIVATE="Press me" scripts/run.sh # and activate the button as VoiceOver would +cd uitest && xcodegen generate && xcodebuild test -project ReadTree.xcodeproj \ + -scheme ReadTree -destination 'platform=iOS Simulator,name=agent-blitz-a11y' +xcrun simctl delete agent-blitz-a11y # when done +``` + +## What it is + +A one-window Dioxus page (a heading, a paragraph, a button that counts its +presses, a status line) on blitz-shell, hosted as leaf's Mac app hosts its +windows (`src/main.rs`). `accesskit_ios` 0.2.1's `SubclassingAdapter` takes +over winit's `UIView`; after every frame the adapter is given blitz-dom's +tree; an action request comes back through the event loop and is carried out +as a click at the node's middle. + +blitz-shell's own `accessibility` feature is not used: it goes through +`accesskit_xplat`, which has no iOS adapter and falls back to a null one. + +## What it showed + +`uitest/` reads the tree from outside, as XCUITest sees it, then taps the +button by its accessibility frame. The app's self-test +(`BLITZ_A11Y_ACTIVATE`) finds the element by its label through UIKit's own +accessibility API and calls `accessibilityActivate`, which is VoiceOver's +double tap. Both pressed the button ("Pressed 2 times"). + +| Element | Type | Label | Frame (pt) | +|---|---|---|---| +| heading | static text | Leaf on Blitz | 56, 209, 290×33 | +| paragraph | static text | VoiceOver should read this paragraph, … | 56, 261, 290×40 | +| button | button | Press me | 56, 330, 104×42 | +| status | static text | Pressed 1 times | 56, 401, 290×20 | + +## What it needed + +In blitz-dom, on this fork, all platform-neutral: + +1. **Bounds** on every node (DioxusLabs/blitz#842), and the viewport's for + the document node, which has no box. +2. **Text as static text**: a `Label` with its text as its *value* (AccessKit's + convention, which the iOS adapter follows strictly; macOS's accepted a + label). A `TextRun` is dropped by every adapter outside a text field. + Whitespace-only text is skipped. An element with no semantics is a + `GenericContainer`, passed through, not an unnamed `Unknown`. +3. **The click action** on buttons, links, menu items, checkboxes, radios, + tabs, options and switches, so assistive tech offers a press. + +In the host (`src/main.rs`), what blitz-shell would do on iOS: + +4. **The safe area.** blitz-shell lays the page out inside the window's safe + area, and the adapter places nodes in the view, which is the whole screen: + the tree's root is translated by the safe area's insets, and a click asked + for is placed with them. Without it every frame was 62 pt too high, and a + tap at an element's frame missed it. +5. **Carrying out an action request.** blitz-shell's `BlitzApplication` + now does (a click, through `View::click_events`), but goes through + `accesskit_xplat`; this example, on `accesskit_ios`, asks `click_events` + itself. + +And in winit-uikit (`patches/winit-uikit` here): rust-windowing/winit#4723, the +UIScene lifecycle, without which an app built with the iOS 27 SDK does not +launch. The page draws with Vello on the CPU: Vello on the GPU needs indirect +execution, which the simulator's Metal lacks (a device may not). + +## Not covered + +VoiceOver itself does not run in the simulator; `accessibilityActivate` is +what it calls. A real device, the editor widget (whose rows need roles), text +input and editing, and the tree's cost per frame (rebuilt whole) are left. diff --git a/examples/ios-a11y/ios/Info.plist b/examples/ios-a11y/ios/Info.plist new file mode 100644 index 0000000000..d008439ffd --- /dev/null +++ b/examples/ios-a11y/ios/Info.plist @@ -0,0 +1,39 @@ + + + + + CFBundleIdentifier + org.diaryx.leaf.agent-blitz-a11y + CFBundleName + BlitzA11y + CFBundleExecutable + BlitzA11y + CFBundlePackageType + APPL + CFBundleVersion + 1 + CFBundleShortVersionString + 0.0.0 + MinimumOSVersion + 17.0 + UIDeviceFamily + 12 + UILaunchScreen + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + + + + + + diff --git a/examples/ios-a11y/scripts/run.sh b/examples/ios-a11y/scripts/run.sh new file mode 100755 index 0000000000..ab164098aa --- /dev/null +++ b/examples/ios-a11y/scripts/run.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# Build the spike for the iOS simulator, bundle it, and run it on a simulator +# made for it: `agent-blitz-a11y`, iPhone 17, iOS 27 (made if missing; delete +# it with `xcrun simctl delete agent-blitz-a11y` when done). +set -e +cd "$(dirname "$0")/.." +cargo build --target aarch64-apple-ios-sim +APP=target/BlitzA11y.app +rm -rf "$APP" && mkdir -p "$APP" +cp target/aarch64-apple-ios-sim/debug/BlitzA11y ios/Info.plist "$APP/" +codesign --force --sign - "$APP" >/dev/null 2>&1 +SIM=agent-blitz-a11y +xcrun simctl list devices | grep -q "$SIM (" || \ + xcrun simctl create "$SIM" "iPhone 17" com.apple.CoreSimulator.SimRuntime.iOS-27-0 +xcrun simctl bootstatus "$SIM" -b >/dev/null +xcrun simctl install "$SIM" "$APP" +xcrun simctl terminate "$SIM" org.diaryx.leaf.agent-blitz-a11y 2>/dev/null || true +xcrun simctl launch --console-pty --terminate-running-process "$SIM" org.diaryx.leaf.agent-blitz-a11y diff --git a/examples/ios-a11y/src/main.rs b/examples/ios-a11y/src/main.rs new file mode 100644 index 0000000000..958143d4db --- /dev/null +++ b/examples/ios-a11y/src/main.rs @@ -0,0 +1,303 @@ +//! A Blitz page on iOS, read by VoiceOver. +//! +//! One window, made the way leaf's Mac app makes its own (blitz-shell's +//! `BlitzApplication`, wrapped), with three additions for accessibility: +//! +//! - when the window is made, `accesskit_ios`'s `SubclassingAdapter` takes +//! over winit's `UIView`, so UIKit asks the adapter for the view's +//! accessibility elements; +//! - after every frame, the adapter is given the page's tree, built by +//! blitz-dom (a no-op until assistive tech asks); +//! - a request from assistive tech — VoiceOver's double tap — comes back +//! through the event loop, and a click is carried out as a click at the +//! middle of the node, through the window's own events +//! (`View::click_events`). + +use accesskit::{ + Action, ActionHandler, ActionRequest, ActivationHandler, DeactivationHandler, TreeUpdate, +}; +use accesskit_ios::SubclassingAdapter; +use anyrender_vello_cpu::{SoftbufferWindowRenderer, VelloCpuImageRenderer}; +use blitz_dom::DocumentConfig; +use blitz_shell::{BlitzApplication, BlitzShellEvent, BlitzShellProxy, WindowConfig}; +use blitz_traits::node_id::NodeId; +use dioxus::prelude::*; +use dioxus_native::DioxusDocument; +use dioxus_native::winit::application::ApplicationHandler; +use dioxus_native::winit::event::WindowEvent; +use dioxus_native::winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; +use dioxus_native::winit::window::{WindowAttributes, WindowId}; +use raw_window_handle::{HasWindowHandle, RawWindowHandle}; + +const CSS: &str = " +main { padding: 60px 24px; font: 17px system-ui, -apple-system, sans-serif; } +h1 { font-size: 28px; } +button { font-size: 17px; padding: 10px 18px; margin: 12px 0; } +"; + +#[allow(non_snake_case)] +fn Page() -> Element { + let mut presses = use_signal(|| 0); + rsx! { + style { {CSS} } + main { + h1 { "Leaf on Blitz" } + p { "VoiceOver should read this paragraph, and the button under it." } + button { onclick: move |_| presses += 1, "Press me" } + p { role: "status", "Pressed {presses} times" } + } + } +} + +/// What the adapter's handlers send the event loop: they run inside UIKit's +/// accessibility queries, where the page cannot be touched. +enum Ask { + /// Assistive tech is listening: build and hand over the tree. + Tree(WindowId), + /// Do what assistive tech asked. + Action(WindowId, ActionRequest), + /// Activate the element of this label, as VoiceOver's double tap does. + Activate(String), +} + +struct Activation(BlitzShellProxy, WindowId); +impl ActivationHandler for Activation { + fn request_initial_tree(&mut self) -> Option { + eprintln!("accessibility: initial tree requested"); + // The self-test: a few seconds on, activate the button as VoiceOver would. + if let Ok(label) = std::env::var("BLITZ_A11Y_ACTIVATE") { + let proxy = self.0.clone(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(4)); + proxy.send_event(BlitzShellEvent::embedder_event(AskBox::new(Ask::Activate( + label, + )))); + }); + } + self.0 + .send_event(BlitzShellEvent::embedder_event(AskBox::new(Ask::Tree( + self.1, + )))); + None + } +} + +struct Actions(BlitzShellProxy, WindowId); +impl ActionHandler for Actions { + fn do_action(&mut self, request: ActionRequest) { + eprintln!( + "accessibility action {:?} on {:?}", + request.action, request.target_node + ); + self.0 + .send_event(BlitzShellEvent::embedder_event(AskBox::new(Ask::Action( + self.1, request, + )))); + } +} + +struct Deactivation; +impl DeactivationHandler for Deactivation { + fn deactivate_accessibility(&mut self) {} +} + +/// `Ask` behind a mutex, as an embedder event must be `Send + Sync`. +struct AskBox(std::sync::Mutex>); +impl AskBox { + fn new(ask: Ask) -> Self { + Self(std::sync::Mutex::new(Some(ask))) + } +} +// SAFETY: an `Ask` is made and taken on the main thread only. +unsafe impl Send for AskBox {} +unsafe impl Sync for AskBox {} + +/// Vello on the CPU, drawn into a softbuffer surface. +type Renderer = SoftbufferWindowRenderer; + +struct App { + blitz: BlitzApplication, + adapter: Option, + built: bool, +} + +impl App { + /// Hand the adapter the page's tree, if assistive tech is listening. + fn update_tree(&mut self, id: WindowId) { + let (Some(adapter), Some(view)) = (self.adapter.as_mut(), self.blitz.windows.get(&id)) + else { + return; + }; + let doc = view.doc.inner(); + // blitz-shell lays the page out inside the window's safe area (below + // the status bar on iOS); the adapter places nodes in the view, which + // is the whole screen. So the root is moved by the safe area's insets, + // and every node with it — VoiceOver's hit test too. + let insets = view.window.safe_area(); + let offset = (insets.left as f64, insets.top as f64); + let mut built = None; + let events = adapter.update_if_active(|| { + let mut tree = doc.build_accessibility_tree(); + let root = tree.tree.as_ref().map(|t| t.root); + if let Some((_, node)) = tree.nodes.iter_mut().find(|(id, _)| Some(*id) == root) { + node.set_transform(accesskit::Affine::translate(offset)); + } + built = Some(tree.nodes.len()); + tree + }); + if let Some(n) = built { + eprintln!("accessibility: tree of {n} nodes handed over"); + } + if let Some(events) = events { + events.raise(); + } + } + + fn act(&mut self, event_loop: &dyn ActiveEventLoop, id: WindowId, request: ActionRequest) { + if request.action != Action::Click { + return; + } + let Some(view) = self.blitz.windows.get(&id) else { + return; + }; + // A click as a hand would make it, placed inside the safe area: + // blitz-shell's, as BlitzApplication carries one out. + let events = view.click_events(NodeId::from_u64(request.target_node.0)); + for e in events { + self.window_event(event_loop, id, e); + } + } +} + +impl App { + /// Find the element labelled `label` through UIKit's accessibility API, + /// from winit's view down, and call `accessibilityActivate` on it: what + /// VoiceOver does on a double tap. + fn activate(&self, label: &str) { + use objc2::msg_send; + use objc2::rc::Retained; + use objc2::runtime::AnyObject; + use objc2_foundation::{NSArray, NSString}; + + fn find(e: &AnyObject, label: &str, depth: usize) -> Option> { + let l: Option> = unsafe { msg_send![e, accessibilityLabel] }; + if l.is_some_and(|l| l.to_string() == label) { + return unsafe { Retained::retain(e as *const _ as *mut AnyObject) }; + } + if depth > 20 { + return None; + } + let kids: Option>> = + unsafe { msg_send![e, accessibilityElements] }; + for k in kids.iter().flat_map(|a| a.iter()) { + if let Some(found) = find(&k, label, depth + 1) { + return Some(found); + } + } + None + } + + for view in self.blitz.windows.values() { + let Ok(handle) = view.window.window_handle() else { + continue; + }; + let RawWindowHandle::UiKit(h) = handle.as_raw() else { + continue; + }; + let ui_view = unsafe { &*(h.ui_view.as_ptr() as *const AnyObject) }; + match find(ui_view, label, 0) { + Some(e) => { + let ok: bool = unsafe { msg_send![&*e, accessibilityActivate] }; + eprintln!("self-test: accessibilityActivate on {label:?} -> {ok}"); + } + None => eprintln!("self-test: no element labelled {label:?}"), + } + } + } +} + +impl ApplicationHandler for App { + fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) { + self.blitz.can_create_surfaces(event_loop); + if self.built { + return; + } + self.built = true; + let proxy = self.blitz.proxy.clone(); + for (id, view) in self.blitz.windows.iter_mut() { + view.downcast_doc_mut::().initial_build(); + view.request_redraw(); + let Ok(handle) = view.window.window_handle() else { + continue; + }; + let RawWindowHandle::UiKit(h) = handle.as_raw() else { + continue; + }; + // SAFETY: winit's view, alive for as long as its window. + self.adapter = Some(unsafe { + SubclassingAdapter::new( + h.ui_view.as_ptr(), + Activation(proxy.clone(), *id), + Actions(proxy.clone(), *id), + Deactivation, + ) + }); + eprintln!("accessibility adapter on {:?}", h.ui_view); + } + } + + fn destroy_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) { + self.blitz.destroy_surfaces(event_loop); + } + + fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, id: WindowId, event: WindowEvent) { + let redraw = matches!(event, WindowEvent::RedrawRequested); + self.blitz.window_event(event_loop, id, event); + if redraw { + self.update_tree(id); + } + } + + fn proxy_wake_up(&mut self, event_loop: &dyn ActiveEventLoop) { + while let Ok(event) = self.blitz.event_queue.try_recv() { + if let BlitzShellEvent::Embedder(data) = &event { + let ask = data + .downcast_ref::() + .and_then(|b| b.0.lock().unwrap().take()); + match ask { + Some(Ask::Tree(id)) => self.update_tree(id), + Some(Ask::Action(id, request)) => self.act(event_loop, id, request), + Some(Ask::Activate(label)) => self.activate(&label), + None => {} + } + continue; + } + self.blitz.handle_blitz_shell_event(event_loop, event); + } + } + + fn about_to_wait(&mut self, event_loop: &dyn ActiveEventLoop) { + self.blitz.about_to_wait(event_loop); + } +} + +fn main() { + let event_loop = EventLoop::new().expect("an event loop"); + event_loop.set_control_flow(ControlFlow::Wait); + let (proxy, queue) = BlitzShellProxy::new(event_loop.create_proxy()); + let mut blitz = BlitzApplication::new(proxy, queue); + let document = DioxusDocument::new(VirtualDom::new(Page), DocumentConfig::default()); + let attributes = WindowAttributes::default().with_title("BlitzA11y"); + blitz.add_window(WindowConfig::with_attributes( + Box::new(document), + Renderer::new(), + attributes, + )); + event_loop + .run_app(App { + blitz, + adapter: None, + built: false, + }) + .expect("the event loop"); +} diff --git a/examples/ios-a11y/uitest/Host/HostApp.swift b/examples/ios-a11y/uitest/Host/HostApp.swift new file mode 100644 index 0000000000..8befbec8da --- /dev/null +++ b/examples/ios-a11y/uitest/Host/HostApp.swift @@ -0,0 +1,6 @@ +import SwiftUI + +@main +struct HostApp: App { + var body: some Scene { WindowGroup { Text("UI test host") } } +} diff --git a/examples/ios-a11y/uitest/ReadTree/ReadTree.swift b/examples/ios-a11y/uitest/ReadTree/ReadTree.swift new file mode 100644 index 0000000000..8b5319c133 --- /dev/null +++ b/examples/ios-a11y/uitest/ReadTree/ReadTree.swift @@ -0,0 +1,28 @@ +import XCTest + +/// The spike's accessibility tree as XCUITest sees it: every descendant by +/// type, label and frame; then the button pressed by its accessibility frame. +final class ReadTree: XCTestCase { + func testTree() throws { + let app = XCUIApplication(bundleIdentifier: "org.diaryx.leaf.agent-blitz-a11y") + app.activate() + sleep(3) + dump(app, "BEFORE") + let button = app.buttons["Press me"] + print("BUTTON exists=\(button.exists)") + if button.exists { + print("BUTTON frame=\(button.frame)") + button.tap() + sleep(2) + dump(app, "AFTER") + } + } + + private func dump(_ app: XCUIApplication, _ tag: String) { + let all = app.descendants(matching: .any).allElementsBoundByIndex + print("\(tag) \(all.count) descendants") + for e in all { + print("\(tag) \(e.elementType.rawValue) label='\(e.label)' value='\(String(describing: e.value))' frame=\(e.frame)") + } + } +} diff --git a/examples/ios-a11y/uitest/project.yml b/examples/ios-a11y/uitest/project.yml new file mode 100644 index 0000000000..083f33cf62 --- /dev/null +++ b/examples/ios-a11y/uitest/project.yml @@ -0,0 +1,27 @@ +# Reads the spike's accessibility tree from outside, as VoiceOver would: a UI +# test that attaches to the running app by its bundle identifier. UI tests +# need a host app of their own; `Host` is an empty one. +name: ReadTree +options: + bundleIdPrefix: org.diaryx.leaf.agent-readtree + deploymentTarget: + iOS: "17.0" +targets: + Host: + type: application + platform: iOS + sources: [Host] + settings: + GENERATE_INFOPLIST_FILE: YES + INFOPLIST_KEY_UILaunchScreen_Generation: YES + CODE_SIGNING_ALLOWED: NO + ReadTree: + type: bundle.ui-testing + platform: iOS + sources: [ReadTree] + dependencies: + - target: Host + settings: + GENERATE_INFOPLIST_FILE: YES + CODE_SIGNING_ALLOWED: NO + TEST_TARGET_NAME: Host diff --git a/packages/blitz-shell/src/application.rs b/packages/blitz-shell/src/application.rs index 293dad2e3b..668509a66f 100644 --- a/packages/blitz-shell/src/application.rs +++ b/packages/blitz-shell/src/application.rs @@ -84,8 +84,12 @@ impl BlitzApplication { accesskit_xplat::WindowEvent::AccessibilityDeactivated => { // TODO } - accesskit_xplat::WindowEvent::ActionRequested(_req) => { - // TODO + accesskit_xplat::WindowEvent::ActionRequested(request) => { + // A click is carried out as a click, through the + // window's own events. + for event in window.accessibility_action_events(request) { + window.handle_winit_event(event); + } } } } diff --git a/packages/blitz-shell/src/window.rs b/packages/blitz-shell/src/window.rs index c569b92103..7734cce76a 100644 --- a/packages/blitz-shell/src/window.rs +++ b/packages/blitz-shell/src/window.rs @@ -524,6 +524,61 @@ impl View { self.accessibility.update_tree(&inner); } + /// The window events that click `node` as a hand would: the pointer + /// moved to the middle of its box, pressed and released there. Fed to + /// [`View::handle_winit_event`], or through an embedder's own handling + /// of window events, the node acts on them exactly as on a real click. + /// Empty for a node with no box. + pub fn click_events(&self, node: blitz_traits::node_id::NodeId) -> Vec { + let Some(rect) = self.doc.inner().get_client_bounding_rect(node) else { + return Vec::new(); + }; + // Window events are in the window's surface, and the page is laid out + // inside its safe area. + let scale = self.window.scale_factor(); + let insets = self.safe_area_insets; + let at = PhysicalPosition::new( + (rect.x + rect.width / 2.0) * scale + insets.left as f64, + (rect.y + rect.height / 2.0) * scale + insets.top as f64, + ); + let button = |state| WindowEvent::PointerButton { + device_id: None, + state, + position: at, + primary: true, + button: ButtonSource::Mouse(MouseButton::Left), + is_macos_activation_click: false, + }; + vec![ + WindowEvent::PointerMoved { + device_id: None, + position: at, + primary: true, + source: winit::event::PointerSource::Mouse, + }, + button(ElementState::Pressed), + button(ElementState::Released), + ] + } + + /// The window events that carry out what assistive tech asks of a node — + /// VoiceOver's activate, an agent's `AXPress` — where it is something a + /// pointer does: a click, as [`View::click_events`]. Empty for any other + /// action. [`crate::BlitzApplication`] carries them out itself; an + /// embedder with its own event loop feeds them through its own handling. + #[cfg(feature = "accessibility")] + pub fn accessibility_action_events( + &self, + request: &accesskit::ActionRequest, + ) -> Vec { + match request.action { + accesskit::Action::Click => self.click_events(blitz_traits::node_id::NodeId::from_u64( + request.target_node.0, + )), + _ => Vec::new(), + } + } + #[cfg(target_arch = "wasm32")] const RESIZE_DEBOUNCE_MS: u32 = 100; diff --git a/patches/winit-appkit/Cargo.toml b/patches/winit-appkit/Cargo.toml new file mode 100644 index 0000000000..b6c730467d --- /dev/null +++ b/patches/winit-appkit/Cargo.toml @@ -0,0 +1,207 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +rust-version = "1.86" +name = "winit-appkit" +version = "0.31.0-beta.3" +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Winit's Appkit / macOS backend" +documentation = "https://docs.rs/winit-appkit" +readme = "README.md" +license = "Apache-2.0" +repository = "https://github.com/rust-windowing/winit" + +[package.metadata.docs.rs] +features = ["serde"] +targets = [ + "aarch64-apple-darwin", + "x86_64-apple-darwin", +] + +[features] +private-apple-apis = [] +serde = [ + "dep:serde", + "bitflags/serde", + "smol_str/serde", + "dpi/serde", +] + +[lib] +name = "winit_appkit" +path = "src/lib.rs" + +[dependencies.bitflags] +version = "2" + +[dependencies.dpi] +version = "0.1.2" + +[dependencies.rwh_06] +version = "0.6" +features = ["std"] +package = "raw-window-handle" + +[dependencies.serde] +version = "1" +features = ["serde_derive"] +optional = true + +[dependencies.smol_str] +version = "0.3" + +[dependencies.tracing] +version = "0.1.40" +default-features = false + +[dependencies.winit-core] +version = "=0.31.0-beta.3" + +[dev-dependencies] + +[target.'cfg(target_vendor = "apple")'.dependencies.block2] +version = "0.6.1" + +[target.'cfg(target_vendor = "apple")'.dependencies.dispatch2] +version = "0.3.0" +features = [ + "std", + "objc2", + "std", + "objc2", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2] +version = "0.6.1" +features = ["relax-sign-encoding"] + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-app-kit] +version = "0.3.2" +features = [ + "std", + "objc2-core-foundation", + "NSAppearance", + "NSApplication", + "NSBitmapImageRep", + "NSButton", + "NSColor", + "NSControl", + "NSCursor", + "NSDragging", + "NSDraggingItem", + "NSDraggingSession", + "NSEvent", + "NSGraphics", + "NSGraphicsContext", + "NSImage", + "NSImageRep", + "NSMenu", + "NSMenuItem", + "NSOpenGLView", + "NSPanel", + "NSPasteboard", + "NSPasteboardItem", + "NSResponder", + "NSRunningApplication", + "NSScreen", + "NSTextInputClient", + "NSTextInputContext", + "NSTrackingArea", + "NSToolbar", + "NSView", + "NSVisualEffectView", + "NSWindow", + "NSWindowScripting", + "NSWindowTabGroup", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-foundation] +version = "0.3.2" +features = [ + "std", + "block2", + "CFBase", + "CFCGTypes", + "CFData", + "CFRunLoop", + "CFString", + "CFUUID", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-graphics] +version = "0.3.2" +features = [ + "std", + "libc", + "CGDirectDisplay", + "CGDisplayConfiguration", + "CGDisplayFade", + "CGError", + "CGRemoteOperation", + "CGWindowLevel", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-video] +version = "0.3.2" +features = [ + "std", + "objc2-core-graphics", + "CVBase", + "CVReturn", + "CVDisplayLink", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-foundation] +version = "0.3.2" +features = [ + "std", + "block2", + "objc2-core-foundation", + "NSArray", + "NSAttributedString", + "NSData", + "NSDictionary", + "NSDistributedNotificationCenter", + "NSEnumerator", + "NSGeometry", + "NSKeyValueObserving", + "NSNotification", + "NSObjCRuntime", + "NSOperation", + "NSPathUtilities", + "NSProcessInfo", + "NSRunLoop", + "NSString", + "NSThread", + "NSValue", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.winit-common] +version = "=0.31.0-beta.3" +features = [ + "core-foundation", + "event-handler", + "foundation", + "positioner", +] diff --git a/patches/winit-appkit/LICENSE b/patches/winit-appkit/LICENSE new file mode 100644 index 0000000000..ad410e1130 --- /dev/null +++ b/patches/winit-appkit/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/patches/winit-appkit/PATCH.md b/patches/winit-appkit/PATCH.md new file mode 100644 index 0000000000..7be80fd29e --- /dev/null +++ b/patches/winit-appkit/PATCH.md @@ -0,0 +1,64 @@ +# winit-appkit 0.31.0-beta.3, patched + +The crate dioxus-native pins, patched for leaf's Mac app and kept here, in +diaryx-org's Blitz fork, beside the Blitz it is built with. It came from +diaryx-org/leaf's `patches/winit-appkit` as of leaf's 69e913a6; its history, +vendored unmodified and then patched, is there (`git log -p -- +patches/winit-appkit`, and before that `apps/leaf-dioxus/patches/` and +`spikes/dioxus-widget/native-alpha/patches/`). Every change is marked +`leaf patch` in the source. + +Consumers take it with `[patch.crates-io]` in their root manifest, from this +repository's branch the rest of their Blitz comes from, `{ git = +"https://github.com/diaryx-org/blitz", branch = "leaf" }` — cargo finds the +crate by name in the repository. + +## What was wrong + +winit's macOS view implements `NSTextInputClient`, but answers none of its +questions about the document: + +- `selectedRange` is always `{NSNotFound, 0}`, and + `attributedSubstringForProposedRange:actualRange:` always `nil`; +- the `replacementRange` of `insertText:` and `setMarkedText:` is ignored + (two `TODO`s: "requires changing the event to report surrounding text" — + which winit-core 0.31 since did, with `ImeRequestData::surrounding_text` + and `Ime::DeleteSurrounding`, but the AppKit backend never used them); +- `insertText:` reports text only when it ends a composition, on the + assumption that anything else arrives as a `KeyboardInput`. + +Two macOS text features fall through those gaps: + +- **Press-and-hold accents.** The input system needs to read the character + before the caret, marks it, and replaces it with the accent chosen. With + no text to read it never opens the menu, and the held key just repeats. +- **The emoji and symbols picker** (and dictation, and services) inserts with + `insertText:` and no keystroke at all, so its text was dropped. + +## What the patch does + +- Keeps the text around the caret that the application reports with + `ImeRequestData::with_surrounding_text` (`window_delegate.rs`), and answers + `selectedRange` and `attributedSubstringForProposedRange:` from it. +- Resolves a `replacementRange` against that text and reports it as + `Ime::DeleteSurrounding` relative to the caret — before the replacement's + `Ime::Commit` in `insertText:`, and before the preedit in `setMarkedText:` + (press-and-hold marks the letter it is offering accents for). +- Reports `insertText:` from outside `keyDown:` as `Ime::Commit`. +- Drops a key *repeat* the input system swallowed — `interpretKeyEvents:` + reached none of insert, mark or command — instead of forwarding it as + `KeyboardInput`: that is press-and-hold holding the key under its menu. + +An application that never asks for the surrounding-text capability gets +exactly the old behaviour, except that picker and dictation text now arrives +as `Ime::Commit`, and that a swallowed repeat is no longer forwarded. + +## Upstream + +Prepared, not sent: `upstream/PR.md` has the PR's text and what to do before +opening it, and `upstream/0001-*.patch` the change redone against winit's +`master` without the leaf-only tracing. Adam approves sending it. When it +lands in a winit release that dioxus-native takes, this vendored copy and the +`[patch]` that uses it go. The plan for the Dioxus work's other winit patch +(iOS, UIScene) is the proposal "A shared, patched winit for the Dioxus work" +in leaf's `docs/proposals/`. diff --git a/patches/winit-appkit/README.md b/patches/winit-appkit/README.md new file mode 100644 index 0000000000..affc454a4e --- /dev/null +++ b/patches/winit-appkit/README.md @@ -0,0 +1,79 @@ +# winit - Cross-platform window creation and management in Rust + +[![Crates.io](https://img.shields.io/crates/v/winit.svg)](https://crates.io/crates/winit) +[![Docs.rs](https://docs.rs/winit/badge.svg)](https://docs.rs/winit) +[![UNSTABLE docs](https://img.shields.io/github/actions/workflow/status/rust-windowing/winit/docs.yml?branch=master&label=UNSTABLE%20docs +)](https://rust-windowing.github.io/winit/winit/index.html) +[![CI Status](https://github.com/rust-windowing/winit/workflows/CI/badge.svg)](https://github.com/rust-windowing/winit/actions) + +```toml +[dependencies] +winit = "0.31.0-beta.3" +``` + +## [Documentation](https://docs.rs/winit) + +For features _within_ the scope of winit, see [FEATURES.md](FEATURES.md). + +For features _outside_ the scope of winit, see [Are we GUI Yet?](https://areweguiyet.com/) and [Are we game yet?](https://arewegameyet.rs/), depending on what kind of project you're looking to do. + +## Contact Us + +Join us in our [![Matrix](https://img.shields.io/badge/Matrix-%23rust--windowing%3Amatrix.org-blueviolet.svg)](https://matrix.to/#/#rust-windowing:matrix.org) room. + +The maintainers have a meeting every friday at UTC 15. The meeting notes can be found [here](https://hackmd.io/@winit-meetings). + +## Usage + +Winit is a window creation and management library. It can create windows and lets you handle +events (for example: the window being resized, a key being pressed, a mouse movement, etc.) +produced by the window. + +Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to +show something on the window you need to use the platform-specific getters provided by winit, or +another library. + +## CONTRIBUTING + +For contributing guidelines see [CONTRIBUTING.md](./CONTRIBUTING.md). + +## MSRV Policy + +This crate's Minimum Supported Rust Version (MSRV) is **1.86**. Changes to +the MSRV will be accompanied by a minor version bump. + +As a **tentative** policy, the upper bound of the MSRV is given by the following +formula: + +``` +min(sid, stable - 3) +``` + +Where `sid` is the current version of `rustc` provided by [Debian Sid], and +`stable` is the latest stable version of Rust. This bound may be broken in case of a major ecosystem shift or a security vulnerability. + +[Debian Sid]: https://packages.debian.org/sid/rustc + +An exception is made for the Android platform, where a higher Rust version +must be used for certain Android features. In this case, the MSRV will be +capped at the latest stable version of Rust minus three. This inconsistency is +not reflected in Cargo metadata, as it is not powerful enough to expose this +restriction. + +Redox OS is also not covered by this MSRV policy, as it requires a Rust nightly +toolchain to compile. + +All crates in the [`rust-windowing`] organizations have the +same MSRV policy. + +[`rust-windowing`]: https://github.com/rust-windowing + +### Platform-specific usage + +Check out the [`winit::platform`](https://docs.rs/winit/latest/winit/platform/index.html) module for platform-specific usage. + +### Repository License + +Note that the license in `LICENSE` doesn't apply in full to the DPI package [./dpi](./dpi). +Full details can be found in that folder's README. + diff --git a/patches/winit-appkit/src/app.rs b/patches/winit-appkit/src/app.rs new file mode 100644 index 0000000000..43627eace9 --- /dev/null +++ b/patches/winit-appkit/src/app.rs @@ -0,0 +1,189 @@ +#![allow(clippy::unnecessary_cast)] + +use std::cell::Cell; +use std::rc::Rc; +use std::{mem, ptr}; + +use dispatch2::MainThreadBound; +use objc2::runtime::{Imp, Sel}; +use objc2::sel; +use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType}; +use objc2_foundation::MainThreadMarker; +use tracing::trace_span; +use winit_core::event::{DeviceEvent, ElementState}; + +use super::app_state::AppState; + +type SendEvent = extern "C-unwind" fn(&NSApplication, Sel, &NSEvent); + +static ORIGINAL: MainThreadBound>> = { + // SAFETY: Creating in a `const` context, where there is no concept of the main thread. + MainThreadBound::new(Cell::new(None), unsafe { MainThreadMarker::new_unchecked() }) +}; + +extern "C-unwind" fn send_event(app: &NSApplication, sel: Sel, event: &NSEvent) { + // This can be a bit noisy, since `event` is fairly large. Note that you can use + // `RUST_LOG='trace,winit_appkit::app=warn'` if you're debugging and want TRACE-level logs but + // not this. + let _entered = trace_span!("sendEvent:", ?event).entered(); + let mtm = MainThreadMarker::from(app); + + // Normally, holding Cmd + any key never sends us a `keyUp` event for that key. + // Overriding `sendEvent:` fixes that. (https://stackoverflow.com/a/15294196) + // Fun fact: Firefox still has this bug! (https://bugzilla.mozilla.org/show_bug.cgi?id=1299553) + // + // For posterity, there are some undocumented event types + // (https://github.com/servo/cocoa-rs/issues/155) + // but that doesn't really matter here. + let event_type = event.r#type(); + let modifier_flags = event.modifierFlags(); + if event_type == NSEventType::KeyUp && modifier_flags.contains(NSEventModifierFlags::Command) { + if let Some(key_window) = app.keyWindow() { + key_window.sendEvent(event); + } + return; + } + + // Events are generally scoped to the window level, so the best way + // to get device events is to listen for them on NSApplication. + let app_state = AppState::get(mtm); + maybe_dispatch_device_event(&app_state, event); + + let original = ORIGINAL.get(mtm).get().expect("no existing sendEvent: handler set"); + original(app, sel, event) +} + +/// Override the [`sendEvent:`][NSApplication::sendEvent] method on the given application class. +/// +/// The previous implementation created a subclass of [`NSApplication`], however we would like to +/// give the user full control over their `NSApplication`, so we override the method here using +/// method swizzling instead. +/// +/// This _should_ also allow two versions of Winit to exist in the same application. +/// +/// See the following links for more info on method swizzling: +/// - +/// - +/// - +/// +/// NOTE: This function assumes that the passed in application object is the one returned from +/// [`NSApplication::sharedApplication`], i.e. the one and only global shared application object. +/// For testing though, we allow it to be a different object. +pub(crate) fn override_send_event(global_app: &NSApplication) { + let mtm = MainThreadMarker::from(global_app); + let class = global_app.class(); + + let method = + class.instance_method(sel!(sendEvent:)).expect("NSApplication must have sendEvent: method"); + + // SAFETY: Converting our `sendEvent:` implementation to an IMP. + let overridden = unsafe { mem::transmute::(send_event) }; + + // If we've already overridden the method, don't do anything. + if ptr::fn_addr_eq(overridden, method.implementation()) { + return; + } + + // SAFETY: Our implementation has: + // 1. The same signature as `sendEvent:`. + // 2. Does not impose extra safety requirements on callers. + let original = unsafe { method.set_implementation(overridden) }; + + // SAFETY: This is the actual signature of `sendEvent:`. + let original = unsafe { mem::transmute::(original) }; + + // NOTE: If NSApplication was safe to use from multiple threads, then this would potentially be + // a (checked) race-condition, since one could call `sendEvent:` before the original had been + // stored here. + // + // It is only usable from the main thread, however, so we're good! + ORIGINAL.get(mtm).set(Some(original)); +} + +fn maybe_dispatch_device_event(app_state: &Rc, event: &NSEvent) { + let event_type = event.r#type(); + #[allow(non_upper_case_globals)] + match event_type { + NSEventType::MouseMoved + | NSEventType::LeftMouseDragged + | NSEventType::OtherMouseDragged + | NSEventType::RightMouseDragged => { + let delta_x = event.deltaX() as f64; + let delta_y = event.deltaY() as f64; + + if delta_x != 0.0 || delta_y != 0.0 { + app_state.maybe_queue_with_handler(move |app, event_loop| { + app.device_event(event_loop, None, DeviceEvent::PointerMotion { + delta: (delta_x, delta_y), + }); + }); + } + }, + NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => { + let button = event.buttonNumber() as u32; + app_state.maybe_queue_with_handler(move |app, event_loop| { + app.device_event(event_loop, None, DeviceEvent::Button { + button, + state: ElementState::Pressed, + }); + }); + }, + NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => { + let button = event.buttonNumber() as u32; + app_state.maybe_queue_with_handler(move |app, event_loop| { + app.device_event(event_loop, None, DeviceEvent::Button { + button, + state: ElementState::Released, + }); + }); + }, + _ => (), + } +} + +#[cfg(test)] +mod tests { + use objc2::rc::Retained; + use objc2::{ClassType, define_class, msg_send}; + use objc2_app_kit::NSResponder; + use objc2_foundation::NSObject; + + use super::*; + + #[test] + fn test_override() { + // FIXME(madsmtm): Ensure this always runs (maybe use cargo-nextest or `--test-threads=1`?) + let Some(mtm) = MainThreadMarker::new() else { return }; + + // Create a new application, without making it the shared application. + let app = NSApplication::new(mtm); + override_send_event(&app); + // Test calling twice works. + override_send_event(&app); + + // FIXME(madsmtm): Can't test this yet, need some way to mock AppState. + // let event = super::super::event::dummy_event().unwrap(); + // app.sendEvent(&event) + } + + #[test] + fn test_custom_class() { + let Some(_mtm) = MainThreadMarker::new() else { return }; + + define_class!( + #[unsafe(super(NSApplication, NSResponder, NSObject))] + #[name = "TestApplication"] + pub(super) struct TestApplication; + + impl TestApplication { + #[unsafe(method(sendEvent:))] + fn send_event(&self, _event: &NSEvent) { + todo!() + } + } + ); + + let app: Retained = unsafe { msg_send![TestApplication::class(), new] }; + override_send_event(&app); + } +} diff --git a/patches/winit-appkit/src/app_state.rs b/patches/winit-appkit/src/app_state.rs new file mode 100644 index 0000000000..4316ff5181 --- /dev/null +++ b/patches/winit-appkit/src/app_state.rs @@ -0,0 +1,435 @@ +use std::cell::{Cell, OnceCell, RefCell}; +use std::collections::HashMap; +use std::mem; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Instant; + +use dispatch2::MainThreadBound; +use objc2::MainThreadMarker; +use objc2::rc::{Retained, Weak}; +use objc2_app_kit::{ + NSApplication, NSApplicationActivationPolicy, NSDragOperation, NSRunningApplication, +}; +use objc2_foundation::NSNotification; +use winit_common::core_foundation::{EventLoopProxy, MainRunLoop}; +use winit_common::event_handler::EventHandler; +use winit_core::application::ApplicationHandler; +use winit_core::data_transfer::DataTransferId; +use winit_core::event::{StartCause, WindowEvent}; +use winit_core::event_loop::{ControlFlow, DndAction}; +use winit_core::window::WindowId; + +use super::event_loop::{ActiveEventLoop, notify_windows_of_exit, stop_app_immediately}; +use super::menu; +use super::observer::EventLoopWaker; +use crate::dnd::Pasteboards; +use crate::window_delegate::WindowDelegate; + +#[derive(Debug)] +pub(super) struct AppState { + mtm: MainThreadMarker, + drag_state: RefCell>, + pasteboards: Pasteboards, + activation_policy: Option, + default_menu: bool, + activate_ignoring_other_apps: bool, + run_loop: MainRunLoop, + event_loop_proxy: Arc, + event_handler: EventHandler, + stop_on_launch: Cell, + stop_before_wait: Cell, + stop_after_wait: Cell, + stop_on_redraw: Cell, + /// Whether `applicationDidFinishLaunching:` has been run or not. + is_launched: Cell, + /// Whether an `EventLoop` is currently running. + is_running: Cell, + /// Whether the user has requested the event loop to exit. + exit: Cell, + control_flow: Cell, + waker: RefCell, + start_time: Cell>, + wait_timeout: Cell>, + pending_redraw: RefCell>, + windows: RefCell>>>, + // NOTE: This is strongly referenced by our `NSWindowDelegate` and our `NSView` subclass, and + // as such should be careful to not add fields that, in turn, strongly reference those. +} + +#[derive(Debug)] +pub(crate) struct DragState { + pub id: DataTransferId, + pub valid_actions: Vec, +} + +// SAFETY: Creating `MainThreadBound` in a `const` context, where there is no concept of the +// main thread. +static GLOBAL: MainThreadBound>> = + MainThreadBound::new(OnceCell::new(), unsafe { MainThreadMarker::new_unchecked() }); + +impl AppState { + pub(super) fn setup_global( + mtm: MainThreadMarker, + activation_policy: Option, + default_menu: bool, + activate_ignoring_other_apps: bool, + ) -> Option> { + let event_loop_proxy = Arc::new(EventLoopProxy::new(mtm, move || { + Self::get(mtm).with_handler(|app, event_loop| app.proxy_wake_up(event_loop)); + })); + + let this = Rc::new(Self { + mtm, + pasteboards: Default::default(), + drag_state: Default::default(), + activation_policy, + default_menu, + activate_ignoring_other_apps, + run_loop: MainRunLoop::get(mtm), + event_loop_proxy, + event_handler: EventHandler::new(), + stop_on_launch: Cell::new(false), + stop_before_wait: Cell::new(false), + stop_after_wait: Cell::new(false), + stop_on_redraw: Cell::new(false), + is_launched: Cell::new(false), + is_running: Cell::new(false), + exit: Cell::new(false), + control_flow: Cell::new(ControlFlow::default()), + waker: RefCell::new(EventLoopWaker::new()), + start_time: Cell::new(None), + wait_timeout: Cell::new(None), + windows: Default::default(), + pending_redraw: RefCell::new(vec![]), + }); + + GLOBAL.get(mtm).set(this.clone()).ok().and(Some(this)) + } + + pub fn get(mtm: MainThreadMarker) -> Rc { + GLOBAL + .get(mtm) + .get() + .expect("tried to get application state before it was registered") + .clone() + } + + pub fn with_window_delegate_on_main(&self, id: WindowId, func: F) -> Option + where + F: FnOnce(Retained) -> R + Send, + R: Send, + { + self.windows.borrow_mut().get(&id)?.get_on_main(move |delegate| delegate.load().map(func)) + } + + pub fn register_window(&self, window: &Retained, mtm: MainThreadMarker) { + let id = window.id(); + let window_downgraded = Weak::from_retained(window); + self.windows.borrow_mut().insert(id, MainThreadBound::new(window_downgraded, mtm)); + } + + // NOTE: This notification will, globally, only be emitted once, + // no matter how many `EventLoop`s the user creates. + pub fn did_finish_launching(self: &Rc, _notification: &NSNotification) { + self.is_launched.set(true); + + let app = NSApplication::sharedApplication(self.mtm); + // We need to delay setting the activation policy and activating the app + // until `applicationDidFinishLaunching` has been called. Otherwise the + // menu bar is initially unresponsive on macOS 10.15. + if let Some(activation_policy) = self.activation_policy { + app.setActivationPolicy(activation_policy); + } else { + // If no activation policy is explicitly provided, and the application + // is bundled, do not set the activation policy at all, to allow the + // package manifest to define the behavior via LSUIElement. + // + // See: + // - https://github.com/rust-windowing/winit/issues/261 + // - https://github.com/rust-windowing/winit/issues/3958 + let is_bundled = + NSRunningApplication::currentApplication().bundleIdentifier().is_some(); + if !is_bundled { + app.setActivationPolicy(NSApplicationActivationPolicy::Regular); + } + } + + #[allow(deprecated)] + app.activateIgnoringOtherApps(self.activate_ignoring_other_apps); + + if self.default_menu { + // The menubar initialization should be before the `NewEvents` event, to allow + // overriding of the default menu even if it's created + menu::initialize(&app); + } + + self.waker.borrow_mut().start(); + + self.set_is_running(true); + self.dispatch_init_events(); + + // If the application is being launched via `EventLoop::pump_app_events()` then we'll + // want to stop the app once it is launched (and return to the external loop) + // + // In this case we still want to consider Winit's `EventLoop` to be "running", + // so we call `start_running()` above. + if self.stop_on_launch.get() { + // NOTE: the original idea had been to only stop the underlying `RunLoop` + // for the app but that didn't work as expected (`-[NSApplication run]` + // effectively ignored the attempt to stop the RunLoop and re-started it). + // + // So we return from `pump_events` by stopping the application. + let app = NSApplication::sharedApplication(self.mtm); + stop_app_immediately(&app); + } + } + + pub fn will_terminate(self: &Rc, _notification: &NSNotification) { + let app = NSApplication::sharedApplication(self.mtm); + notify_windows_of_exit(&app); + self.event_handler.terminate(); + self.internal_exit(); + } + + /// Place the event handler in the application state for the duration + /// of the given closure. + pub fn set_event_handler( + &self, + handler: impl ApplicationHandler, + closure: impl FnOnce() -> R, + ) -> R { + self.event_handler.set(Box::new(handler), closure) + } + + pub fn event_loop_proxy(&self) -> &Arc { + &self.event_loop_proxy + } + + /// If `pump_events` is called to progress the event loop then we + /// bootstrap the event loop via `-[NSApplication run]` but will use + /// `CFRunLoopRunInMode` for subsequent calls to `pump_events`. + pub fn set_stop_on_launch(&self) { + self.stop_on_launch.set(true); + } + + pub fn set_stop_before_wait(&self, value: bool) { + self.stop_before_wait.set(value) + } + + pub fn set_stop_after_wait(&self, value: bool) { + self.stop_after_wait.set(value) + } + + pub fn set_stop_on_redraw(&self, value: bool) { + self.stop_on_redraw.set(value) + } + + pub fn set_wait_timeout(&self, value: Option) { + self.wait_timeout.set(value) + } + + /// Clears the `running` state and resets the `control_flow` state when an `EventLoop` exits. + /// + /// NOTE: that if the `NSApplication` has been launched then that state is preserved, + /// and we won't need to re-launch the app if subsequent EventLoops are run. + pub fn internal_exit(self: &Rc) { + self.set_is_running(false); + self.set_stop_on_redraw(false); + self.set_stop_before_wait(false); + self.set_stop_after_wait(false); + self.set_wait_timeout(None); + } + + pub fn is_launched(&self) -> bool { + self.is_launched.get() + } + + pub fn set_is_running(&self, value: bool) { + self.is_running.set(value) + } + + pub fn is_running(&self) -> bool { + self.is_running.get() + } + + pub fn exit(&self) { + self.exit.set(true) + } + + pub fn clear_exit(&self) { + self.exit.set(false) + } + + pub fn exiting(&self) -> bool { + self.exit.get() + } + + pub fn set_control_flow(&self, value: ControlFlow) { + self.control_flow.set(value) + } + + pub(super) fn is_handling_event(&self) -> bool { + self.event_handler.in_use() + } + + pub fn control_flow(&self) -> ControlFlow { + self.control_flow.get() + } + + pub fn handle_redraw(self: &Rc, window_id: WindowId) { + // Redraw request might come out of order from the OS. + // -> Don't go back into the event handler when our callstack originates from there + if !self.event_handler.in_use() { + self.with_handler(|app, event_loop| { + app.window_event(event_loop, window_id, WindowEvent::RedrawRequested); + }); + + // `pump_events` will request to stop immediately _after_ dispatching RedrawRequested + // events as a way to ensure that `pump_events` can't block an external loop + // indefinitely + if self.stop_on_redraw.get() { + let app = NSApplication::sharedApplication(self.mtm); + stop_app_immediately(&app); + } + } + } + + pub fn queue_redraw(&self, window_id: WindowId) { + let mut pending_redraw = self.pending_redraw.borrow_mut(); + if !pending_redraw.contains(&window_id) { + pending_redraw.push(window_id); + } + self.run_loop.wake_up(); + } + + #[track_caller] + pub fn maybe_queue_with_handler( + self: &Rc, + callback: impl FnOnce(&mut dyn ApplicationHandler, &ActiveEventLoop) + 'static, + ) { + // Most programmer actions in AppKit (e.g. change window fullscreen, set focused, etc.) + // result in an event being queued, and applied at a later point. + // + // However, it is not documented which actions do this, and which ones are done immediately, + // so to make sure that we don't encounter re-entrancy issues, we first check if we're + // currently handling another event, and if we are, we queue the event instead. + if !self.event_handler.in_use() { + self.with_handler(callback); + } else { + tracing::debug!("had to queue event since another is currently being handled"); + let this = Rc::clone(self); + self.run_loop.queue_closure(move || { + this.with_handler(callback); + }); + } + } + + #[track_caller] + fn with_handler( + self: &Rc, + callback: impl FnOnce(&mut dyn ApplicationHandler, &ActiveEventLoop), + ) { + let event_loop = ActiveEventLoop { app_state: Rc::clone(self), mtm: self.mtm }; + self.event_handler.handle(|app| callback(app, &event_loop)); + } + + /// dispatch `NewEvents(Init)` + `Resumed` + pub fn dispatch_init_events(self: &Rc) { + self.with_handler(|app, event_loop| app.new_events(event_loop, StartCause::Init)); + // NB: For consistency all platforms must call `can_create_surfaces` even though macOS + // applications don't themselves have a formal surface destroy/create lifecycle. + self.with_handler(|app, event_loop| app.can_create_surfaces(event_loop)); + } + + // Called by RunLoopObserver after finishing waiting for new events + pub fn wakeup(self: &Rc) { + // Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779 + // (we have registered to observe all modes, including modal event loops). + if !self.event_handler.ready() || !self.is_running() { + return; + } + + if self.stop_after_wait.get() { + let app = NSApplication::sharedApplication(self.mtm); + stop_app_immediately(&app); + } + + let start = self.start_time.get().unwrap(); + let cause = match self.control_flow() { + ControlFlow::Poll => StartCause::Poll, + ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None }, + ControlFlow::WaitUntil(requested_resume) => { + if Instant::now() >= requested_resume { + StartCause::ResumeTimeReached { start, requested_resume } + } else { + StartCause::WaitCancelled { start, requested_resume: Some(requested_resume) } + } + }, + }; + + self.with_handler(|app, event_loop| app.new_events(event_loop, cause)); + } + + // Called by RunLoopObserver before waiting for new events + pub fn cleared(self: &Rc) { + // Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779 + // (we have registered to observe all modes, including modal event loops). + if !self.event_handler.ready() || !self.is_running() { + return; + } + + let redraw = mem::take(&mut *self.pending_redraw.borrow_mut()); + for window_id in redraw { + self.with_handler(|app, event_loop| { + app.window_event(event_loop, window_id, WindowEvent::RedrawRequested); + }); + } + self.with_handler(|app, event_loop| { + app.about_to_wait(event_loop); + }); + + if self.exiting() { + let app = NSApplication::sharedApplication(self.mtm); + stop_app_immediately(&app); + notify_windows_of_exit(&app); + } + + if self.stop_before_wait.get() { + let app = NSApplication::sharedApplication(self.mtm); + stop_app_immediately(&app); + } + self.start_time.set(Some(Instant::now())); + let wait_timeout = self.wait_timeout.get(); // configured by pump_events + let app_timeout = match self.control_flow() { + ControlFlow::Wait => None, + ControlFlow::Poll => Some(Instant::now()), + ControlFlow::WaitUntil(instant) => Some(instant), + }; + self.waker.borrow_mut().start_at(min_timeout(wait_timeout, app_timeout)); + } + + pub fn pasteboards(&self) -> &Pasteboards { + &self.pasteboards + } + + pub fn drag_state(&self) -> &RefCell> { + &self.drag_state + } + + pub(crate) fn proposed_drag_action( + &self, + source_operations: NSDragOperation, + ) -> Option { + self.drag_state().borrow().as_ref().and_then(|drag_state| { + crate::dnd::preferred_drag_operation(source_operations, &drag_state.valid_actions) + }) + } +} + +/// Returns the minimum `Option`, taking into account that `None` +/// equates to an infinite timeout, not a zero timeout (so can't just use +/// `Option::min`) +fn min_timeout(a: Option, b: Option) -> Option { + a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout)))) +} diff --git a/patches/winit-appkit/src/cursor.rs b/patches/winit-appkit/src/cursor.rs new file mode 100644 index 0000000000..c41c3e9b23 --- /dev/null +++ b/patches/winit-appkit/src/cursor.rs @@ -0,0 +1,401 @@ +use std::ffi::c_uchar; +use std::slice; +use std::sync::OnceLock; + +use objc2::rc::Retained; +use objc2::runtime::Sel; +use objc2::{AllocAnyThread, ClassType, available, msg_send, sel}; +use objc2_app_kit::{ + NSBitmapImageRep, NSCursor, NSCursorFrameResizeDirections, NSCursorFrameResizePosition, + NSDeviceRGBColorSpace, NSImage, +}; +use objc2_foundation::{ + NSData, NSDictionary, NSNumber, NSObject, NSPoint, NSSize, NSString, ns_string, +}; +use winit_core::cursor::{CursorIcon, CursorImage, CustomCursorProvider, CustomCursorSource}; +use winit_core::error::{NotSupportedError, RequestError}; +use winit_core::icon::{Icon, RgbaIcon}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct CustomCursor(pub(crate) Retained); + +impl CustomCursorProvider for CustomCursor { + fn is_animated(&self) -> bool { + false + } +} + +// SAFETY: NSCursor is immutable and thread-safe +// TODO(madsmtm): Put this logic in objc2-app-kit itself +unsafe impl Send for CustomCursor {} +unsafe impl Sync for CustomCursor {} + +impl CustomCursor { + pub(crate) fn new(cursor: CustomCursorSource) -> Result { + let cursor = match cursor { + CustomCursorSource::Image(cursor_image) => cursor_image, + _ => { + return Err(NotSupportedError::new("unsupported cursor kind").into()); + }, + }; + + cursor_from_image(&cursor).map(Self) + } +} + +pub(crate) fn image_from_icon(icon: &Icon) -> Result, RequestError> { + let rgba_icon = icon + .cast_ref::() + .ok_or(NotSupportedError::new("Only RGBA icons can be converted to `NSImage`"))?; + + let width = rgba_icon.width(); + let height = rgba_icon.height(); + + let bitmap = unsafe { + NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel( + NSBitmapImageRep::alloc(), + std::ptr::null_mut::<*mut c_uchar>(), + width as isize, + height as isize, + 8, + 4, + true, + false, + NSDeviceRGBColorSpace, + width as isize * 4, + 32, + ) + }.ok_or_else(|| os_error!("Initializing the `NSBitmapImageRep` failed"))?; + + let bitmap_data = + unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), rgba_icon.buffer().len()) }; + bitmap_data.copy_from_slice(rgba_icon.buffer()); + + let image = NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into())); + image.addRepresentation(&bitmap); + + Ok(image) +} + +pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Result, RequestError> { + let width = cursor.width(); + let height = cursor.height(); + + let bitmap = unsafe { + NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel( + NSBitmapImageRep::alloc(), + std::ptr::null_mut::<*mut c_uchar>(), + width as isize, + height as isize, + 8, + 4, + true, + false, + NSDeviceRGBColorSpace, + width as isize * 4, + 32, + ) + }.ok_or_else(|| os_error!("parent view should be installed in a window"))?; + let bitmap_data = + unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), cursor.buffer().len()) }; + bitmap_data.copy_from_slice(cursor.buffer()); + + let image = NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into())); + image.addRepresentation(&bitmap); + + let hotspot = NSPoint::new(cursor.hotspot_x() as f64, cursor.hotspot_y() as f64); + + Ok(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot)) +} + +pub(crate) fn default_cursor() -> Retained { + NSCursor::arrowCursor() +} + +unsafe fn try_cursor_from_selector(sel: Sel) -> Option> { + let cls = NSCursor::class(); + if unsafe { msg_send![cls, respondsToSelector: sel] } { + let cursor: Retained = unsafe { msg_send![cls, performSelector: sel] }; + Some(cursor) + } else { + tracing::warn!("cursor `{sel}` appears to be invalid"); + None + } +} + +macro_rules! def_undocumented_cursor { + {$( + $(#[$($m:meta)*])* + fn $name:ident(); + )*} => {$( + $(#[$($m)*])* + #[allow(non_snake_case)] + fn $name() -> Retained { + unsafe { try_cursor_from_selector(sel!($name)).unwrap_or_else(|| default_cursor()) } + } + )*}; +} + +def_undocumented_cursor!( + // Undocumented cursors: https://stackoverflow.com/a/46635398/5435443 + fn _helpCursor(); + fn _zoomInCursor(); + fn _zoomOutCursor(); + fn _windowResizeNorthEastCursor(); + fn _windowResizeNorthWestCursor(); + fn _windowResizeSouthEastCursor(); + fn _windowResizeSouthWestCursor(); + fn _windowResizeNorthEastSouthWestCursor(); + fn _windowResizeNorthWestSouthEastCursor(); + + // While these two are available, the former just loads a white arrow, + // and the latter loads an ugly deflated beachball! + // pub fn _moveCursor(); + // pub fn _waitCursor(); + + // An even more undocumented cursor... + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=522349 + fn busyButClickableCursor(); +); + +// Note that loading `busybutclickable` with this code won't animate +// the frames; instead you'll just get them all in a column. +unsafe fn load_webkit_cursor(name: &NSString) -> Retained { + // Snatch a cursor from WebKit; They fit the style of the native + // cursors, and will seem completely standard to macOS users. + // + // https://stackoverflow.com/a/21786835/5435443 + let root = ns_string!( + "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/\ + HIServices.framework/Versions/A/Resources/cursors" + ); + let cursor_path = root.stringByAppendingPathComponent(name); + + let pdf_path = cursor_path.stringByAppendingPathComponent(ns_string!("cursor.pdf")); + let image = NSImage::initByReferencingFile(NSImage::alloc(), &pdf_path).unwrap(); + + // TODO: Handle PLists better + let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist")); + #[allow(deprecated)] + let info: Retained> = + unsafe { NSDictionary::dictionaryWithContentsOfFile(&info_path) }.unwrap(); + let mut x = 0.0; + if let Some(n) = info.objectForKey(ns_string!("hotx")) { + if let Ok(n) = n.downcast::() { + x = n.as_cgfloat(); + } + } + let mut y = 0.0; + if let Some(n) = info.objectForKey(ns_string!("hoty")) { + if let Ok(n) = n.downcast::() { + y = n.as_cgfloat(); + } + } + + let hotspot = NSPoint::new(x, y); + NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot) +} + +fn webkit_move() -> Retained { + unsafe { load_webkit_cursor(ns_string!("move")) } +} + +fn webkit_cell() -> Retained { + unsafe { load_webkit_cursor(ns_string!("cell")) } +} + +pub(crate) fn invisible_cursor() -> Retained { + // 16x16 GIF data for invisible cursor + // You can reproduce this via ImageMagick. + // $ convert -size 16x16 xc:none cursor.gif + static CURSOR_BYTES: &[u8] = &[ + 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0e, 0x84, 0x8f, 0xa9, 0xcb, 0xed, 0x0f, + 0xa3, 0x9c, 0xb4, 0xda, 0x8b, 0xb3, 0x3e, 0x05, 0x00, 0x3b, + ]; + + fn new_invisible() -> Retained { + // TODO: Consider using `dataWithBytesNoCopy:` + let data = NSData::with_bytes(CURSOR_BYTES); + let image = NSImage::initWithData(NSImage::alloc(), &data).unwrap(); + let hotspot = NSPoint::new(0.0, 0.0); + NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot) + } + + // Cache this for efficiency + static CURSOR: OnceLock = OnceLock::new(); + CURSOR.get_or_init(|| CustomCursor(new_invisible())).0.clone() +} + +#[allow(deprecated)] +pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained { + match icon { + CursorIcon::Default => default_cursor(), + CursorIcon::Pointer => NSCursor::pointingHandCursor(), + CursorIcon::Grab => NSCursor::openHandCursor(), + CursorIcon::Grabbing => NSCursor::closedHandCursor(), + CursorIcon::Text => NSCursor::IBeamCursor(), + CursorIcon::VerticalText => NSCursor::IBeamCursorForVerticalLayout(), + CursorIcon::Copy => NSCursor::dragCopyCursor(), + CursorIcon::Alias => NSCursor::dragLinkCursor(), + CursorIcon::NotAllowed | CursorIcon::NoDrop => NSCursor::operationNotAllowedCursor(), + CursorIcon::ContextMenu => NSCursor::contextualMenuCursor(), + CursorIcon::Crosshair => NSCursor::crosshairCursor(), + CursorIcon::EResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::Right, + NSCursorFrameResizeDirections::Outward, + ) + } else { + NSCursor::resizeRightCursor() + } + }, + CursorIcon::NResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::Top, + NSCursorFrameResizeDirections::Outward, + ) + } else { + NSCursor::resizeUpCursor() + } + }, + CursorIcon::WResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::Left, + NSCursorFrameResizeDirections::Outward, + ) + } else { + NSCursor::resizeLeftCursor() + } + }, + CursorIcon::SResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::Bottom, + NSCursorFrameResizeDirections::Outward, + ) + } else { + NSCursor::resizeDownCursor() + } + }, + CursorIcon::EwResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::Right, + NSCursorFrameResizeDirections::All, + ) + } else { + NSCursor::resizeLeftRightCursor() + } + }, + CursorIcon::NsResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::Top, + NSCursorFrameResizeDirections::All, + ) + } else { + NSCursor::resizeUpDownCursor() + } + }, + CursorIcon::NeResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::TopRight, + NSCursorFrameResizeDirections::Outward, + ) + } else { + _windowResizeNorthEastCursor() + } + }, + CursorIcon::NwResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::TopLeft, + NSCursorFrameResizeDirections::Outward, + ) + } else { + _windowResizeNorthWestCursor() + } + }, + CursorIcon::SeResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::BottomRight, + NSCursorFrameResizeDirections::Outward, + ) + } else { + _windowResizeSouthEastCursor() + } + }, + CursorIcon::SwResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::BottomLeft, + NSCursorFrameResizeDirections::Outward, + ) + } else { + _windowResizeSouthWestCursor() + } + }, + CursorIcon::NeswResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::TopRight, + NSCursorFrameResizeDirections::All, + ) + } else { + _windowResizeNorthEastSouthWestCursor() + } + }, + CursorIcon::NwseResize => { + if available!(macos = 15.0) { + NSCursor::frameResizeCursorFromPosition_inDirections( + NSCursorFrameResizePosition::TopLeft, + NSCursorFrameResizeDirections::All, + ) + } else { + _windowResizeNorthWestSouthEastCursor() + } + }, + CursorIcon::ColResize => { + if available!(macos = 15.0) { + NSCursor::columnResizeCursor() + } else { + NSCursor::resizeLeftRightCursor() + } + }, + CursorIcon::RowResize => { + if available!(macos = 15.0) { + NSCursor::rowResizeCursor() + } else { + NSCursor::resizeUpDownCursor() + } + }, + CursorIcon::ZoomIn => { + if available!(macos = 15.0) { + NSCursor::zoomInCursor() + } else { + _zoomInCursor() + } + }, + CursorIcon::ZoomOut => { + if available!(macos = 15.0) { + NSCursor::zoomOutCursor() + } else { + _zoomOutCursor() + } + }, + CursorIcon::Help => _helpCursor(), + // This is the wrong semantics for `Wait`, but it's the same as + // what's used in Safari and Chrome. + CursorIcon::Wait | CursorIcon::Progress => busyButClickableCursor(), + CursorIcon::Move | CursorIcon::AllScroll => webkit_move(), + CursorIcon::Cell => webkit_cell(), + _ => default_cursor(), + } +} diff --git a/patches/winit-appkit/src/dnd.rs b/patches/winit-appkit/src/dnd.rs new file mode 100644 index 0000000000..3dd44c309a --- /dev/null +++ b/patches/winit-appkit/src/dnd.rs @@ -0,0 +1,500 @@ +use std::cell::RefCell; +use std::collections::HashMap; +use std::io; +use std::ops::{BitOr, ControlFlow}; +use std::sync::{Arc, OnceLock}; + +use dispatch2::MainThreadBound; +use objc2::rc::{Retained, Weak}; +use objc2::runtime::AnyObject; +use objc2::{AnyThread, DefinedClass as _, MainThreadMarker, Message, define_class, msg_send}; +use objc2_app_kit::{ + NSDragOperation, NSPasteboard, NSPasteboardType, NSPasteboardTypeFileURL, NSPasteboardTypeHTML, + NSPasteboardTypePNG, NSPasteboardTypeSound, NSPasteboardTypeString, NSPasteboardTypeTIFF, + NSPasteboardWriting, NSPasteboardWritingOptions, +}; +use objc2_foundation::{NSArray, NSData, NSObject, NSObjectProtocol, NSString}; +use winit_core::data_transfer::{ + DataTransfer, DataTransferId, DataTransferSend, SendData, TransferType, TypeHint, TypedData, +}; +use winit_core::event_loop::DndAction; +use winit_core::window::WindowId; + +/// A thin wrapper around [`NSPasteboardType`], implementing [`TransferType`]. +#[derive(PartialEq, Eq, Debug, Clone)] +pub struct PasteboardType { + hint: Option, + // We need to convert `NSString` to `str` since `NSString` isn't `Send`/`Sync` + inner: Arc, +} + +impl PasteboardType { + fn from_hint(hint: TypeHint) -> Option { + let hint_to_pasteboard_type = unsafe { + [ + (TypeHint::UriList, NSPasteboardTypeFileURL), + (TypeHint::Plaintext, NSPasteboardTypeString), + (TypeHint::Html, NSPasteboardTypeHTML), + (TypeHint::Image { extension_hint: Some("png") }, NSPasteboardTypePNG), + (TypeHint::Image { extension_hint: Some("tiff") }, NSPasteboardTypeTIFF), + (TypeHint::Audio { extension_hint: None }, NSPasteboardTypeSound), + ] + }; + + hint_to_pasteboard_type.into_iter().find_map(|(haystack, inner)| { + (haystack.matches(&hint)) + .then(|| Self { hint: Some(hint), inner: inner.to_string().into() }) + }) + } +} + +impl From> for PasteboardType { + fn from(value: Retained) -> Self { + let pasteboard_type_to_hint = unsafe { + [ + // Just in case the source application uses the deprecated method, we handle it + // here + #[expect(deprecated)] + (objc2_app_kit::NSFilenamesPboardType, TypeHint::UriList), + (NSPasteboardTypeFileURL, TypeHint::UriList), + (NSPasteboardTypeString, TypeHint::Plaintext), + (NSPasteboardTypeHTML, TypeHint::Html), + (NSPasteboardTypePNG, TypeHint::Image { extension_hint: Some("png") }), + (NSPasteboardTypeTIFF, TypeHint::Image { extension_hint: Some("tiff") }), + (NSPasteboardTypeSound, TypeHint::Audio { extension_hint: None }), + ] + }; + + let hint = pasteboard_type_to_hint + .iter() + .find_map(|(pb_type, hint)| (**pb_type == *value).then_some(hint)); + + Self { hint: hint.copied(), inner: value.to_string().into() } + } +} + +impl TransferType for PasteboardType { + fn hint(&self) -> Option { + self.hint + } + + fn matches(&self, other: &dyn TransferType) -> bool { + if let Some(other_pb_type) = other.cast_ref::() { + *self == *other_pb_type + } else { + // If either hint is `None`, return false + self.hint().is_some_and(|hint| other.hint() == Some(hint)) + } + } +} + +/// A thin wrapper around [`NSPasteboard`], implementing [`DataTransfer`]. +#[derive(Debug)] +pub struct Pasteboard { + transfer_id: DataTransferId, + ns_pasteboard: MainThreadBound>, + types: OnceLock>, +} + +impl Clone for Pasteboard { + fn clone(&self) -> Self { + let inner = self.ns_pasteboard.get_on_main(|inner| { + MainThreadBound::new(inner.clone(), MainThreadMarker::new().unwrap()) + }); + + Self { transfer_id: self.transfer_id, ns_pasteboard: inner, types: self.types.clone() } + } +} + +impl Pasteboard { + fn new( + transfer_id: DataTransferId, + ns_pasteboard: MainThreadBound>, + ) -> Self { + Self { transfer_id, ns_pasteboard, types: Default::default() } + } + + /// Get the array of [`PasteboardType`]s advertized by this [`Pasteboard`]. + pub fn types(&self) -> &[PasteboardType] { + self.types.get_or_init(|| { + self.ns_pasteboard.get_on_main(|pb| { + pb.types() + .map(|types| types.into_iter().map(PasteboardType::from).collect::>()) + .unwrap_or_default() + .into() + }) + }) + } + + /// Get the `DataTransferId` of this pasteboard. + pub fn id(&self) -> DataTransferId { + self.transfer_id + } + + /// Get a typed reader for this pasteboard. This is only necessary in the cross-platform case, + /// as a user downcasting to the platform-specific type can just access the `NSPasteboard` + /// directly. + pub(crate) fn with_type(&self, type_: PasteboardTypeSpec) -> PasteboardValue { + PasteboardValue { type_, pasteboard: self.clone() } + } +} + +impl DataTransfer for Pasteboard { + fn for_each_available_type<'this>( + &'this self, + func: &'_ mut dyn FnMut(&'this dyn TransferType) -> std::ops::ControlFlow<()>, + ) { + let _ = self.types().iter().map(|mime| mime as &dyn TransferType).try_for_each(func); + } +} + +#[derive(Debug, Clone)] +pub(crate) enum PasteboardTypeSpec { + PasteboardType(PasteboardType), + TypeHint(TypeHint), +} + +impl PasteboardTypeSpec { + pub(crate) fn from_dyn(type_: &dyn TransferType) -> Option { + match type_.cast_ref::() { + Some(pb_type) => Some(Self::PasteboardType(pb_type.clone())), + None => type_.hint().map(Into::into), + } + } +} + +impl From for PasteboardTypeSpec { + fn from(value: TypeHint) -> Self { + match PasteboardType::from_hint(value) { + Some(pb_type) => Self::PasteboardType(pb_type), + None => Self::TypeHint(value), + } + } +} + +impl PasteboardTypeSpec { + fn pasteboard_type(&self) -> Option<&PasteboardType> { + match self { + PasteboardTypeSpec::PasteboardType(pasteboard_type) => Some(pasteboard_type), + PasteboardTypeSpec::TypeHint(_) => None, + } + } +} + +pub fn dnd_action_to_ns_drag_operation(value: DndAction) -> NSDragOperation { + match value { + DndAction::Copy => NSDragOperation::Copy, + DndAction::Move => NSDragOperation::Move, + DndAction::Link => NSDragOperation::Link, + DndAction::Private => NSDragOperation::Private, + _ => NSDragOperation::empty(), + } +} + +pub fn ns_drag_operation_to_dnd_action(value: NSDragOperation) -> Option { + [ + (NSDragOperation::Copy, DndAction::Copy), + (NSDragOperation::Move, DndAction::Move), + (NSDragOperation::Link, DndAction::Link), + (NSDragOperation::Private, DndAction::Private), + // Sometimes the OS returns `Generic`, in which case we just fall back to `Copy`. + (NSDragOperation::Generic, DndAction::Copy), + ] + .into_iter() + .find_map(|(appkit, winit)| value.contains(appkit).then_some(winit)) +} + +pub fn dnd_actions_to_ns_drag_operation(value: &[DndAction]) -> NSDragOperation { + value + .iter() + .copied() + .map(dnd_action_to_ns_drag_operation) + .fold(NSDragOperation::empty(), BitOr::bitor) +} + +pub fn preferred_drag_operation( + value: NSDragOperation, + preference: &[DndAction], +) -> Option { + preference + .iter() + .find(|action| value.intersects(dnd_action_to_ns_drag_operation(**action))) + .copied() +} + +/// A thin wrapper around [`NSPasteboard`], implementing [`TypedData`]. +#[derive(Debug)] +pub struct PasteboardValue { + // The concept of "top-level" types for a pasteboard doesn't always make sense on macOS due to + // the use of `pasteboardItems`, so we allow using `TypeHint` instead to preserve the user's + // intention. + type_: PasteboardTypeSpec, + pasteboard: Pasteboard, +} + +impl TypedData for PasteboardValue { + fn type_(&self) -> &dyn TransferType { + match &self.type_ { + PasteboardTypeSpec::PasteboardType(pasteboard_type) => { + pasteboard_type as &dyn TransferType + }, + PasteboardTypeSpec::TypeHint(type_hint) => type_hint, + } + } + + fn try_read(&self) -> Option> { + self.try_as_bytes() + .ok() + .map(|bytes| Box::new(io::Cursor::new(bytes)) as Box) + } + + fn try_as_bytes(&self) -> io::Result> { + let type_ = self.type_.clone(); + self.pasteboard + .ns_pasteboard + .get_on_main(|pasteboard| { + let bytes = + pasteboard.dataForType(&NSString::from_str(&type_.pasteboard_type()?.inner))?; + Some(bytes.to_vec()) + }) + .ok_or_else(|| { + io::Error::other(format!( + "NSPasteboard doesn't advertise a binary representation for type {:?}", + self.type_ + )) + }) + } + + fn try_as_uris(&self) -> io::Result> { + // TODO: We should probably use `readObjects`, need to check how that works. + if self.type_().hint() != Some(TypeHint::UriList) { + return Err(io::ErrorKind::InvalidData.into()); + } + + self.pasteboard.ns_pasteboard.get_on_main(|pasteboard| { + let Some(items) = pasteboard.pasteboardItems() else { + // The pasteboard didn't expose any items, so we try with the deprecated method. + #[expect(deprecated)] + let property_list = match pasteboard + .propertyListForType(unsafe { objc2_app_kit::NSFilenamesPboardType }) + { + Some(property_list) => property_list, + None => { + return pasteboard + .stringForType(unsafe { NSPasteboardTypeFileURL }) + .map(|ns_str| vec![ns_str.to_string()]) + .ok_or_else(|| io::ErrorKind::InvalidData.into()); + }, + }; + + let paths = property_list + .downcast::() + .unwrap() + .into_iter() + .map(|file| file.downcast::().unwrap().to_string()) + .collect(); + + return Ok(paths); + }; + + Ok(items + .into_iter() + .filter_map(|item| item.stringForType(unsafe { NSPasteboardTypeFileURL })) + .map(|ns_str| ns_str.to_string()) + .collect()) + }) + } + + fn try_as_string(&self) -> io::Result { + let type_ = self.type_.clone(); + + self.pasteboard.ns_pasteboard.get_on_main(|pasteboard| { + pasteboard + .stringForType(&NSString::from_str( + &type_.pasteboard_type().ok_or(io::ErrorKind::InvalidData)?.inner, + )) + .map(|ns_str| ns_str.to_string()) + .ok_or_else(|| io::ErrorKind::InvalidData.into()) + }) + } +} + +#[derive(Debug)] +struct ActivePasteboard { + window_id: WindowId, + pb: MainThreadBound>, +} + +#[derive(Debug, Default)] +pub struct Pasteboards { + inner: RefCell>, +} + +impl Pasteboards { + pub fn remove_deloaded_pasteboards(&self) { + self.inner.borrow_mut().retain(|_, ActivePasteboard { pb, .. }| { + pb.get_on_main(|state| state.load().is_some()) + }); + } + + /// If the data transfer exists, update the pasteboard it points to. + pub fn set_pasteboard( + &self, + id: DataTransferId, + new_pb: &MainThreadBound>, + ) { + let mut inner = self.inner.borrow_mut(); + if let Some(ActivePasteboard { pb, .. }) = inner.get_mut(&id) { + *pb = new_pb.get_on_main(|pb| { + MainThreadBound::new(Weak::from_retained(pb), MainThreadMarker::new().unwrap()) + }); + } + } + + pub fn insert( + &self, + transfer_id: DataTransferId, + pb: &MainThreadBound>, + window_id: WindowId, + ) { + let mut inner = self.inner.borrow_mut(); + let transfer = inner.entry(transfer_id).or_insert_with(move || { + pb.get_on_main(move |pb| ActivePasteboard { + window_id, + pb: MainThreadBound::new(Weak::from_retained(pb), MainThreadMarker::new().unwrap()), + }) + }); + + transfer.window_id = window_id; + } + + pub fn get(&self, id: DataTransferId) -> Option { + self.inner.borrow().get(&id).and_then(|ActivePasteboard { pb, .. }| { + pb.get_on_main(|state| { + let pb = state.load()?; + let pb = MainThreadBound::new(pb, MainThreadMarker::new().unwrap()); + Some(Pasteboard::new(id, pb)) + }) + }) + } + + /// Get the window ID that most-recently saw the provided data transfer. + pub fn window_id(&self, id: DataTransferId) -> Option { + self.inner.borrow().get(&id).map(|active_pasteboard| active_pasteboard.window_id) + } +} + +pub(crate) struct PasteboardWriterState { + data: Box, + // The macOS drag-and-drop API has some confusing aspects when handling multi-drag. The best + // we can really do is have the first element contain all the cross-platform items, and + // any further items are file paths only. + uri: Option>, + writable_types: Retained>, +} + +impl PasteboardWriter { + pub(crate) fn new( + value: Box, + uri: Option>, + ) -> Retained { + let mut writable_types = Vec::>::new(); + value.for_each_available_type(&mut |type_| { + let Some(spec) = PasteboardTypeSpec::from_dyn(type_) else { + return ControlFlow::Continue(()); + }; + + let Some(pb_type) = spec.pasteboard_type() else { + return ControlFlow::Continue(()); + }; + + writable_types.push(NSString::from_str(&pb_type.inner)); + + ControlFlow::Continue(()) + }); + + let pb_writer = Self::alloc().set_ivars(PasteboardWriterState { + data: value, + uri, + writable_types: NSArray::from_retained_slice(&writable_types), + }); + + // Unsure if there's an easier way to do this, but this is how `WindowDelegate` does it. + unsafe { msg_send![super(pb_writer), init] } + } +} + +impl PasteboardWriterState { + fn data_for_pasteboard_type( + &self, + pasteboard_type: &NSPasteboardType, + ) -> Option> { + if pasteboard_type == unsafe { NSPasteboardTypeFileURL } { + if let Some(out) = self.uri.clone().map(Into::into) { + return Some(out); + } + } + let pb_type = PasteboardType::from(pasteboard_type.retain()); + + let mut out = None; + + self.data.for_each_available_type(&mut |haystack| { + if haystack.matches(&pb_type) { + out = self.data.data_for_type(haystack); + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }); + + match out? { + // This should be handled separately + // TODO: Is there a better way to do this? + SendData::Uris(_) => None, + SendData::String(string) => Some(NSString::from_str(&string).into()), + SendData::Bytes(binary) => Some(NSData::from_vec(binary).into()), + _ => None, + } + } +} + +define_class!( + #[unsafe(super(NSObject))] + #[thread_kind = AnyThread] + #[name = "WinitPasteboardWriter"] + #[ivars = PasteboardWriterState] + pub(crate) struct PasteboardWriter; + + unsafe impl NSObjectProtocol for PasteboardWriter {} + + unsafe impl NSPasteboardWriting for PasteboardWriter { + #[unsafe(method_id(writableTypesForPasteboard:))] + fn writable_types_for_pasteboard( + &self, + _: &NSPasteboard, + ) -> Retained> { + let vars = self.ivars(); + vars.writable_types.clone() + } + + #[unsafe(method(writingOptionsForType:pasteboard:))] + fn writing_options_for_type( + &self, + type_: &NSPasteboardType, + pasteboard: &NSPasteboard, + ) -> NSPasteboardWritingOptions { + let _ = type_; + let _ = pasteboard; + NSPasteboardWritingOptions::empty() + } + + #[unsafe(method_id(pasteboardPropertyListForType:))] + fn pasteboard_property_list_for_type( + &self, + type_: &NSPasteboardType, + ) -> Option> { + let vars = self.ivars(); + vars.data_for_pasteboard_type(type_) + } + } +); diff --git a/patches/winit-appkit/src/event.rs b/patches/winit-appkit/src/event.rs new file mode 100644 index 0000000000..434a1de761 --- /dev/null +++ b/patches/winit-appkit/src/event.rs @@ -0,0 +1,630 @@ +use std::ptr::NonNull; + +use dispatch2::run_on_main; +use objc2::rc::Retained; +use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventSubtype, NSEventType}; +use objc2_core_foundation::{CFData, CFRetained}; +use objc2_foundation::NSPoint; +use smol_str::SmolStr; +use winit_core::event::{ElementState, KeyEvent, Modifiers}; +use winit_core::keyboard::{ + Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode, + PhysicalKey, +}; + +use super::ffi; + +/// Ignores ALL modifiers. +pub fn get_modifierless_char(scancode: u16) -> Key { + let Some(ptr) = NonNull::new(unsafe { ffi::TISCopyCurrentKeyboardLayoutInputSource() }) else { + tracing::error!("`TISCopyCurrentKeyboardLayoutInputSource` returned null ptr"); + return Key::Unidentified(NativeKey::MacOS(scancode)); + }; + let input_source = unsafe { CFRetained::from_raw(ptr) }; + + let layout_data = unsafe { + ffi::TISGetInputSourceProperty(&input_source, ffi::kTISPropertyUnicodeKeyLayoutData) + }; + let Some(layout_data) = (unsafe { layout_data.cast::().as_ref() }) else { + tracing::error!("`TISGetInputSourceProperty` returned null ptr"); + return Key::Unidentified(NativeKey::MacOS(scancode)); + }; + + let layout = layout_data.byte_ptr().cast(); + let keyboard_type = run_on_main(|_mtm| unsafe { ffi::LMGetKbdType() }); + + let mut result_len = 0; + let mut dead_keys = 0; + let modifiers = 0; + let mut string = [0; 16]; + let translate_result = unsafe { + ffi::UCKeyTranslate( + layout, + scancode, + ffi::kUCKeyActionDisplay, + modifiers, + keyboard_type as u32, + ffi::kUCKeyTranslateNoDeadKeysMask, + &mut dead_keys, + string.len() as ffi::UniCharCount, + &mut result_len, + string.as_mut_ptr(), + ) + }; + if translate_result != 0 { + tracing::error!("`UCKeyTranslate` returned with the non-zero value: {}", translate_result); + return Key::Unidentified(NativeKey::MacOS(scancode)); + } + if result_len == 0 { + // This is fine - not all keys have text representation. + // For instance, users that have mapped the `Fn` key to toggle + // keyboard layouts will hit this code path. + return Key::Unidentified(NativeKey::MacOS(scancode)); + } + let chars = String::from_utf16_lossy(&string[0..result_len as usize]); + Key::Character(SmolStr::new(chars)) +} + +// Ignores all modifiers except for SHIFT (yes, even ALT is ignored). +fn get_logical_key_char(ns_event: &NSEvent, modifierless_chars: &str) -> Key { + let string = ns_event.charactersIgnoringModifiers().map(|s| s.to_string()).unwrap_or_default(); + if string.is_empty() { + // Probably a dead key + let first_char = modifierless_chars.chars().next(); + return Key::Dead(first_char); + } + Key::Character(SmolStr::new(string)) +} + +/// Create `KeyEvent` for the given `NSEvent`. +/// +/// This function shouldn't be called when the IME input is in process. +pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bool) -> KeyEvent { + use ElementState::{Pressed, Released}; + let state = if is_press { Pressed } else { Released }; + + let scancode = ns_event.keyCode(); + let mut physical_key = scancode_to_physicalkey(scancode as u32); + + // NOTE: The logical key should heed both SHIFT and ALT if possible. + // For instance: + // * Pressing the A key: logical key should be "a" + // * Pressing SHIFT A: logical key should be "A" + // * Pressing CTRL SHIFT A: logical key should also be "A" + // This is not easy to tease out of `NSEvent`, but we do our best. + + let characters = ns_event.characters().map(|s| s.to_string()).unwrap_or_default(); + let text_with_all_modifiers = if characters.is_empty() { + None + } else { + if matches!(physical_key, PhysicalKey::Unidentified(_)) { + // The key may be one of the funky function keys + physical_key = extra_function_key_to_code(scancode, &characters); + } + Some(SmolStr::new(characters)) + }; + + let key_from_code = code_to_key(physical_key, scancode); + let (logical_key, key_without_modifiers) = if matches!(key_from_code, Key::Unidentified(_)) { + // `get_modifierless_char/key_without_modifiers` ignores ALL modifiers. + let key_without_modifiers = get_modifierless_char(scancode); + + let modifiers = ns_event.modifierFlags(); + let has_ctrl = modifiers.contains(NSEventModifierFlags::Control); + let has_cmd = modifiers.contains(NSEventModifierFlags::Command); + + let logical_key = match text_with_all_modifiers.as_ref() { + // Only checking for ctrl and cmd here, not checking for alt because we DO want to + // include its effect in the key. For example if -on the German layout- one + // presses alt+8, the logical key should be "{" + // Also not checking if this is a release event because then this issue would + // still affect the key release. + Some(text) if !has_ctrl && !has_cmd => { + // Character heeding both SHIFT and ALT. + Key::Character(text.clone()) + }, + + _ => match key_without_modifiers.as_ref() { + // Character heeding just SHIFT, ignoring ALT. + Key::Character(ch) => get_logical_key_char(ns_event, ch), + + // Character ignoring ALL modifiers. + _ => key_without_modifiers.clone(), + }, + }; + + (logical_key, key_without_modifiers) + } else { + (key_from_code.clone(), key_from_code) + }; + + let text = if is_press { logical_key.to_text().map(SmolStr::new) } else { None }; + + let location = code_to_location(physical_key); + + KeyEvent { + location, + logical_key, + physical_key, + repeat: is_repeat, + state, + text, + text_with_all_modifiers, + key_without_modifiers, + } +} + +pub fn code_to_key(key: PhysicalKey, scancode: u16) -> Key { + let code = match key { + PhysicalKey::Code(code) => code, + PhysicalKey::Unidentified(code) => return Key::Unidentified(code.into()), + }; + + // Roughly same handling as Firefox and Chromium: + // https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMKeyName.h + // https://chromium.googlesource.com/chromium/src.git/+/010a75a426c4a2292955a52f480e9251cacf750e/ui/events/keycodes/keyboard_code_conversion_mac.mm#100 + Key::Named(match code { + KeyCode::Enter => NamedKey::Enter, + KeyCode::Tab => NamedKey::Tab, + KeyCode::Space => return Key::Character(" ".into()), + KeyCode::Backspace => NamedKey::Backspace, + KeyCode::Escape => NamedKey::Escape, + KeyCode::MetaRight => NamedKey::Meta, + KeyCode::MetaLeft => NamedKey::Meta, + KeyCode::ShiftLeft => NamedKey::Shift, + KeyCode::AltLeft => NamedKey::Alt, + KeyCode::ControlLeft => NamedKey::Control, + KeyCode::ShiftRight => NamedKey::Shift, + KeyCode::AltRight => NamedKey::Alt, + KeyCode::ControlRight => NamedKey::Control, + KeyCode::CapsLock => NamedKey::CapsLock, + + KeyCode::NumLock => NamedKey::NumLock, + KeyCode::AudioVolumeUp => NamedKey::AudioVolumeUp, + KeyCode::AudioVolumeDown => NamedKey::AudioVolumeDown, + KeyCode::AudioVolumeMute => NamedKey::AudioVolumeMute, + + // Other numpad keys all generate text on macOS (if I understand correctly) + KeyCode::NumpadEnter => NamedKey::Enter, + + KeyCode::Fn => NamedKey::Fn, + KeyCode::F1 => NamedKey::F1, + KeyCode::F2 => NamedKey::F2, + KeyCode::F3 => NamedKey::F3, + KeyCode::F4 => NamedKey::F4, + KeyCode::F5 => NamedKey::F5, + KeyCode::F6 => NamedKey::F6, + KeyCode::F7 => NamedKey::F7, + KeyCode::F8 => NamedKey::F8, + KeyCode::F9 => NamedKey::F9, + KeyCode::F10 => NamedKey::F10, + KeyCode::F11 => NamedKey::F11, + KeyCode::F12 => NamedKey::F12, + KeyCode::F13 => NamedKey::F13, + KeyCode::F14 => NamedKey::F14, + KeyCode::F15 => NamedKey::F15, + KeyCode::F16 => NamedKey::F16, + KeyCode::F17 => NamedKey::F17, + KeyCode::F18 => NamedKey::F18, + KeyCode::F19 => NamedKey::F19, + KeyCode::F20 => NamedKey::F20, + KeyCode::F21 => NamedKey::F21, + KeyCode::F22 => NamedKey::F22, + KeyCode::F23 => NamedKey::F23, + KeyCode::F24 => NamedKey::F24, + + KeyCode::Insert => NamedKey::Insert, + KeyCode::Home => NamedKey::Home, + KeyCode::PageUp => NamedKey::PageUp, + KeyCode::Delete => NamedKey::Delete, + KeyCode::End => NamedKey::End, + KeyCode::Help => NamedKey::Help, + KeyCode::PageDown => NamedKey::PageDown, + KeyCode::ArrowLeft => NamedKey::ArrowLeft, + KeyCode::ArrowRight => NamedKey::ArrowRight, + KeyCode::ArrowDown => NamedKey::ArrowDown, + KeyCode::ArrowUp => NamedKey::ArrowUp, + KeyCode::ContextMenu => NamedKey::ContextMenu, + + KeyCode::Lang2 => NamedKey::Eisu, + KeyCode::Lang1 => NamedKey::KanjiMode, + + _ => return Key::Unidentified(NativeKey::MacOS(scancode)), + }) +} + +pub fn code_to_location(key: PhysicalKey) -> KeyLocation { + let code = match key { + PhysicalKey::Code(code) => code, + PhysicalKey::Unidentified(_) => return KeyLocation::Standard, + }; + + match code { + KeyCode::MetaRight => KeyLocation::Right, + KeyCode::MetaLeft => KeyLocation::Left, + KeyCode::ShiftLeft => KeyLocation::Left, + KeyCode::AltLeft => KeyLocation::Left, + KeyCode::ControlLeft => KeyLocation::Left, + KeyCode::ShiftRight => KeyLocation::Right, + KeyCode::AltRight => KeyLocation::Right, + KeyCode::ControlRight => KeyLocation::Right, + + KeyCode::NumLock => KeyLocation::Numpad, + KeyCode::NumpadDecimal => KeyLocation::Numpad, + KeyCode::NumpadMultiply => KeyLocation::Numpad, + KeyCode::NumpadAdd => KeyLocation::Numpad, + KeyCode::NumpadDivide => KeyLocation::Numpad, + KeyCode::NumpadEnter => KeyLocation::Numpad, + KeyCode::NumpadSubtract => KeyLocation::Numpad, + KeyCode::NumpadEqual => KeyLocation::Numpad, + KeyCode::Numpad0 => KeyLocation::Numpad, + KeyCode::Numpad1 => KeyLocation::Numpad, + KeyCode::Numpad2 => KeyLocation::Numpad, + KeyCode::Numpad3 => KeyLocation::Numpad, + KeyCode::Numpad4 => KeyLocation::Numpad, + KeyCode::Numpad5 => KeyLocation::Numpad, + KeyCode::Numpad6 => KeyLocation::Numpad, + KeyCode::Numpad7 => KeyLocation::Numpad, + KeyCode::Numpad8 => KeyLocation::Numpad, + KeyCode::Numpad9 => KeyLocation::Numpad, + + _ => KeyLocation::Standard, + } +} + +// While F1-F20 have scancodes we can match on, we have to check against UTF-16 +// constants for the rest. +// https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?preferredLanguage=occ +pub fn extra_function_key_to_code(scancode: u16, string: &str) -> PhysicalKey { + if let Some(ch) = string.encode_utf16().next() { + match ch { + 0xf718 => PhysicalKey::Code(KeyCode::F21), + 0xf719 => PhysicalKey::Code(KeyCode::F22), + 0xf71a => PhysicalKey::Code(KeyCode::F23), + 0xf71b => PhysicalKey::Code(KeyCode::F24), + _ => PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode)), + } + } else { + PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode)) + } +} + +// The values are from the https://github.com/apple-oss-distributions/IOHIDFamily/blob/19666c840a6d896468416ff0007040a10b7b46b8/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h#L258-L259 +const NX_DEVICELCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000001); +const NX_DEVICELSHIFTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000002); +const NX_DEVICERSHIFTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000004); +const NX_DEVICELCMDKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000008); +const NX_DEVICERCMDKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000010); +const NX_DEVICELALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000020); +const NX_DEVICERALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000040); +const NX_DEVICERCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00002000); + +pub(super) fn lalt_pressed(event: &NSEvent) -> bool { + event.modifierFlags().contains(NX_DEVICELALTKEYMASK) +} + +pub(super) fn ralt_pressed(event: &NSEvent) -> bool { + event.modifierFlags().contains(NX_DEVICERALTKEYMASK) +} + +pub(super) fn event_mods(event: &NSEvent) -> Modifiers { + let flags = event.modifierFlags(); + let mut state = ModifiersState::empty(); + let mut pressed_mods = ModifiersKeys::empty(); + + state.set(ModifiersState::SHIFT, flags.contains(NSEventModifierFlags::Shift)); + pressed_mods.set(ModifiersKeys::LSHIFT, flags.contains(NX_DEVICELSHIFTKEYMASK)); + pressed_mods.set(ModifiersKeys::RSHIFT, flags.contains(NX_DEVICERSHIFTKEYMASK)); + + state.set(ModifiersState::CONTROL, flags.contains(NSEventModifierFlags::Control)); + pressed_mods.set(ModifiersKeys::LCONTROL, flags.contains(NX_DEVICELCTLKEYMASK)); + pressed_mods.set(ModifiersKeys::RCONTROL, flags.contains(NX_DEVICERCTLKEYMASK)); + + state.set(ModifiersState::ALT, flags.contains(NSEventModifierFlags::Option)); + pressed_mods.set(ModifiersKeys::LALT, flags.contains(NX_DEVICELALTKEYMASK)); + pressed_mods.set(ModifiersKeys::RALT, flags.contains(NX_DEVICERALTKEYMASK)); + + state.set(ModifiersState::META, flags.contains(NSEventModifierFlags::Command)); + pressed_mods.set(ModifiersKeys::LMETA, flags.contains(NX_DEVICELCMDKEYMASK)); + pressed_mods.set(ModifiersKeys::RMETA, flags.contains(NX_DEVICERCMDKEYMASK)); + + Modifiers::new(state, pressed_mods) +} + +pub(super) fn dummy_event() -> Option> { + NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2( + NSEventType::ApplicationDefined, + NSPoint::new(0.0, 0.0), + NSEventModifierFlags(0), + 0.0, + 0, + None, + NSEventSubtype::WindowExposed.0, + 0, + 0, + ) +} + +pub fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option { + let code = match physical_key { + PhysicalKey::Code(code) => code, + PhysicalKey::Unidentified(_) => return None, + }; + + match code { + KeyCode::KeyA => Some(0x00), + KeyCode::KeyS => Some(0x01), + KeyCode::KeyD => Some(0x02), + KeyCode::KeyF => Some(0x03), + KeyCode::KeyH => Some(0x04), + KeyCode::KeyG => Some(0x05), + KeyCode::KeyZ => Some(0x06), + KeyCode::KeyX => Some(0x07), + KeyCode::KeyC => Some(0x08), + KeyCode::KeyV => Some(0x09), + KeyCode::IntlBackslash => Some(0x0a), + KeyCode::KeyB => Some(0x0b), + KeyCode::KeyQ => Some(0x0c), + KeyCode::KeyW => Some(0x0d), + KeyCode::KeyE => Some(0x0e), + KeyCode::KeyR => Some(0x0f), + KeyCode::KeyY => Some(0x10), + KeyCode::KeyT => Some(0x11), + KeyCode::Digit1 => Some(0x12), + KeyCode::Digit2 => Some(0x13), + KeyCode::Digit3 => Some(0x14), + KeyCode::Digit4 => Some(0x15), + KeyCode::Digit6 => Some(0x16), + KeyCode::Digit5 => Some(0x17), + KeyCode::Equal => Some(0x18), + KeyCode::Digit9 => Some(0x19), + KeyCode::Digit7 => Some(0x1a), + KeyCode::Minus => Some(0x1b), + KeyCode::Digit8 => Some(0x1c), + KeyCode::Digit0 => Some(0x1d), + KeyCode::BracketRight => Some(0x1e), + KeyCode::KeyO => Some(0x1f), + KeyCode::KeyU => Some(0x20), + KeyCode::BracketLeft => Some(0x21), + KeyCode::KeyI => Some(0x22), + KeyCode::KeyP => Some(0x23), + KeyCode::Enter => Some(0x24), + KeyCode::KeyL => Some(0x25), + KeyCode::KeyJ => Some(0x26), + KeyCode::Quote => Some(0x27), + KeyCode::KeyK => Some(0x28), + KeyCode::Semicolon => Some(0x29), + KeyCode::Backslash => Some(0x2a), + KeyCode::Comma => Some(0x2b), + KeyCode::Slash => Some(0x2c), + KeyCode::KeyN => Some(0x2d), + KeyCode::KeyM => Some(0x2e), + KeyCode::Period => Some(0x2f), + KeyCode::Tab => Some(0x30), + KeyCode::Space => Some(0x31), + KeyCode::Backquote => Some(0x32), + KeyCode::Backspace => Some(0x33), + KeyCode::Escape => Some(0x35), + KeyCode::MetaRight => Some(0x36), + KeyCode::MetaLeft => Some(0x37), + KeyCode::ShiftLeft => Some(0x38), + KeyCode::CapsLock => Some(0x39), + KeyCode::AltLeft => Some(0x3a), + KeyCode::ControlLeft => Some(0x3b), + KeyCode::ShiftRight => Some(0x3c), + KeyCode::AltRight => Some(0x3d), + KeyCode::ControlRight => Some(0x3e), + KeyCode::Fn => Some(0x3f), + KeyCode::F17 => Some(0x40), + KeyCode::NumpadDecimal => Some(0x41), + KeyCode::NumpadMultiply => Some(0x43), + KeyCode::NumpadAdd => Some(0x45), + KeyCode::NumLock => Some(0x47), + KeyCode::AudioVolumeUp => Some(0x48), + KeyCode::AudioVolumeDown => Some(0x49), + KeyCode::AudioVolumeMute => Some(0x4a), + KeyCode::NumpadDivide => Some(0x4b), + KeyCode::NumpadEnter => Some(0x4c), + KeyCode::NumpadSubtract => Some(0x4e), + KeyCode::F18 => Some(0x4f), + KeyCode::F19 => Some(0x50), + KeyCode::NumpadEqual => Some(0x51), + KeyCode::Numpad0 => Some(0x52), + KeyCode::Numpad1 => Some(0x53), + KeyCode::Numpad2 => Some(0x54), + KeyCode::Numpad3 => Some(0x55), + KeyCode::Numpad4 => Some(0x56), + KeyCode::Numpad5 => Some(0x57), + KeyCode::Numpad6 => Some(0x58), + KeyCode::Numpad7 => Some(0x59), + KeyCode::F20 => Some(0x5a), + KeyCode::Numpad8 => Some(0x5b), + KeyCode::Numpad9 => Some(0x5c), + KeyCode::IntlYen => Some(0x5d), + KeyCode::IntlRo => Some(0x5e), + KeyCode::NumpadComma => Some(0x5f), + KeyCode::F5 => Some(0x60), + KeyCode::F6 => Some(0x61), + KeyCode::F7 => Some(0x62), + KeyCode::F3 => Some(0x63), + KeyCode::F8 => Some(0x64), + KeyCode::F9 => Some(0x65), + KeyCode::Lang2 => Some(0x66), + KeyCode::F11 => Some(0x67), + KeyCode::Lang1 => Some(0x68), + KeyCode::F13 => Some(0x69), + KeyCode::F16 => Some(0x6a), + KeyCode::F14 => Some(0x6b), + KeyCode::F10 => Some(0x6d), + KeyCode::ContextMenu => Some(0x6e), + KeyCode::F12 => Some(0x6f), + KeyCode::F15 => Some(0x71), + KeyCode::Insert => Some(0x72), + KeyCode::Home => Some(0x73), + KeyCode::PageUp => Some(0x74), + KeyCode::Delete => Some(0x75), + KeyCode::F4 => Some(0x76), + KeyCode::End => Some(0x77), + KeyCode::F2 => Some(0x78), + KeyCode::PageDown => Some(0x79), + KeyCode::F1 => Some(0x7a), + KeyCode::ArrowLeft => Some(0x7b), + KeyCode::ArrowRight => Some(0x7c), + KeyCode::ArrowDown => Some(0x7d), + KeyCode::ArrowUp => Some(0x7e), + KeyCode::Power => Some(0x7f), + _ => None, + } +} + +pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { + // Follows what Chromium and Firefox do: + // https://chromium.googlesource.com/chromium/src.git/+/3e1a26c44c024d97dc9a4c09bbc6a2365398ca2c/ui/events/keycodes/dom/dom_code_data.inc + // https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMCodeName.h + // + // See also: + // Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h + // + // Also see https://developer.apple.com/documentation/appkit/function-key-unicode-values: + // + // > the system handles some function keys at a lower level and your app never sees them. + // > Examples include the Volume Up key, Volume Down key, Volume Mute key, Eject key, and + // > Function key found on many Macs. + // + // So the handling of some of these is mostly for show. + PhysicalKey::Code(match scancode { + 0x00 => KeyCode::KeyA, + 0x01 => KeyCode::KeyS, + 0x02 => KeyCode::KeyD, + 0x03 => KeyCode::KeyF, + 0x04 => KeyCode::KeyH, + 0x05 => KeyCode::KeyG, + 0x06 => KeyCode::KeyZ, + 0x07 => KeyCode::KeyX, + 0x08 => KeyCode::KeyC, + 0x09 => KeyCode::KeyV, + // This key is typically located near LeftShift key, roughly the same location as backquote + // (`) on Windows' US layout. + // + // The keycap varies on international keyboards. + 0x0a => KeyCode::IntlBackslash, + 0x0b => KeyCode::KeyB, + 0x0c => KeyCode::KeyQ, + 0x0d => KeyCode::KeyW, + 0x0e => KeyCode::KeyE, + 0x0f => KeyCode::KeyR, + 0x10 => KeyCode::KeyY, + 0x11 => KeyCode::KeyT, + 0x12 => KeyCode::Digit1, + 0x13 => KeyCode::Digit2, + 0x14 => KeyCode::Digit3, + 0x15 => KeyCode::Digit4, + 0x16 => KeyCode::Digit6, + 0x17 => KeyCode::Digit5, + 0x18 => KeyCode::Equal, + 0x19 => KeyCode::Digit9, + 0x1a => KeyCode::Digit7, + 0x1b => KeyCode::Minus, + 0x1c => KeyCode::Digit8, + 0x1d => KeyCode::Digit0, + 0x1e => KeyCode::BracketRight, + 0x1f => KeyCode::KeyO, + 0x20 => KeyCode::KeyU, + 0x21 => KeyCode::BracketLeft, + 0x22 => KeyCode::KeyI, + 0x23 => KeyCode::KeyP, + 0x24 => KeyCode::Enter, + 0x25 => KeyCode::KeyL, + 0x26 => KeyCode::KeyJ, + 0x27 => KeyCode::Quote, + 0x28 => KeyCode::KeyK, + 0x29 => KeyCode::Semicolon, + 0x2a => KeyCode::Backslash, + 0x2b => KeyCode::Comma, + 0x2c => KeyCode::Slash, + 0x2d => KeyCode::KeyN, + 0x2e => KeyCode::KeyM, + 0x2f => KeyCode::Period, + 0x30 => KeyCode::Tab, + 0x31 => KeyCode::Space, + 0x32 => KeyCode::Backquote, + 0x33 => KeyCode::Backspace, + // 0x34 => unknown, // kVK_Powerbook_KeypadEnter + 0x35 => KeyCode::Escape, + 0x36 => KeyCode::MetaRight, + 0x37 => KeyCode::MetaLeft, + 0x38 => KeyCode::ShiftLeft, + 0x39 => KeyCode::CapsLock, + 0x3a => KeyCode::AltLeft, + 0x3b => KeyCode::ControlLeft, + 0x3c => KeyCode::ShiftRight, + 0x3d => KeyCode::AltRight, + 0x3e => KeyCode::ControlRight, + 0x3f => KeyCode::Fn, + 0x40 => KeyCode::F17, + 0x41 => KeyCode::NumpadDecimal, + // 0x42 -> unknown, + 0x43 => KeyCode::NumpadMultiply, + // 0x44 => unknown, + 0x45 => KeyCode::NumpadAdd, + // 0x46 => unknown, + 0x47 => KeyCode::NumLock, // kVK_ANSI_KeypadClear + 0x48 => KeyCode::AudioVolumeUp, + 0x49 => KeyCode::AudioVolumeDown, + 0x4a => KeyCode::AudioVolumeMute, + 0x4b => KeyCode::NumpadDivide, + 0x4c => KeyCode::NumpadEnter, + // 0x4d => unknown, + 0x4e => KeyCode::NumpadSubtract, + 0x4f => KeyCode::F18, + 0x50 => KeyCode::F19, + 0x51 => KeyCode::NumpadEqual, + 0x52 => KeyCode::Numpad0, + 0x53 => KeyCode::Numpad1, + 0x54 => KeyCode::Numpad2, + 0x55 => KeyCode::Numpad3, + 0x56 => KeyCode::Numpad4, + 0x57 => KeyCode::Numpad5, + 0x58 => KeyCode::Numpad6, + 0x59 => KeyCode::Numpad7, + 0x5a => KeyCode::F20, + 0x5b => KeyCode::Numpad8, + 0x5c => KeyCode::Numpad9, + 0x5d => KeyCode::IntlYen, + 0x5e => KeyCode::IntlRo, + 0x5f => KeyCode::NumpadComma, + 0x60 => KeyCode::F5, + 0x61 => KeyCode::F6, + 0x62 => KeyCode::F7, + 0x63 => KeyCode::F3, + 0x64 => KeyCode::F8, + 0x65 => KeyCode::F9, + 0x66 => KeyCode::Lang2, + 0x67 => KeyCode::F11, + 0x68 => KeyCode::Lang1, + 0x69 => KeyCode::F13, + 0x6a => KeyCode::F16, + 0x6b => KeyCode::F14, + // 0x6c => unknown, + 0x6d => KeyCode::F10, + 0x6e => KeyCode::ContextMenu, + 0x6f => KeyCode::F12, + // 0x70 => unknown, + 0x71 => KeyCode::F15, + 0x72 => KeyCode::Insert, + 0x73 => KeyCode::Home, + 0x74 => KeyCode::PageUp, + 0x75 => KeyCode::Delete, + 0x76 => KeyCode::F4, + 0x77 => KeyCode::End, + 0x78 => KeyCode::F2, + 0x79 => KeyCode::PageDown, + 0x7a => KeyCode::F1, + 0x7b => KeyCode::ArrowLeft, + 0x7c => KeyCode::ArrowRight, + 0x7d => KeyCode::ArrowDown, + 0x7e => KeyCode::ArrowUp, + 0x7f => KeyCode::Power, // On 10.7 and 10.8 only + _ => return PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode as u16)), + }) +} diff --git a/patches/winit-appkit/src/event_loop.rs b/patches/winit-appkit/src/event_loop.rs new file mode 100644 index 0000000000..2682a30972 --- /dev/null +++ b/patches/winit-appkit/src/event_loop.rs @@ -0,0 +1,622 @@ +use std::fmt; +use std::rc::Rc; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use objc2::rc::{Retained, autoreleasepool}; +use objc2::runtime::ProtocolObject; +use objc2::{AnyThread, MainThreadMarker, available}; +use objc2_app_kit::{ + NSApplication, NSApplicationActivationPolicy, NSApplicationDidFinishLaunchingNotification, + NSApplicationWillTerminateNotification, NSDraggingItem, NSWindow, +}; +use objc2_core_foundation::{ + CFIndex, CFRunLoopActivity, CGPoint, CGRect, CGSize, kCFRunLoopCommonModes, +}; +use objc2_foundation::{NSArray, NSNotificationCenter, NSObjectProtocol, NSString}; +use rwh_06::HasDisplayHandle; +use tracing::debug_span; +use winit_common::core_foundation::{MainRunLoop, MainRunLoopObserver, tracing_observers}; +use winit_common::foundation::create_observer; +use winit_core::application::ApplicationHandler; +use winit_core::cursor::{CustomCursor as CoreCustomCursor, CustomCursorSource}; +use winit_core::data_transfer::{ + DataTransfer, DataTransferId, DataTransferSend, SendData, TransferType, TypeHint, +}; +use winit_core::error::{EventLoopError, RequestError}; +use winit_core::event::WindowEvent; +use winit_core::event_loop::pump_events::PumpStatus; +use winit_core::event_loop::{ + ActiveEventLoop as RootActiveEventLoop, AsyncRequestSerial, ControlFlow, DeviceEvents, + DndAction, DragIcon, EventLoopProvider, EventLoopProxy as CoreEventLoopProxy, + OwnedDisplayHandle as CoreOwnedDisplayHandle, +}; +use winit_core::monitor::MonitorHandle as CoreMonitorHandle; +use winit_core::window::{Theme, WindowId}; + +use super::app::override_send_event; +use super::app_state::AppState; +use super::cursor::CustomCursor; +use super::event::dummy_event; +use super::monitor; +use crate::ActivationPolicy; +use crate::cursor::image_from_icon; +use crate::dnd::{PasteboardTypeSpec, PasteboardWriter, dnd_actions_to_ns_drag_operation}; +use crate::window::Window; + +#[derive(Debug)] +pub struct ActiveEventLoop { + pub(super) app_state: Rc, + pub(super) mtm: MainThreadMarker, +} + +impl ActiveEventLoop { + pub(crate) fn hide_application(&self) { + NSApplication::sharedApplication(self.mtm).hide(None) + } + + pub(crate) fn hide_other_applications(&self) { + NSApplication::sharedApplication(self.mtm).hideOtherApplications(None) + } + + pub(crate) fn set_allows_automatic_window_tabbing(&self, enabled: bool) { + NSWindow::setAllowsAutomaticWindowTabbing(enabled, self.mtm) + } + + pub(crate) fn allows_automatic_window_tabbing(&self) -> bool { + NSWindow::allowsAutomaticWindowTabbing(self.mtm) + } +} + +impl RootActiveEventLoop for ActiveEventLoop { + fn create_proxy(&self) -> CoreEventLoopProxy { + CoreEventLoopProxy::new(self.app_state.event_loop_proxy().clone()) + } + + fn create_window( + &self, + window_attributes: winit_core::window::WindowAttributes, + ) -> Result, RequestError> { + Ok(Box::new(Window::new(self, window_attributes)?)) + } + + fn create_custom_cursor( + &self, + source: CustomCursorSource, + ) -> Result { + Ok(CoreCustomCursor(Arc::new(CustomCursor::new(source)?))) + } + + fn available_monitors(&self) -> Box> { + Box::new( + monitor::available_monitors() + .into_iter() + .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), + ) + } + + fn primary_monitor(&self) -> Option { + let monitor = monitor::primary_monitor(); + Some(CoreMonitorHandle(Arc::new(monitor))) + } + + fn listen_device_events(&self, _allowed: DeviceEvents) {} + + fn system_theme(&self) -> Option { + let app = NSApplication::sharedApplication(self.mtm); + + // Dark appearance was introduced in macOS 10.14 + if available!(macos = 10.14) { + Some(super::window_delegate::appearance_to_theme(&app.effectiveAppearance())) + } else { + Some(Theme::Light) + } + } + + fn set_control_flow(&self, control_flow: ControlFlow) { + self.app_state.set_control_flow(control_flow) + } + + fn control_flow(&self) -> ControlFlow { + self.app_state.control_flow() + } + + fn exit(&self) { + self.app_state.exit() + } + + fn exiting(&self) -> bool { + self.app_state.exiting() + } + + fn owned_display_handle(&self) -> CoreOwnedDisplayHandle { + CoreOwnedDisplayHandle::new(Arc::new(OwnedDisplayHandle)) + } + + fn rwh_06_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } + + fn fetch_data_transfer( + &self, + id: DataTransferId, + type_: &dyn TransferType, + ) -> Result { + let Some(pb) = self.app_state.pasteboards().get(id) else { + return Err(RequestError::Ignored); + }; + let Some(window_id) = self.app_state.pasteboards().window_id(id) else { + return Err(RequestError::Ignored); + }; + + let serial = AsyncRequestSerial::get(); + + let Some(type_) = PasteboardTypeSpec::from_dyn(type_) else { + return Err(os_error!(format!("Pasteboard does not contain type {type_:?}")).into()); + }; + + let data = Arc::new(pb.with_type(type_)); + + self.app_state.maybe_queue_with_handler(move |app, event_loop| { + app.window_event(event_loop, window_id, WindowEvent::DataTransferReceived { + id, + serial, + value: data, + }); + }); + + Ok(serial) + } + + fn data_transfer(&self, id: DataTransferId) -> Result, RequestError> { + let Some(pb) = self.app_state.pasteboards().get(id) else { + return Err(RequestError::Ignored); + }; + + Ok(Box::new(pb)) + } + + fn set_valid_dnd_actions( + &self, + id: DataTransferId, + actions: &[DndAction], + ) -> Result<(), RequestError> { + let mut state = self.app_state.drag_state().borrow_mut(); + let Some(drag_state) = &mut *state else { + return Err(os_error!(UnknownDataTransfer(id)).into()); + }; + + if drag_state.id != id { + return Err(os_error!(UnknownDataTransfer(id)).into()); + } + + drag_state.valid_actions.clear(); + drag_state.valid_actions.extend_from_slice(actions); + + Ok(()) + } + + fn start_drag( + &self, + source: WindowId, + send_data: Box, + actions: &[DndAction], + icon: Option, + ) -> Result { + let drag_operation = dnd_actions_to_ns_drag_operation(actions); + + self.app_state + .with_window_delegate_on_main(source, move |delegate| { + let (dragging_rect_offset_x, dragging_rect_offset_y) = + icon.as_ref().map(|icon| (icon.offset_x, icon.offset_y)).unwrap_or_default(); + let drag_image = icon.and_then(|icon| image_from_icon(&icon.icon).ok()); + + let Some(event) = delegate.window().currentEvent() else { + return Err(RequestError::Ignored); + }; + + let dragging_rect_size = drag_image + .as_ref() + .map(|img| img.size()) + // Seemingly we need some kind of dragging rectangle even if no icon is + // supplied. + .unwrap_or(CGSize::new(16., 16.)); + + let event_location = event.locationInWindow(); + let dragging_rect_location = CGPoint::new( + event_location.x + dragging_rect_offset_x as f64, + // Convert generic coordinates (y=0 is top of image) to AppKit coordinates (y=0 + // is bottom of image) + event_location.y - dragging_rect_size.height - dragging_rect_offset_y as f64, + ); + let dragging_rect = CGRect::new(dragging_rect_location, dragging_rect_size); + + let mut uris = send_data + .data_for_type(&TypeHint::UriList) + .and_then(|file_uris| { + // TODO: Might not be ideal to do this + let ns_url_from_str = |str: String| NSString::from_str(&str); + // Slightly complicated use of iterators in order to ensure that branches + // have the same opaque type + match file_uris { + SendData::Uris(os_strings) => Some( + None.into_iter().chain(os_strings.into_iter().map(ns_url_from_str)), + ), + SendData::String(string) => Some( + Some(NSString::from_str(&string)) + .into_iter() + .chain(Vec::new().into_iter().map(ns_url_from_str)), + ), + SendData::Bytes(_) => None, + _ => None, + } + }) + .into_iter() + .flatten(); + + let first_uri = uris.next(); + + let mut pasteboard_items = uris + .map(|ns_url| { + let dragging_item = NSDraggingItem::initWithPasteboardWriter( + NSDraggingItem::alloc(), + ProtocolObject::from_ref(&*ns_url), + ); + + // No dragging frame/contents, icon only applies to the first item. + + dragging_item + }) + .collect::>(); + + let first_dragging_item = NSDraggingItem::initWithPasteboardWriter( + NSDraggingItem::alloc(), + ProtocolObject::from_ref(&*PasteboardWriter::new(send_data, first_uri)), + ); + + unsafe { + first_dragging_item.setDraggingFrame_contents( + dragging_rect, + drag_image.as_ref().map(AsRef::as_ref), + ) + }; + + pasteboard_items.insert(0, first_dragging_item); + + let pasteboard_items = NSArray::from_retained_slice(&pasteboard_items); + + let session = delegate.window().beginDraggingSessionWithItems_event_source( + &pasteboard_items, + &event, + ProtocolObject::from_ref(&*delegate), + ); + + let id = DataTransferId::from_raw(session.draggingSequenceNumber() as i64); + + delegate.view().set_dragging_session(session, drag_operation); + + Ok(id) + }) + .ok_or(RequestError::Ignored)? + } +} + +/// An operation was attempted on a data transfer ID, but that ID was invalid. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct UnknownDataTransfer(pub DataTransferId); + +impl fmt::Display for UnknownDataTransfer { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let id = self.0.into_raw(); + write!(f, "Unknown data transfer with ID {id}") + } +} + +impl std::error::Error for UnknownDataTransfer {} + +impl rwh_06::HasDisplayHandle for ActiveEventLoop { + fn display_handle(&self) -> Result, rwh_06::HandleError> { + let raw = rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new()); + unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) } + } +} + +#[derive(Debug)] +pub struct EventLoop { + /// Store a reference to the application for convenience. + /// + /// We intentionally don't store `WinitApplication` since we want to have + /// the possibility of swapping that out at some point. + app: Retained, + app_state: Rc, + + window_target: ActiveEventLoop, + + // Since macOS 10.11, we no longer need to remove the observers before they are deallocated; + // the system instead cleans it up next time it would have posted a notification to it. + // + // Though we do still need to keep the observers around to prevent them from being deallocated. + _did_finish_launching_observer: Retained>, + _will_terminate_observer: Retained>, + + _tracing_observers: Option<(MainRunLoopObserver, MainRunLoopObserver)>, + _before_waiting_observer: MainRunLoopObserver, + _after_waiting_observer: MainRunLoopObserver, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct PlatformSpecificEventLoopAttributes { + pub activation_policy: Option, + pub default_menu: bool, + pub activate_ignoring_other_apps: bool, +} + +impl Default for PlatformSpecificEventLoopAttributes { + fn default() -> Self { + Self { activation_policy: None, default_menu: true, activate_ignoring_other_apps: true } + } +} + +impl EventLoop { + pub fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Result { + let mtm = MainThreadMarker::new() + .expect("on macOS, `EventLoop` must be created on the main thread!"); + + let activation_policy = match attributes.activation_policy { + None => None, + Some(ActivationPolicy::Regular) => Some(NSApplicationActivationPolicy::Regular), + Some(ActivationPolicy::Accessory) => Some(NSApplicationActivationPolicy::Accessory), + Some(ActivationPolicy::Prohibited) => Some(NSApplicationActivationPolicy::Prohibited), + }; + + let app_state = AppState::setup_global( + mtm, + activation_policy, + attributes.default_menu, + attributes.activate_ignoring_other_apps, + ) + .ok_or_else(|| EventLoopError::RecreationAttempt)?; + + // Initialize the application (if it has not already been). + let app = NSApplication::sharedApplication(mtm); + + // Override `sendEvent:` on the application to forward to our application state. + override_send_event(&app); + + let center = NSNotificationCenter::defaultCenter(); + + let weak_app_state = Rc::downgrade(&app_state); + let _did_finish_launching_observer = create_observer( + ¢er, + // `applicationDidFinishLaunching:` + unsafe { NSApplicationDidFinishLaunchingNotification }, + move |notification| { + let _entered = debug_span!("NSApplicationDidFinishLaunchingNotification").entered(); + if let Some(app_state) = weak_app_state.upgrade() { + app_state.did_finish_launching(notification); + } + }, + ); + + let weak_app_state = Rc::downgrade(&app_state); + let _will_terminate_observer = create_observer( + ¢er, + // `applicationWillTerminate:` + unsafe { NSApplicationWillTerminateNotification }, + move |notification| { + let _entered = debug_span!("NSApplicationWillTerminateNotification").entered(); + if let Some(app_state) = weak_app_state.upgrade() { + app_state.will_terminate(notification); + } + }, + ); + + let main_loop = MainRunLoop::get(mtm); + let mode = unsafe { kCFRunLoopCommonModes }.unwrap(); + + // Tracing observers have the lowest and highest orderings. + let _tracing_observers = tracing_observers(mtm).inspect(|(start, end)| { + main_loop.add_observer(start, mode); + main_loop.add_observer(end, mode); + }); + + let app_state_clone = Rc::clone(&app_state); + let _before_waiting_observer = MainRunLoopObserver::new( + mtm, + CFRunLoopActivity::BeforeWaiting, + true, + // Queued with the second-lowest priority (tracing observers use the lowest) to ensure + // it is processed after other observers. + CFIndex::MAX - 1, + move |_| app_state_clone.cleared(), + ); + main_loop.add_observer(&_before_waiting_observer, mode); + + let app_state_clone = Rc::clone(&app_state); + let _after_waiting_observer = MainRunLoopObserver::new( + mtm, + CFRunLoopActivity::AfterWaiting, + true, + // Queued with the second-highest priority (tracing observers use the highest) to + // ensure it is processed before other observers. + CFIndex::MIN + 1, + move |_| app_state_clone.wakeup(), + ); + main_loop.add_observer(&_after_waiting_observer, mode); + + Ok(EventLoop { + app, + app_state: app_state.clone(), + window_target: ActiveEventLoop { app_state, mtm }, + _did_finish_launching_observer, + _will_terminate_observer, + _tracing_observers, + _before_waiting_observer, + _after_waiting_observer, + }) + } + + pub fn window_target(&self) -> &dyn RootActiveEventLoop { + &self.window_target + } + + // NB: we don't base this on `pump_events` because for `MacOs` we can't support + // `pump_events` elegantly (we just ask to run the loop for a "short" amount of + // time and so a layered implementation would end up using a lot of CPU due to + // redundant wake ups. + pub fn run_app_on_demand( + &mut self, + app: A, + ) -> Result<(), EventLoopError> { + self.app_state.clear_exit(); + self.app_state.set_event_handler(app, || { + autoreleasepool(|_| { + // clear / normalize pump_events state + self.app_state.set_wait_timeout(None); + self.app_state.set_stop_before_wait(false); + self.app_state.set_stop_after_wait(false); + self.app_state.set_stop_on_redraw(false); + + if self.app_state.is_launched() { + debug_assert!(!self.app_state.is_running()); + self.app_state.set_is_running(true); + self.app_state.dispatch_init_events(); + } + + // NOTE: Make sure to not run the application re-entrantly, as that'd be confusing. + self.app.run(); + + self.app_state.internal_exit() + }) + }); + + Ok(()) + } + + pub fn pump_app_events( + &mut self, + timeout: Option, + app: A, + ) -> PumpStatus { + self.app_state.set_event_handler(app, || { + autoreleasepool(|_| { + // As a special case, if the application hasn't been launched yet then we at least + // run the loop until it has fully launched. + if !self.app_state.is_launched() { + debug_assert!(!self.app_state.is_running()); + + self.app_state.set_stop_on_launch(); + self.app.run(); + + // Note: we dispatch `NewEvents(Init)` + `Resumed` events after the application + // has launched + } else if !self.app_state.is_running() { + // Even though the application may have been launched, it's possible we aren't + // running if the `EventLoop` was run before and has since + // exited. This indicates that we just starting to re-run + // the same `EventLoop` again. + self.app_state.set_is_running(true); + self.app_state.dispatch_init_events(); + } else { + // Only run for as long as the given `Duration` allows so we don't block the + // external loop. + match timeout { + Some(Duration::ZERO) => { + self.app_state.set_wait_timeout(None); + self.app_state.set_stop_before_wait(true); + }, + Some(duration) => { + self.app_state.set_stop_before_wait(false); + let timeout = Instant::now() + duration; + self.app_state.set_wait_timeout(Some(timeout)); + self.app_state.set_stop_after_wait(true); + }, + None => { + self.app_state.set_wait_timeout(None); + self.app_state.set_stop_before_wait(false); + self.app_state.set_stop_after_wait(true); + }, + } + self.app_state.set_stop_on_redraw(true); + self.app.run(); + } + + if self.app_state.exiting() { + self.app_state.internal_exit(); + PumpStatus::Exit(0) + } else { + PumpStatus::Continue + } + }) + }) + } +} + +impl EventLoopProvider for EventLoop { + fn run_app( + mut self, + mut app: A, + ) -> Result<(), EventLoopError> { + let result = self.run_app_on_demand(&mut app); + // SAFETY: unsure that the state is dropped before the exit from the event loop. + drop(app); + result + } + + fn create_proxy(&self) -> CoreEventLoopProxy { + self.window_target().create_proxy() + } + + fn owned_display_handle(&self) -> CoreOwnedDisplayHandle { + self.window_target().owned_display_handle() + } + + fn listen_device_events(&self, allowed: DeviceEvents) { + self.window_target().listen_device_events(allowed); + } + + fn set_control_flow(&self, control_flow: ControlFlow) { + self.window_target().set_control_flow(control_flow); + } + + fn create_custom_cursor( + &self, + custom_cursor: CustomCursorSource, + ) -> Result { + self.window_target().create_custom_cursor(custom_cursor) + } +} + +pub(crate) struct OwnedDisplayHandle; + +impl HasDisplayHandle for OwnedDisplayHandle { + fn display_handle(&self) -> Result, rwh_06::HandleError> { + let raw = rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new()); + unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) } + } +} + +pub(super) fn stop_app_immediately(app: &NSApplication) { + autoreleasepool(|_| { + app.stop(None); + // To stop event loop immediately, we need to post some event here. + // See: https://stackoverflow.com/questions/48041279/stopping-the-nsapplication-main-event-loop/48064752#48064752 + app.postEvent_atStart(&dummy_event().unwrap(), true); + }); +} + +/// Tell all windows to close. +/// +/// This will synchronously trigger `WindowEvent::Destroyed` within +/// `windowWillClose:`, giving the application one last chance to handle +/// those events. It doesn't matter if the user also ends up closing the +/// windows in `Window`'s `Drop` impl, once a window has been closed once, it +/// stays closed. +/// +/// This ensures that no windows linger on after the event loop has exited, +/// see . +pub(super) fn notify_windows_of_exit(app: &NSApplication) { + for window in app.windows() { + window.close(); + } +} diff --git a/patches/winit-appkit/src/ffi.rs b/patches/winit-appkit/src/ffi.rs new file mode 100644 index 0000000000..1fd11c5425 --- /dev/null +++ b/patches/winit-appkit/src/ffi.rs @@ -0,0 +1,76 @@ +// TODO: Upstream these + +#![allow(non_upper_case_globals)] + +use std::ffi::c_void; + +use objc2_core_foundation::{CFString, CFUUID, cf_type}; +use objc2_core_graphics::CGDirectDisplayID; + +pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB"; +pub const IO32BitDirectPixels: &str = "--------RRRRRRRRGGGGGGGGBBBBBBBB"; +pub const kIO30BitDirectPixels: &str = "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB"; +pub const kIO64BitDirectPixels: &str = "-16R16G16B16"; + +// `CGDisplayCreateUUIDFromDisplayID` comes from the `ColorSync` framework. +// However, that framework was only introduced "publicly" in macOS 10.13. +// +// Since we want to support older versions, we can't link to `ColorSync` +// directly. Fortunately, it has always been available as a subframework of +// `ApplicationServices`, see: +// https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/OSX_Technology_Overview/SystemFrameworks/SystemFrameworks.html#//apple_ref/doc/uid/TP40001067-CH210-BBCFFIEG +#[link(name = "ApplicationServices", kind = "framework")] +unsafe extern "C" { + pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> *mut CFUUID; + + pub fn CGDisplayGetDisplayIDFromUUID(uuid: &CFUUID) -> CGDirectDisplayID; +} + +#[repr(transparent)] +pub struct TISInputSource(std::ffi::c_void); + +cf_type!( + unsafe impl TISInputSource {} +); + +#[repr(transparent)] +pub struct UCKeyboardLayout(std::ffi::c_void); + +pub type OptionBits = u32; +pub type UniCharCount = std::os::raw::c_ulong; +pub type UniChar = std::os::raw::c_ushort; +pub type OSStatus = i32; + +#[allow(non_upper_case_globals)] +pub const kUCKeyActionDisplay: u16 = 3; +#[allow(non_upper_case_globals)] +pub const kUCKeyTranslateNoDeadKeysMask: OptionBits = 1; + +#[link(name = "Carbon", kind = "framework")] +unsafe extern "C" { + pub static kTISPropertyUnicodeKeyLayoutData: &'static CFString; + + #[allow(non_snake_case)] + pub fn TISGetInputSourceProperty( + inputSource: &TISInputSource, + propertyKey: &CFString, + ) -> *mut c_void; + + pub fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut TISInputSource; + + pub fn LMGetKbdType() -> u8; + + #[allow(non_snake_case)] + pub fn UCKeyTranslate( + keyLayoutPtr: *const UCKeyboardLayout, + virtualKeyCode: u16, + keyAction: u16, + modifierKeyState: u32, + keyboardType: u32, + keyTranslateOptions: OptionBits, + deadKeyState: *mut u32, + maxStringLength: UniCharCount, + actualStringLength: *mut UniCharCount, + unicodeString: *mut UniChar, + ) -> OSStatus; +} diff --git a/patches/winit-appkit/src/lib.rs b/patches/winit-appkit/src/lib.rs new file mode 100644 index 0000000000..29c96dbf2a --- /dev/null +++ b/patches/winit-appkit/src/lib.rs @@ -0,0 +1,742 @@ +//! # macOS / AppKit +//! +//! Winit has [the same macOS version requirements as `rustc`][rustc-macos-version], and is tested +//! once in a while on as low as macOS 10.14. +//! +//! [rustc-macos-version]: https://doc.rust-lang.org/rustc/platform-support/apple-darwin.html#os-version +//! +//! ## Custom `NSApplicationDelegate` +//! +//! Winit usually handles everything related to the lifecycle events of the application. Sometimes, +//! though, you might want to do more niche stuff, such as [handle when the user re-activates the +//! application][reopen]. Such functionality is not exposed directly in Winit, since it would +//! increase the API surface by quite a lot. +//! +//! [reopen]: https://developer.apple.com/documentation/appkit/nsapplicationdelegate/1428638-applicationshouldhandlereopen?language=objc +//! +//! Instead, Winit guarantees that it will not register an application delegate, so the solution is +//! to register your own application delegate, as outlined in the following example (see +//! `objc2-app-kit` for more detailed information). +//! ``` +//! use objc2::rc::Retained; +//! use objc2::runtime::ProtocolObject; +//! use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send}; +//! use objc2_app_kit::{NSApplication, NSApplicationDelegate}; +//! use objc2_foundation::{NSArray, NSObject, NSObjectProtocol, NSURL}; +//! use winit::event_loop::EventLoop; +//! +//! define_class!( +//! #[unsafe(super(NSObject))] +//! #[thread_kind = MainThreadOnly] +//! #[name = "AppDelegate"] +//! struct AppDelegate; +//! +//! unsafe impl NSObjectProtocol for AppDelegate {} +//! +//! unsafe impl NSApplicationDelegate for AppDelegate { +//! #[unsafe(method(application:openURLs:))] +//! fn application_openURLs(&self, application: &NSApplication, urls: &NSArray) { +//! // Note: To specifically get `application:openURLs:` to work, you _might_ +//! // have to bundle your application. This is not done in this example. +//! println!("open urls: {application:?}, {urls:?}"); +//! } +//! } +//! ); +//! +//! impl AppDelegate { +//! fn new(mtm: MainThreadMarker) -> Retained { +//! unsafe { msg_send![super(Self::alloc(mtm).set_ivars(())), init] } +//! } +//! } +//! +//! fn main() -> Result<(), Box> { +//! let event_loop = EventLoop::new()?; +//! +//! let mtm = MainThreadMarker::new().unwrap(); +//! let delegate = AppDelegate::new(mtm); +//! // Important: Call `sharedApplication` after `EventLoop::new`, +//! // doing it before is not yet supported. +//! let app = NSApplication::sharedApplication(mtm); +//! app.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); +//! +//! // event_loop.run_app(&mut my_app); +//! Ok(()) +//! } +//! ``` +#![cfg(target_vendor = "apple")] // TODO: Remove once `objc2` allows compiling on all platforms +#![warn(clippy::exhaustive_enums)] + +#[macro_use] +mod util; + +mod app; +mod app_state; +mod cursor; +mod dnd; +mod event; +mod event_loop; +mod ffi; +mod menu; +mod monitor; +mod observer; +mod view; +mod window; +mod window_delegate; + +use std::os::raw::c_void; + +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; +#[doc(inline)] +pub use winit_core::application::macos::ApplicationHandlerExtMacOS; +use winit_core::event_loop::ActiveEventLoop; +use winit_core::monitor::MonitorHandle; +use winit_core::window::{PlatformWindowAttributes, Window}; + +pub use self::dnd::{Pasteboard, PasteboardType, PasteboardValue}; +pub use self::event::{physicalkey_to_scancode, scancode_to_physicalkey}; +use self::event_loop::ActiveEventLoop as AppKitActiveEventLoop; +pub use self::event_loop::{EventLoop, PlatformSpecificEventLoopAttributes}; +use self::monitor::MonitorHandle as AppKitMonitorHandle; +use self::window::Window as AppKitWindow; + +/// Additional methods on [`Window`] that are specific to MacOS. +pub trait WindowExtMacOS { + /// Returns whether or not the window is in simple fullscreen mode. + fn simple_fullscreen(&self) -> bool; + + /// Toggles a fullscreen mode that doesn't require a new macOS space. + /// Returns a boolean indicating whether the transition was successful (this + /// won't work if the window was already in the native fullscreen). + /// + /// This is how fullscreen used to work on macOS in versions before Lion. + /// And allows the user to have a fullscreen window without using another + /// space or taking control over the entire monitor. + /// + /// Make sure you only draw your important content inside the safe area so that it does not + /// overlap with the notch on newer devices, see [`Window::safe_area`] for details. + fn set_simple_fullscreen(&self, fullscreen: bool) -> bool; + + /// Returns whether or not the window has shadow. + fn has_shadow(&self) -> bool; + + /// Sets whether or not the window has shadow. + fn set_has_shadow(&self, has_shadow: bool); + + /// Group windows together by using the same tabbing identifier. + /// + /// + fn set_tabbing_identifier(&self, identifier: &str); + + /// Returns the window's tabbing identifier. + fn tabbing_identifier(&self) -> String; + + /// Select next tab. + fn select_next_tab(&self); + + /// Select previous tab. + fn select_previous_tab(&self); + + /// Select the tab with the given index. + /// + /// Will no-op when the index is out of bounds. + fn select_tab_at_index(&self, index: usize); + + /// Get the number of tabs in the window tab group. + fn num_tabs(&self) -> usize; + + /// Get the window's edit state. + /// + /// # Examples + /// + /// ```ignore + /// WindowEvent::CloseRequested => { + /// if window.is_document_edited() { + /// // Show the user a save pop-up or similar + /// } else { + /// // Close the window + /// drop(window); + /// } + /// } + /// ``` + fn is_document_edited(&self) -> bool; + + /// Put the window in a state which indicates a file save is required. + fn set_document_edited(&self, edited: bool); + + /// Set option as alt behavior as described in [`OptionAsAlt`]. + /// + /// This will ignore diacritical marks and accent characters from + /// being processed as received characters. Instead, the input + /// device's raw character will be placed in event queues with the + /// Alt modifier set. + fn set_option_as_alt(&self, option_as_alt: OptionAsAlt); + + /// Getter for the [`WindowExtMacOS::set_option_as_alt`]. + fn option_as_alt(&self) -> OptionAsAlt; + + /// Disable the Menu Bar and Dock in Simple or Borderless Fullscreen mode. Useful for games. + /// The effect is applied when [`WindowExtMacOS::set_simple_fullscreen`] or + /// [`Window::set_fullscreen`] is called. + fn set_borderless_game(&self, borderless_game: bool); + + /// Getter for the [`WindowExtMacOS::set_borderless_game`]. + fn is_borderless_game(&self) -> bool; + + /// Makes the titlebar bigger, effectively adding more space around the + /// window controls if the titlebar is invisible. + fn set_unified_titlebar(&self, unified_titlebar: bool); + + /// Getter for the [`WindowExtMacOS::set_unified_titlebar`]. + fn unified_titlebar(&self) -> bool; + + /// Sets whether the window can be shown on the same Space as a fullscreen window. + /// + /// This corresponds to [`NSWindowCollectionBehaviorFullScreenAuxiliary`], and is useful + /// for floating palettes, inspectors and other secondary windows accompanying a fullscreen + /// window. Without it, ordering a new window on screen while another window of the + /// application is fullscreen on the active Space makes macOS switch Spaces or attempt + /// Split View tiling. + /// + /// A window marked as fullscreen auxiliary cannot itself enter (native) fullscreen; + /// [`Window::set_fullscreen`] will warn and do nothing. Call + /// `set_fullscreen_auxiliary(false)` first if you want to make the window fullscreen. + /// + /// [`NSWindowCollectionBehaviorFullScreenAuxiliary`]: https://developer.apple.com/documentation/appkit/nswindow/collectionbehavior-swift.struct/fullscreenauxiliary?language=objc + /// [`Window::set_fullscreen`]: winit_core::window::Window::set_fullscreen + fn set_fullscreen_auxiliary(&self, fullscreen_auxiliary: bool); + + /// Getter for the [`WindowExtMacOS::set_fullscreen_auxiliary`]. + fn fullscreen_auxiliary(&self) -> bool; + + /// Sets the material drawn behind the window when it is blurred. + /// + /// Takes effect the next time the window is blurred, and immediately if it already is. See + /// [`Window::set_blur`]. + /// + /// [`Window::set_blur`]: winit_core::window::Window::set_blur + fn set_blur_material(&self, blur_material: BlurMaterial); + + /// Getter for the [`WindowExtMacOS::set_blur_material`]. + fn blur_material(&self) -> BlurMaterial; +} + +impl WindowExtMacOS for dyn Window + '_ { + #[inline] + fn simple_fullscreen(&self) -> bool { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.simple_fullscreen()) + } + + #[inline] + fn set_simple_fullscreen(&self, fullscreen: bool) -> bool { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen)) + } + + #[inline] + fn has_shadow(&self) -> bool { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.has_shadow()) + } + + #[inline] + fn set_has_shadow(&self, has_shadow: bool) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_has_shadow(has_shadow)); + } + + #[inline] + fn set_tabbing_identifier(&self, identifier: &str) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier)) + } + + #[inline] + fn tabbing_identifier(&self) -> String { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.tabbing_identifier()) + } + + #[inline] + fn select_next_tab(&self) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.select_next_tab()); + } + + #[inline] + fn select_previous_tab(&self) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.select_previous_tab()); + } + + #[inline] + fn select_tab_at_index(&self, index: usize) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.select_tab_at_index(index)); + } + + #[inline] + fn num_tabs(&self) -> usize { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.num_tabs()) + } + + #[inline] + fn is_document_edited(&self) -> bool { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.is_document_edited()) + } + + #[inline] + fn set_document_edited(&self, edited: bool) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_document_edited(edited)); + } + + #[inline] + fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_option_as_alt(option_as_alt)); + } + + #[inline] + fn option_as_alt(&self) -> OptionAsAlt { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.option_as_alt()) + } + + #[inline] + fn set_borderless_game(&self, borderless_game: bool) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.set_borderless_game(borderless_game)) + } + + #[inline] + fn is_borderless_game(&self) -> bool { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.is_borderless_game()) + } + + #[inline] + fn set_unified_titlebar(&self, unified_titlebar: bool) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.set_unified_titlebar(unified_titlebar)) + } + + #[inline] + fn unified_titlebar(&self) -> bool { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.unified_titlebar()) + } + + #[inline] + fn set_fullscreen_auxiliary(&self, fullscreen_auxiliary: bool) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_fullscreen_auxiliary(fullscreen_auxiliary)) + } + + #[inline] + fn fullscreen_auxiliary(&self) -> bool { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.fullscreen_auxiliary()) + } + + #[inline] + fn set_blur_material(&self, blur_material: BlurMaterial) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_blur_material(blur_material)) + } + + #[inline] + fn blur_material(&self) -> BlurMaterial { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.blur_material()) + } +} + +/// Corresponds to `NSApplicationActivationPolicy`. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[non_exhaustive] +pub enum ActivationPolicy { + /// Corresponds to `NSApplicationActivationPolicyRegular`. + #[default] + Regular, + + /// Corresponds to `NSApplicationActivationPolicyAccessory`. + Accessory, + + /// Corresponds to `NSApplicationActivationPolicyProhibited`. + Prohibited, +} + +/// Window attributes that are specific to MacOS. +/// +/// **Note:** Properties dealing with the titlebar will be overwritten by the +/// [`WindowAttributes::with_decorations`] method: +/// - `with_titlebar_transparent` +/// - `with_title_hidden` +/// - `with_titlebar_hidden` +/// - `with_titlebar_buttons_hidden` +/// - `with_fullsize_content_view` +/// +/// [`WindowAttributes::with_decorations`]: crate::window::WindowAttributes::with_decorations +#[derive(Clone, Debug, PartialEq)] +pub struct WindowAttributesMacOS { + pub(crate) movable_by_window_background: bool, + pub(crate) titlebar_transparent: bool, + pub(crate) title_hidden: bool, + pub(crate) titlebar_hidden: bool, + pub(crate) titlebar_buttons_hidden: bool, + pub(crate) fullsize_content_view: bool, + pub(crate) disallow_hidpi: bool, + pub(crate) has_shadow: bool, + pub(crate) tabbing_identifier: Option, + pub(crate) option_as_alt: OptionAsAlt, + pub(crate) borderless_game: bool, + pub(crate) unified_titlebar: bool, + pub(crate) panel: bool, + pub(crate) fullscreen_auxiliary: bool, + pub(crate) blur_material: BlurMaterial, +} + +impl WindowAttributesMacOS { + /// Enables click-and-drag behavior for the entire window, not just the titlebar. + #[inline] + pub fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> Self { + self.movable_by_window_background = movable_by_window_background; + self + } + + /// Sets the material drawn behind the window when it is blurred. + /// + /// Has no effect unless the window is blurred, see [`Window::set_blur`]. + /// + /// [`Window::set_blur`]: winit_core::window::Window::set_blur + #[inline] + pub fn with_blur_material(mut self, blur_material: BlurMaterial) -> Self { + self.blur_material = blur_material; + self + } + + /// Makes the titlebar transparent and allows the content to appear behind it. + #[inline] + pub fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self { + self.titlebar_transparent = titlebar_transparent; + self + } + + /// Hides the window titlebar. + #[inline] + pub fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> Self { + self.titlebar_hidden = titlebar_hidden; + self + } + + /// Hides the window titlebar buttons. + #[inline] + pub fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> Self { + self.titlebar_buttons_hidden = titlebar_buttons_hidden; + self + } + + /// Hides the window title. + #[inline] + pub fn with_title_hidden(mut self, title_hidden: bool) -> Self { + self.title_hidden = title_hidden; + self + } + + /// Makes the window content appear behind the titlebar. + #[inline] + pub fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> Self { + self.fullsize_content_view = fullsize_content_view; + self + } + + #[inline] + pub fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> Self { + self.disallow_hidpi = disallow_hidpi; + self + } + + #[inline] + pub fn with_has_shadow(mut self, has_shadow: bool) -> Self { + self.has_shadow = has_shadow; + self + } + + /// Defines the window tabbing identifier. + /// + /// + #[inline] + pub fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self { + self.tabbing_identifier.replace(tabbing_identifier.to_string()); + self + } + + /// Set how the Option keys are interpreted. + /// + /// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set. + #[inline] + pub fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> Self { + self.option_as_alt = option_as_alt; + self + } + + /// See [`WindowExtMacOS::set_borderless_game`] for details on what this means if set. + #[inline] + pub fn with_borderless_game(mut self, borderless_game: bool) -> Self { + self.borderless_game = borderless_game; + self + } + + /// See [`WindowExtMacOS::set_unified_titlebar`] for details on what this means if set. + #[inline] + pub fn with_unified_titlebar(mut self, unified_titlebar: bool) -> Self { + self.unified_titlebar = unified_titlebar; + self + } + + /// Use [`NSPanel`] window with [`NonactivatingPanel`] window style mask instead of + /// [`NSWindow`]. + /// + /// [`NSWindow`]: https://developer.apple.com/documentation/appkit/NSWindow?language=objc + /// [`NSPanel`]: https://developer.apple.com/documentation/appkit/NSPanel?language=objc + /// [`NonactivatingPanel`]: https://developer.apple.com/documentation/appkit/nswindow/stylemask-swift.struct/nonactivatingpanel?language=objc + #[inline] + pub fn with_panel(mut self, panel: bool) -> Self { + self.panel = panel; + self + } + + /// See [`WindowExtMacOS::set_fullscreen_auxiliary`] for details on what this means if set. + /// + /// Contrary to the runtime setter, setting this attribute guarantees that the collection + /// behavior is already in place when the window is first ordered on screen, which is + /// required to avoid disturbing an active fullscreen Space. + #[inline] + pub fn with_fullscreen_auxiliary(mut self, fullscreen_auxiliary: bool) -> Self { + self.fullscreen_auxiliary = fullscreen_auxiliary; + self + } +} + +impl Default for WindowAttributesMacOS { + #[inline] + fn default() -> Self { + Self { + movable_by_window_background: false, + titlebar_transparent: false, + title_hidden: false, + titlebar_hidden: false, + titlebar_buttons_hidden: false, + fullsize_content_view: false, + disallow_hidpi: false, + has_shadow: true, + tabbing_identifier: None, + option_as_alt: Default::default(), + borderless_game: false, + unified_titlebar: false, + panel: false, + fullscreen_auxiliary: false, + blur_material: Default::default(), + } + } +} + +impl PlatformWindowAttributes for WindowAttributesMacOS { + fn box_clone(&self) -> Box { + Box::from(self.clone()) + } +} + +pub trait EventLoopBuilderExtMacOS { + /// Sets the activation policy for the application. If used, this will override + /// any relevant settings provided in the package manifest. + /// For instance, `with_activation_policy(ActivationPolicy::Regular)` will prevent + /// the application from running as an "agent", even if LSUIElement is set to true. + /// + /// If unused, the Winit will honor the package manifest. + /// + /// # Example + /// + /// Set the activation policy to "accessory". + /// + /// ``` + /// use winit::event_loop::EventLoop; + /// #[cfg(target_os = "macos")] + /// use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS}; + /// + /// let mut builder = EventLoop::builder(); + /// #[cfg(target_os = "macos")] + /// builder.with_activation_policy(ActivationPolicy::Accessory); + /// # if false { // We can't test this part + /// let event_loop = builder.build(); + /// # } + /// ``` + fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self; + + /// Used to control whether a default menubar menu is created. + /// + /// Menu creation is enabled by default. + /// + /// # Example + /// + /// Disable creating a default menubar. + /// + /// ``` + /// use winit::event_loop::EventLoop; + /// #[cfg(target_os = "macos")] + /// use winit::platform::macos::EventLoopBuilderExtMacOS; + /// + /// let mut builder = EventLoop::builder(); + /// #[cfg(target_os = "macos")] + /// builder.with_default_menu(false); + /// # if false { // We can't test this part + /// let event_loop = builder.build(); + /// # } + /// ``` + fn with_default_menu(&mut self, enable: bool) -> &mut Self; + + /// Used to prevent the application from automatically activating when launched if + /// another application is already active. + /// + /// The default behavior is to ignore other applications and activate when launched. + fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self; +} + +/// Additional methods on [`MonitorHandle`] that are specific to MacOS. +pub trait MonitorHandleExtMacOS { + /// Returns a pointer to the NSScreen representing this monitor. + fn ns_screen(&self) -> Option<*mut c_void>; +} + +impl MonitorHandleExtMacOS for MonitorHandle { + fn ns_screen(&self) -> Option<*mut c_void> { + let monitor = self.cast_ref::().unwrap(); + // SAFETY: We only use the marker to get a pointer + let mtm = unsafe { objc2::MainThreadMarker::new_unchecked() }; + monitor.ns_screen(mtm).map(|s| objc2::rc::Retained::as_ptr(&s) as _) + } +} + +/// Additional methods on [`ActiveEventLoop`] that are specific to macOS. +pub trait ActiveEventLoopExtMacOS { + /// Hide the entire application. In most applications this is typically triggered with + /// Command-H. + fn hide_application(&self); + /// Hide the other applications. In most applications this is typically triggered with + /// Command+Option-H. + fn hide_other_applications(&self); + /// Set whether the system can automatically organize windows into tabs. + /// + /// + fn set_allows_automatic_window_tabbing(&self, enabled: bool); + /// Returns whether the system can automatically organize windows into tabs. + fn allows_automatic_window_tabbing(&self) -> bool; +} + +impl ActiveEventLoopExtMacOS for dyn ActiveEventLoop + '_ { + fn hide_application(&self) { + let event_loop = + self.cast_ref::().expect("non macOS event loop on macOS"); + event_loop.hide_application() + } + + fn hide_other_applications(&self) { + let event_loop = + self.cast_ref::().expect("non macOS event loop on macOS"); + event_loop.hide_other_applications() + } + + fn set_allows_automatic_window_tabbing(&self, enabled: bool) { + let event_loop = + self.cast_ref::().expect("non macOS event loop on macOS"); + event_loop.set_allows_automatic_window_tabbing(enabled); + } + + fn allows_automatic_window_tabbing(&self) -> bool { + let event_loop = + self.cast_ref::().expect("non macOS event loop on macOS"); + event_loop.allows_automatic_window_tabbing() + } +} + +/// Option as alt behavior. +/// +/// The default is `None`. +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[allow(clippy::exhaustive_enums)] +pub enum OptionAsAlt { + /// The left `Option` key is treated as `Alt`. + OnlyLeft, + + /// The right `Option` key is treated as `Alt`. + OnlyRight, + + /// Both `Option` keys are treated as `Alt`. + Both, + + /// No special handling is applied for `Option` key. + #[default] + None, +} + +/// The material drawn behind a blurred window, corresponding to `NSVisualEffectMaterial`. +/// +/// Only the materials that AppKit renders behind the window are listed. The remaining +/// `NSVisualEffectMaterial` values are meant for opaque backgrounds, and draw a placeholder +/// rather than a blur when used this way. +/// +/// The material determines the tint and translucency of the blur, so the result is not an +/// untinted blur of a chosen radius; AppKit exposes no public API for that. Enable the +/// `private-apple-apis` Cargo feature for the private one, which this setting then no longer +/// affects. +/// +/// See [`Window::set_blur`] for the blur itself. +/// +/// [`Window::set_blur`]: winit_core::window::Window::set_blur +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[non_exhaustive] +pub enum BlurMaterial { + /// Corresponds to `NSVisualEffectMaterialFullScreenUI`. + /// + /// Tints the least of the available materials, making it the closest to a plain backdrop + /// blur. This is the default. + #[default] + FullScreenUI, + + /// Corresponds to `NSVisualEffectMaterialHUDWindow`. + HudWindow, + + /// Corresponds to `NSVisualEffectMaterialMenu`. + Menu, + + /// Corresponds to `NSVisualEffectMaterialPopover`. + Popover, + + /// Corresponds to `NSVisualEffectMaterialSidebar`. + Sidebar, + + /// Corresponds to `NSVisualEffectMaterialSelection`. + Selection, + + /// Corresponds to `NSVisualEffectMaterialTitlebar`. + Titlebar, + + /// Corresponds to `NSVisualEffectMaterialHeaderView`. + HeaderView, + + /// Corresponds to `NSVisualEffectMaterialToolTip`. + ToolTip, + + /// Corresponds to `NSVisualEffectMaterialUnderWindowBackground`. + /// + /// Tints heavily towards the window's background colour, which can leave the blur barely + /// visible over light content. + UnderWindowBackground, +} diff --git a/patches/winit-appkit/src/menu.rs b/patches/winit-appkit/src/menu.rs new file mode 100644 index 0000000000..10b0075be2 --- /dev/null +++ b/patches/winit-appkit/src/menu.rs @@ -0,0 +1,107 @@ +use objc2::rc::Retained; +use objc2::runtime::Sel; +use objc2::{MainThreadMarker, sel}; +use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSMenu, NSMenuItem}; +use objc2_foundation::{NSBundle, NSProcessInfo, NSString, ns_string}; + +struct KeyEquivalent<'a> { + key: &'a NSString, + masks: Option, +} + +pub fn initialize(app: &NSApplication) { + let mtm = MainThreadMarker::from(app); + let menubar = NSMenu::new(mtm); + let app_menu_item = NSMenuItem::new(mtm); + menubar.addItem(&app_menu_item); + + let app_menu = NSMenu::new(mtm); + let process_name = match NSBundle::mainBundle().name() { + Some(bundle_name) => bundle_name, + None => NSProcessInfo::processInfo().processName(), + }; + + // About menu item + let about_item_title = ns_string!("About ").stringByAppendingString(&process_name); + let about_item = + menu_item(mtm, &about_item_title, Some(sel!(orderFrontStandardAboutPanel:)), None); + + // Services menu item + let services_menu = NSMenu::new(mtm); + let services_item = menu_item(mtm, ns_string!("Services"), None, None); + services_item.setSubmenu(Some(&services_menu)); + + // Separator menu item + let sep_first = NSMenuItem::separatorItem(mtm); + + // Hide application menu item + let hide_item_title = ns_string!("Hide ").stringByAppendingString(&process_name); + let hide_item = menu_item( + mtm, + &hide_item_title, + Some(sel!(hide:)), + Some(KeyEquivalent { key: ns_string!("h"), masks: None }), + ); + + // Hide other applications menu item + let hide_others_item_title = ns_string!("Hide Others"); + let hide_others_item = menu_item( + mtm, + hide_others_item_title, + Some(sel!(hideOtherApplications:)), + Some(KeyEquivalent { + key: ns_string!("h"), + masks: Some(NSEventModifierFlags::Option | NSEventModifierFlags::Command), + }), + ); + + // Show applications menu item + let show_all_item_title = ns_string!("Show All"); + let show_all_item = + menu_item(mtm, show_all_item_title, Some(sel!(unhideAllApplications:)), None); + + // Separator menu item + let sep = NSMenuItem::separatorItem(mtm); + + // Quit application menu item + let quit_item_title = ns_string!("Quit ").stringByAppendingString(&process_name); + let quit_item = menu_item( + mtm, + &quit_item_title, + Some(sel!(terminate:)), + Some(KeyEquivalent { key: ns_string!("q"), masks: None }), + ); + + app_menu.addItem(&about_item); + app_menu.addItem(&sep_first); + app_menu.addItem(&services_item); + app_menu.addItem(&hide_item); + app_menu.addItem(&hide_others_item); + app_menu.addItem(&show_all_item); + app_menu.addItem(&sep); + app_menu.addItem(&quit_item); + app_menu_item.setSubmenu(Some(&app_menu)); + + app.setServicesMenu(Some(&services_menu)); + app.setMainMenu(Some(&menubar)); +} + +fn menu_item( + mtm: MainThreadMarker, + title: &NSString, + selector: Option, + key_equivalent: Option>, +) -> Retained { + let (key, masks) = match key_equivalent { + Some(ke) => (ke.key, ke.masks), + None => (ns_string!(""), None), + }; + let item = unsafe { + NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), title, selector, key) + }; + if let Some(masks) = masks { + item.setKeyEquivalentModifierMask(masks) + } + + item +} diff --git a/patches/winit-appkit/src/monitor.rs b/patches/winit-appkit/src/monitor.rs new file mode 100644 index 0000000000..cc4a15e52f --- /dev/null +++ b/patches/winit-appkit/src/monitor.rs @@ -0,0 +1,418 @@ +#![allow(clippy::unnecessary_cast)] + +use std::collections::VecDeque; +use std::num::{NonZeroU16, NonZeroU32}; +use std::ptr::NonNull; +use std::{fmt, ptr}; + +use dispatch2::run_on_main; +use dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; +use objc2::MainThreadMarker; +use objc2::rc::Retained; +use objc2_app_kit::NSScreen; +use objc2_core_foundation::{CFArray, CFRetained, CFUUID}; +use objc2_core_graphics::{ + CGDirectDisplayID, CGDisplayBounds, CGDisplayCopyAllDisplayModes, CGDisplayCopyDisplayMode, + CGDisplayMode, CGDisplayModelNumber, CGGetActiveDisplayList, CGMainDisplayID, +}; +use objc2_core_video::{CVDisplayLink, CVTimeFlags, kCVReturnSuccess}; +use objc2_foundation::{NSNumber, NSPoint, NSRect, ns_string}; +use tracing::warn; +use winit_core::monitor::{MonitorHandleProvider, VideoMode}; + +use super::ffi; +use super::util::cgerr; + +#[derive(Clone)] +pub struct VideoModeHandle { + pub(crate) mode: VideoMode, + pub(crate) monitor: MonitorHandle, + pub(crate) native_mode: NativeDisplayMode, +} + +impl PartialEq for VideoModeHandle { + fn eq(&self, other: &Self) -> bool { + self.monitor == other.monitor && self.mode == other.mode + } +} + +impl Eq for VideoModeHandle {} + +impl std::hash::Hash for VideoModeHandle { + fn hash(&self, state: &mut H) { + self.monitor.hash(state); + } +} + +impl std::fmt::Debug for VideoModeHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VideoModeHandle") + .field("mode", &self.mode) + .field("monitor", &self.monitor) + .finish() + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct NativeDisplayMode(pub CFRetained); + +unsafe impl Send for NativeDisplayMode {} +unsafe impl Sync for NativeDisplayMode {} + +impl VideoModeHandle { + fn new( + monitor: MonitorHandle, + native_mode: NativeDisplayMode, + refresh_rate_millihertz: Option, + ) -> Self { + // The bit-depth is basically always 32 since macOS 10.12. + #[allow(deprecated)] + let pixel_encoding = + CGDisplayMode::pixel_encoding(Some(&native_mode.0)).unwrap().to_string(); + let bit_depth = if pixel_encoding.eq_ignore_ascii_case(ffi::IO32BitDirectPixels) { + NonZeroU16::new(32) + } else if pixel_encoding.eq_ignore_ascii_case(ffi::IO16BitDirectPixels) { + NonZeroU16::new(16) + } else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO30BitDirectPixels) { + NonZeroU16::new(30) + } else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO64BitDirectPixels) { + NonZeroU16::new(64) + } else { + warn!(?pixel_encoding, "unknown bit depth"); + None + }; + + let mode = VideoMode::new( + PhysicalSize::new( + CGDisplayMode::pixel_width(Some(&native_mode.0)) as u32, + CGDisplayMode::pixel_height(Some(&native_mode.0)) as u32, + ), + bit_depth, + refresh_rate_millihertz, + ); + + Self { mode, monitor: monitor.clone(), native_mode } + } +} + +/// `CGDirectDisplayID` is documented as: +/// > a framebuffer, a color correction (gamma) table, and possibly an attached monitor. +/// +/// That is, it doesn't actually represent the monitor itself. Instead, we use the UUID of the +/// monitor, as retrieved from `CGDisplayCreateUUIDFromDisplayID` (this makes the monitor ID stable, +/// even across reboots and video mode changes). +/// +/// NOTE: I'd be perfectly valid to store `[u8; 16]` in here instead, we only store `CFUUID` to +/// avoid having to re-create it when we want to fetch the display ID. +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct MonitorHandle(CFRetained); + +impl MonitorHandle { + /// Internal comparisons of [`MonitorHandle`]s are done first requesting a UUID for the handle. + fn uuid(&self) -> u128 { + u128::from_ne_bytes(self.0.uuid_bytes().into()) + } + + fn display_id(&self) -> CGDirectDisplayID { + unsafe { ffi::CGDisplayGetDisplayIDFromUUID(&self.0) } + } + + #[track_caller] + pub(crate) fn new(display_id: CGDirectDisplayID) -> Option { + // kCGNullDirectDisplay + if display_id == 0 { + // `CGDisplayCreateUUIDFromDisplayID` checks kCGNullDirectDisplay internally. + warn!("constructing monitor from invalid display ID 0; falling back to main monitor"); + } + // SAFETY: Valid to call. + let ptr = unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(display_id) }; + let ptr = NonNull::new(ptr)?; + // SAFETY: `CGDisplayCreateUUIDFromDisplayID` is a "create" function, so the pointer has + // +1 retain count. + let uuid = unsafe { CFRetained::from_raw(ptr) }; + Some(Self(uuid)) + } + + fn refresh_rate_millihertz(&self) -> Option { + let current_display_mode = + NativeDisplayMode(CGDisplayCopyDisplayMode(self.display_id()).unwrap()); + refresh_rate_millihertz(self.display_id(), ¤t_display_mode) + } + + pub fn video_mode_handles(&self) -> impl Iterator + 'static { + let refresh_rate_millihertz = self.refresh_rate_millihertz(); + let monitor = self.clone(); + + let array = unsafe { CGDisplayCopyAllDisplayModes(self.display_id(), None) }; + let modes = if let Some(array) = array { + // SAFETY: `CGDisplayCopyAllDisplayModes` is documented to return an array of + // display modes. + unsafe { CFRetained::cast_unchecked::>(array) } + } else { + // Occasionally, certain CalDigit Thunderbolt Hubs report a spurious monitor during + // sleep/wake/cycling monitors. It tends to have null or 1 video mode only. + // See . + warn!(monitor = ?self, "failed to get a list of display modes"); + CFArray::empty() + }; + + modes.into_iter().map(move |mode| { + let cg_refresh_rate_hertz = CGDisplayMode::refresh_rate(Some(&mode)); + + // CGDisplayModeGetRefreshRate returns 0.0 for any display that + // isn't a CRT + let refresh_rate_millihertz = if cg_refresh_rate_hertz > 0.0 { + NonZeroU32::new((cg_refresh_rate_hertz * 1000.0).round() as u32) + } else { + refresh_rate_millihertz + }; + + VideoModeHandle::new(monitor.clone(), NativeDisplayMode(mode), refresh_rate_millihertz) + }) + } + + /// The monitor's work area, i.e. its bounds minus space reserved by the system for the menu + /// bar and the Dock (see `NSScreen.visibleFrame`). `None` if the underlying + /// `NSScreen` can no longer be found. + pub(crate) fn work_area(&self) -> Option<(PhysicalPosition, PhysicalSize)> { + let scale_factor = self.scale_factor(); + run_on_main(|mtm| { + let visible_frame = self.ns_screen(mtm)?.visibleFrame(); + let origin = flip_window_screen_coordinates(visible_frame); + let position = + LogicalPosition::new(origin.x, origin.y).to_physical::(scale_factor); + let size = LogicalSize::new(visible_frame.size.width, visible_frame.size.height) + .to_physical::(scale_factor); + Some((position, size)) + }) + } + + pub(crate) fn ns_screen(&self, mtm: MainThreadMarker) -> Option> { + let uuid = self.uuid(); + NSScreen::screens(mtm).into_iter().find(|screen| { + let other_native_id = get_display_id(screen); + if let Some(other) = MonitorHandle::new(other_native_id) { + uuid == other.uuid() + } else { + // Display ID was just fetched from live NSScreen, but can still result in `None` + // with certain Thunderbolt docked monitors. + warn!(other_native_id, "comparing against screen with invalid display ID"); + false + } + }) + } +} + +impl MonitorHandleProvider for MonitorHandle { + fn id(&self) -> u128 { + self.uuid() + } + + fn native_id(&self) -> u64 { + self.display_id() as _ + } + + // TODO: Be smarter about this: + // + // + fn name(&self) -> Option> { + let screen_num = CGDisplayModelNumber(self.display_id()); + Some(format!("Monitor #{screen_num}").into()) + } + + fn position(&self) -> Option> { + // This is already in screen coordinates. If we were using `NSScreen`, + // then a conversion would've been needed: + // flip_window_screen_coordinates(self.ns_screen(mtm)?.frame()) + let bounds = CGDisplayBounds(self.display_id()); + let position = LogicalPosition::new(bounds.origin.x, bounds.origin.y); + Some(position.to_physical(self.scale_factor())) + } + + fn scale_factor(&self) -> f64 { + run_on_main(|mtm| { + match self.ns_screen(mtm) { + Some(screen) => screen.backingScaleFactor() as f64, + None => 1.0, // default to 1.0 when we can't find the screen + } + }) + } + + fn current_video_mode(&self) -> Option { + let mode = NativeDisplayMode(CGDisplayCopyDisplayMode(self.display_id()).unwrap()); + let refresh_rate_millihertz = refresh_rate_millihertz(self.display_id(), &mode); + Some(VideoModeHandle::new(self.clone(), mode, refresh_rate_millihertz).mode) + } + + fn video_modes(&self) -> Box> { + Box::new(self.video_mode_handles().map(|mode| mode.mode)) + } +} + +pub fn available_monitors() -> VecDeque { + let mut expected_count = 0; + let res = cgerr(unsafe { CGGetActiveDisplayList(0, ptr::null_mut(), &mut expected_count) }); + if res.is_err() { + return VecDeque::with_capacity(0); + } + + let mut displays: Vec = vec![0; expected_count as usize]; + let mut actual_count = 0; + let res = cgerr(unsafe { + CGGetActiveDisplayList(expected_count, displays.as_mut_ptr(), &mut actual_count) + }); + displays.truncate(actual_count as usize); + + if res.is_err() { + return VecDeque::with_capacity(0); + } + + let mut monitors = VecDeque::with_capacity(displays.len()); + for display in displays { + // Display ID just fetched from `CGGetActiveDisplayList`, should be fine to unwrap. + monitors.push_back(MonitorHandle::new(display).expect("invalid display ID")); + } + monitors +} + +pub fn primary_monitor() -> MonitorHandle { + // Display ID just fetched from `CGMainDisplayID`, should be fine to unwrap. + MonitorHandle::new(CGMainDisplayID()).expect("invalid display ID") +} + +impl fmt::Debug for MonitorHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MonitorHandle") + .field("name", &self.name()) + .field("uuid", &self.uuid()) + .field("display_id", &self.display_id()) + .field("position", &self.position()) + .field("scale_factor", &self.scale_factor()) + .finish_non_exhaustive() + } +} + +pub(crate) fn get_display_id(screen: &NSScreen) -> u32 { + let key = ns_string!("NSScreenNumber"); + + objc2::rc::autoreleasepool(|_| { + let device_description = screen.deviceDescription(); + + // Retrieve the CGDirectDisplayID associated with this screen + // + // The value from @"NSScreenNumber" in deviceDescription is guaranteed + // to be an NSNumber. See documentation for details: + // + let obj = device_description + .objectForKey(key) + .expect("failed getting screen display id from device description") + .downcast::() + .expect("NSScreenNumber must be NSNumber"); + + obj.as_u32() + }) +} + +/// Core graphics screen coordinates are relative to the top-left corner of +/// the so-called "main" display, with y increasing downwards - which is +/// exactly what we want in Winit. +/// +/// However, `NSWindow` and `NSScreen` changes these coordinates to: +/// 1. Be relative to the bottom-left corner of the "main" screen. +/// 2. Be relative to the bottom-left corner of the window/screen itself. +/// 3. Have y increasing upwards. +/// +/// This conversion happens to be symmetric, so we only need this one function +/// to convert between the two coordinate systems. +pub(crate) fn flip_window_screen_coordinates(frame: NSRect) -> NSPoint { + // It is intentional that we use `CGMainDisplayID` (as opposed to + // `NSScreen::mainScreen`), because that's what the screen coordinates + // are relative to, no matter which display the window is currently on. + let main_screen_height = CGDisplayBounds(CGMainDisplayID()).size.height; + + let y = main_screen_height - frame.size.height - frame.origin.y; + NSPoint::new(frame.origin.x, y) +} + +fn refresh_rate_millihertz(id: CGDirectDisplayID, mode: &NativeDisplayMode) -> Option { + let refresh_rate = CGDisplayMode::refresh_rate(Some(&mode.0)); + if refresh_rate > 0.0 { + return NonZeroU32::new((refresh_rate * 1000.0).round() as u32); + } + + let mut display_link = std::ptr::null_mut(); + #[allow(deprecated)] + if unsafe { CVDisplayLink::create_with_cg_display(id, NonNull::from(&mut display_link)) } + != kCVReturnSuccess + { + return None; + } + let display_link = unsafe { CFRetained::from_raw(NonNull::new(display_link).unwrap()) }; + #[allow(deprecated)] + let time = display_link.nominal_output_video_refresh_period(); + + // This value is indefinite if an invalid display link was specified + if time.flags & CVTimeFlags::IsIndefinite.0 != 0 { + return None; + } + + (time.timeScale as i64) + .checked_div(time.timeValue) + .map(|v| (v * 1000) as u32) + .and_then(NonZeroU32::new) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn uuid_stable() { + let primary_id = CGMainDisplayID(); + + let handle_a = MonitorHandle::new(primary_id).unwrap(); + let handle_b = MonitorHandle::new(primary_id).unwrap(); + assert_eq!(handle_a, handle_b); + assert_eq!(handle_a.display_id(), handle_b.display_id()); + assert_eq!(handle_a.uuid(), handle_b.uuid()); + + let handle_a = primary_monitor(); + let handle_b = primary_monitor(); + assert_eq!(handle_a, handle_b); + assert_eq!(handle_a.display_id(), handle_b.display_id()); + assert_eq!(handle_a.uuid(), handle_b.uuid()); + } + + /// Test the MonitorHandle::new fallback. + #[test] + fn monitorhandle_from_zero() { + let primary_id = CGMainDisplayID(); + + let handle0 = MonitorHandle::new(0).unwrap(); + let handle1 = MonitorHandle::new(primary_id).unwrap(); + assert_eq!(handle0, handle1); + assert_eq!(handle0.display_id(), handle1.display_id()); + assert_eq!(handle0.uuid(), handle1.uuid()); + } + + #[test] + fn from_invalid_id() { + // Assume there are never this many monitors connected. + assert!(MonitorHandle::new(10000).is_none()); + } + + /// Test that calling `CGDisplayGetDisplayIDFromUUID` on an invalid UUID returns an invalid + /// display ID. + #[test] + fn invalid_monitor_handle() { + // `CGMainDisplayID` must be called to avoid: + // ``` + // Assertion failed: (did_initialize), function CGS_REQUIRE_INIT, file CGInitialization.c, line 44. + // ``` + // See https://github.com/JXA-Cookbook/JXA-Cookbook/issues/27#issuecomment-277517668 + let _ = CGMainDisplayID(); + + let handle = MonitorHandle(CFUUID::new(None).unwrap()); + assert_eq!(handle.display_id(), 0); + } +} diff --git a/patches/winit-appkit/src/observer.rs b/patches/winit-appkit/src/observer.rs new file mode 100644 index 0000000000..1bc79acf0c --- /dev/null +++ b/patches/winit-appkit/src/observer.rs @@ -0,0 +1,87 @@ +use std::ffi::c_void; +use std::ptr; +use std::time::Instant; + +use objc2_core_foundation::{ + CFAbsoluteTimeGetCurrent, CFRetained, CFRunLoop, CFRunLoopTimer, kCFRunLoopCommonModes, +}; + +#[derive(Debug)] +pub struct EventLoopWaker { + timer: CFRetained, + + /// An arbitrary instant in the past, that will trigger an immediate wake + /// We save this as the `next_fire_date` for consistency so we can + /// easily check if the next_fire_date needs updating. + start_instant: Instant, + + /// This is what the `NextFireDate` has been set to. + /// `None` corresponds to `waker.stop()` and `start_instant` is used + /// for `waker.start()` + next_fire_date: Option, +} + +impl Drop for EventLoopWaker { + fn drop(&mut self) { + self.timer.invalidate(); + } +} + +impl EventLoopWaker { + pub(crate) fn new() -> Self { + extern "C-unwind" fn wakeup_main_loop(_timer: *mut CFRunLoopTimer, _info: *mut c_void) {} + unsafe { + // Create a timer with a 0.1µs interval (1ns does not work) to mimic polling. + // It is initially setup with a first fire time really far into the + // future, but that gets changed to fire immediately in did_finish_launching + let timer = CFRunLoopTimer::new( + None, + f64::MAX, + 0.000_000_1, + 0, + 0, + Some(wakeup_main_loop), + ptr::null_mut(), + ) + .unwrap(); + CFRunLoop::main().unwrap().add_timer(Some(&timer), kCFRunLoopCommonModes); + Self { timer, start_instant: Instant::now(), next_fire_date: None } + } + } + + pub fn stop(&mut self) { + if self.next_fire_date.is_some() { + self.next_fire_date = None; + self.timer.set_next_fire_date(f64::MAX); + } + } + + pub fn start(&mut self) { + if self.next_fire_date != Some(self.start_instant) { + self.next_fire_date = Some(self.start_instant); + self.timer.set_next_fire_date(f64::MIN); + } + } + + pub fn start_at(&mut self, instant: Option) { + let now = Instant::now(); + match instant { + Some(instant) if now >= instant => { + self.start(); + }, + Some(instant) => { + if self.next_fire_date != Some(instant) { + self.next_fire_date = Some(instant); + let current = CFAbsoluteTimeGetCurrent(); + let duration = instant - now; + let fsecs = duration.subsec_nanos() as f64 / 1_000_000_000.0 + + duration.as_secs() as f64; + self.timer.set_next_fire_date(current + fsecs); + } + }, + None => { + self.stop(); + }, + } + } +} diff --git a/patches/winit-appkit/src/util.rs b/patches/winit-appkit/src/util.rs new file mode 100644 index 0000000000..3fbcfac53c --- /dev/null +++ b/patches/winit-appkit/src/util.rs @@ -0,0 +1,11 @@ +use objc2_core_graphics::CGError; +use winit_core::error::OsError; + +macro_rules! os_error { + ($error:expr) => {{ winit_core::error::OsError::new(line!(), file!(), $error) }}; +} + +#[track_caller] +pub(crate) fn cgerr(err: CGError) -> Result<(), OsError> { + if err == CGError::Success { Ok(()) } else { Err(os_error!(format!("CGError {err:?}"))) } +} diff --git a/patches/winit-appkit/src/view.rs b/patches/winit-appkit/src/view.rs new file mode 100644 index 0000000000..fa60288a16 --- /dev/null +++ b/patches/winit-appkit/src/view.rs @@ -0,0 +1,1571 @@ +#![allow(clippy::unnecessary_cast)] +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, VecDeque}; +use std::rc::Rc; + +use dpi::{LogicalPosition, PhysicalSize}; +use objc2::rc::Retained; +use objc2::runtime::{AnyObject, Sel}; +use objc2::{AnyThread, DefinedClass, MainThreadMarker, Message, define_class, msg_send}; +use objc2_app_kit::{ + NSApplication, NSCursor, NSDragOperation, NSDraggingSession, NSEvent, NSEventPhase, + NSResponder, NSTextInputClient, NSTrackingArea, NSTrackingAreaOptions, NSView, + NSViewLayerContentsRedrawPolicy, NSWindow, +}; +use objc2_core_foundation::CGRect; +use objc2_foundation::{ + NSArray, NSAttributedString, NSAttributedStringKey, NSCopying, NSMutableAttributedString, + NSNotFound, NSObject, NSPoint, NSRange, NSRect, NSSize, NSString, NSUInteger, +}; +use tracing::{debug_span, trace_span}; +use winit_core::event::{ + DeviceEvent, ElementState, Ime, KeyEvent, Modifiers, MouseButton, MouseScrollDelta, + PointerKind, PointerSource, TouchPhase, WindowEvent, +}; +use winit_core::keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey}; +use winit_core::window::{ImeCapabilities, ImeSurroundingText}; + +use super::app_state::AppState; +use super::cursor::{default_cursor, invisible_cursor}; +use super::event::{ + code_to_key, code_to_location, create_key_event, event_mods, lalt_pressed, ralt_pressed, + scancode_to_physicalkey, +}; +use super::window::window_id; +use crate::OptionAsAlt; + +#[derive(Debug)] +struct CursorState { + visible: bool, + cursor: Retained, +} + +impl Default for CursorState { + fn default() -> Self { + Self { visible: true, cursor: default_cursor() } + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Copy, Default)] +enum ImeState { + #[default] + /// The IME events are disabled, so only `ReceivedCharacter` is being sent to the user. + Disabled, + + /// The ground state of enabled IME input. It means that both Preedit and regular keyboard + /// input could be start from it. + Ground, + + /// The IME is in preedit. + Preedit, + + /// The text was just committed, so the next input from the keyboard must be ignored. + Committed, +} + +bitflags::bitflags! { + #[derive(Debug, Clone, Copy, PartialEq)] + struct ModLocationMask: u8 { + const LEFT = 0b0001; + const RIGHT = 0b0010; + } +} +impl ModLocationMask { + fn from_location(loc: KeyLocation) -> ModLocationMask { + match loc { + KeyLocation::Left => ModLocationMask::LEFT, + KeyLocation::Right => ModLocationMask::RIGHT, + _ => unreachable!(), + } + } +} + +fn key_to_modifier(key: &Key) -> Option { + match key { + Key::Named(NamedKey::Alt) => Some(ModifiersState::ALT), + Key::Named(NamedKey::Control) => Some(ModifiersState::CONTROL), + Key::Named(NamedKey::Meta) => Some(ModifiersState::META), + Key::Named(NamedKey::Shift) => Some(ModifiersState::SHIFT), + _ => None, + } +} + +fn get_right_modifier_code(key: &Key) -> KeyCode { + match key { + Key::Named(NamedKey::Alt) => KeyCode::AltRight, + Key::Named(NamedKey::Control) => KeyCode::ControlRight, + Key::Named(NamedKey::Shift) => KeyCode::ShiftRight, + Key::Named(NamedKey::Meta) => KeyCode::MetaRight, + _ => unreachable!(), + } +} + +fn get_left_modifier_code(key: &Key) -> KeyCode { + match key { + Key::Named(NamedKey::Alt) => KeyCode::AltLeft, + Key::Named(NamedKey::Control) => KeyCode::ControlLeft, + Key::Named(NamedKey::Shift) => KeyCode::ShiftLeft, + Key::Named(NamedKey::Meta) => KeyCode::MetaLeft, + _ => unreachable!(), + } +} + +#[derive(Debug)] +pub struct ViewState { + /// Strong reference to the global application state. + app_state: Rc, + + /// This is for a dragging session that we initiated + dragging_session: RefCell>>, + + /// This is for a dragging session that we initiated + drag_operations: Cell, + + cursor_state: RefCell, + ime_position: Cell, + ime_size: Cell, + modifiers: Cell, + phys_modifiers: RefCell>, + ime_state: Cell, + input_source: RefCell, + + /// True if this view was in a preedit session that will result in a commit. + pending_commit: Cell, + + /// True iff the application wants IME events. + /// + /// Can be set using `set_ime_allowed` + ime_capabilities: Cell>, + + /// True if the current key event should be forwarded + /// to the application, even during IME + forward_key_to_app: Cell, + marked_text: RefCell>, + + /// Set by `acceptsFirstMouse:` so the next `mouseDown:` can tag its + /// [`WindowEvent::PointerButton`] with `is_macos_activation_click: true`. + next_click_is_activation: Cell, + + /// The state of the `Option` as `Alt`. + option_as_alt: Cell, + + // leaf patch: the text around the caret, as the application last reported + // it with `ImeRequestData::with_surrounding_text`. What `selectedRange` and + // `attributedSubstringForProposedRange:` answer from, and what a + // `replacementRange` is resolved against — without it the input system + // cannot see the character before the caret, so press-and-hold never + // opens its accent menu. + surrounding: RefCell>, + /// leaf patch: inside `keyDown:`'s `interpretKeyEvents:`, so `insertText:` + /// can tell a keystroke's own text (which `KeyboardInput` carries) from + /// text inserted with no key at all — the emoji picker, dictation. + in_key_down: Cell, + /// leaf patch: whether `interpretKeyEvents:` reached the client at all — + /// inserted, marked or commanded. A key repeat the input system swallowed + /// without any of those is press-and-hold holding the key, not typing. + text_activity: Cell, + /// leaf patch: press-and-hold's accent menu is up — a repeat was + /// swallowed and nothing has been inserted since. The key that picks an + /// accent (a digit, an arrow, Return) reaches none of the client's + /// methods while it is pressed: the menu inserts its choice *after* + /// `keyDown:` returns, so without this the digit was forwarded as typing + /// and the accent's `DeleteSurrounding` then took the digit, not the + /// letter. + accent_menu: Cell, +} + +define_class!( + #[unsafe(super(NSView, NSResponder, NSObject))] + #[ivars = ViewState] + #[name = "WinitView"] + #[derive(Debug)] + pub(super) struct WinitView; + + /// This documentation attribute makes rustfmt work for some reason? + impl WinitView { + #[unsafe(method(isFlipped))] + fn is_flipped(&self) -> bool { + // `winit` uses the upper-left corner as the origin. + true + } + + // Not a normal method on `NSView`, it's triggered by `NSViewFrameDidChangeNotification`. + #[unsafe(method(viewFrameDidChangeNotification:))] + fn frame_did_change(&self, _notification: Option<&AnyObject>) { + let _entered = debug_span!("NSViewFrameDidChangeNotification").entered(); + + // Emit resize event here rather than from windowDidResize because: + // 1. When a new window is created as a tab, the frame size may change without a window + // resize occurring. + // 2. Even when a window resize does occur on a new tabbed window, it contains the wrong + // size (includes tab height). + self.surface_resized(); + // During live resize, AppKit may not let the normal event loop reach its next redraw + // point before stretching the current layer contents. Redraw immediately after the + // app has observed the new surface size. + self.redraw_during_live_resize(); + } + + #[unsafe(method(viewDidChangeBackingProperties))] + fn view_did_change_backing_properties(&self) { + let _entered = debug_span!("viewDidChangeBackingProperties").entered(); + // Moving between displays or changing scale can alter the drawable backing size + // without a matching frame-size change. + self.surface_resized(); + self.redraw_during_live_resize(); + } + + #[unsafe(method(drawRect:))] + fn draw_rect(&self, _rect: NSRect) { + let _entered = debug_span!("drawRect:").entered(); + + self.ivars().app_state.handle_redraw(window_id(&self.window())); + + // This is a direct subclass of NSView, no need to call superclass' drawRect: + } + + #[unsafe(method(acceptsFirstResponder))] + fn accepts_first_responder(&self) -> bool { + let _entered = trace_span!("acceptsFirstResponder").entered(); + true + } + + // This is necessary to prevent a beefy terminal error on MacBook Pros: + // IMKInputSession [0x7fc573576ff0 + // presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self + // textInputContext]=0x7fc573558e10 *NO* NSRemoteViewController to client, NSError=Error + // Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 0 was invalidated from this + // process." UserInfo={NSDebugDescription=The connection from pid 0 was invalidated from + // this process.}, com.apple.inputmethod.EmojiFunctionRowItem TODO: Add an API + // extension for using `NSTouchBar` + #[unsafe(method_id(touchBar))] + fn touch_bar(&self) -> Option> { + let _entered = debug_span!("touchBar").entered(); + None + } + + #[unsafe(method(resetCursorRects))] + fn reset_cursor_rects(&self) { + let _entered = debug_span!("resetCursorRects").entered(); + let bounds = self.bounds(); + let cursor_state = self.ivars().cursor_state.borrow(); + // We correctly invoke `addCursorRect` only from inside `resetCursorRects` + if cursor_state.visible { + self.addCursorRect_cursor(bounds, &cursor_state.cursor); + } else { + self.addCursorRect_cursor(bounds, &invisible_cursor()); + } + } + } + + unsafe impl NSTextInputClient for WinitView { + #[unsafe(method(hasMarkedText))] + fn has_marked_text(&self) -> bool { + let _entered = debug_span!("hasMarkedText").entered(); + self.ivars().marked_text.borrow().length() > 0 + } + + #[unsafe(method(markedRange))] + fn marked_range(&self) -> NSRange { + let _entered = debug_span!("markedRange").entered(); + let length = self.ivars().marked_text.borrow().length(); + if length > 0 { + NSRange::new(0, length) + } else { + // Documented to return `{NSNotFound, 0}` if there is no marked range. + NSRange::new(NSNotFound as NSUInteger, 0) + } + } + + #[unsafe(method(selectedRange))] + fn selected_range(&self) -> NSRange { + let _entered = debug_span!("selectedRange").entered(); + // leaf patch: answer from the surrounding text when the + // application reported it. + if let Some(s) = &*self.ivars().surrounding.borrow() { + let (lo, hi) = (s.cursor().min(s.anchor()), s.cursor().max(s.anchor())); + let start = utf16_len(&s.text()[..lo]); + return NSRange::new(start, utf16_len(&s.text()[lo..hi])); + } + // Documented to return `{NSNotFound, 0}` if there is no selection. + NSRange::new(NSNotFound as NSUInteger, 0) + } + + #[unsafe(method(setMarkedText:selectedRange:replacementRange:))] + fn set_marked_text( + &self, + string: &NSObject, + selected_range: NSRange, + replacement_range: NSRange, + ) { + let _entered = debug_span!("setMarkedText:selectedRange:replacementRange:").entered(); + self.ivars().text_activity.set(true); + // leaf patch: marking text that is already in the document — + // press-and-hold marks the character it is offering accents for — + // takes that text out first, so the preedit stands in its place. + if !self.hasMarkedText() { + self.delete_replaced(replacement_range); + } + + let (marked_text, string) = if let Some(string) = + string.downcast_ref::() + { + (NSMutableAttributedString::from_attributed_nsstring(string), string.string()) + } else if let Some(string) = string.downcast_ref::() { + (NSMutableAttributedString::from_nsstring(string), string.copy()) + } else { + // This method is guaranteed to get either a `NSString` or a `NSAttributedString`. + panic!("unexpected text {string:?}") + }; + + // Update marked text. + *self.ivars().marked_text.borrow_mut() = marked_text; + + // Notify IME is active if application still doesn't know it. + if self.ivars().ime_state.get() == ImeState::Disabled { + *self.ivars().input_source.borrow_mut() = self.current_input_source(); + self.queue_event(WindowEvent::Ime(Ime::Enabled)); + } + + if self.hasMarkedText() { + self.ivars().ime_state.set(ImeState::Preedit); + } else { + // In case the preedit was cleared, set IME into the Ground state. + self.ivars().ime_state.set(ImeState::Ground); + } + self.ivars().pending_commit.set(true); + + let string = string.to_string(); + let cursor_range = if string.is_empty() { + // An empty string basically means that there's no preedit, so indicate that by + // sending a `None` cursor range. + None + } else { + // Convert the selected range from UTF-16 code unit indices to UTF-8 byte + // offsets. `utf16_to_utf8_offset` is defensive: it snaps an offset that would + // split a surrogate pair down to the character boundary and clamps an + // out-of-bounds offset to the string length, so no `NSRangeException` is + // possible and the resulting range can never be inverted (`lower <= upper`). + // IMEs are known to send both mid-surrogate and out-of-bounds offsets (e.g. + // native Pinyin, see https://github.com/alacritty/alacritty/issues/8791). + let lowerbound_utf8 = utf16_to_utf8_offset(&string, selected_range.location); + let upperbound_utf8 = utf16_to_utf8_offset(&string, selected_range.end()); + Some((lowerbound_utf8, upperbound_utf8)) + }; + + // Send WindowEvent for updating marked text + self.queue_event(WindowEvent::Ime(Ime::Preedit(string, cursor_range))); + } + + #[unsafe(method(unmarkText))] + fn unmark_text(&self) { + let _entered = debug_span!("unmarkText").entered(); + *self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new(); + + let input_context = self.inputContext().expect("input context"); + input_context.discardMarkedText(); + + self.queue_event(WindowEvent::Ime(Ime::Preedit(String::new(), None))); + if self.is_ime_enabled() { + // Leave the Preedit self.ivars() + self.ivars().ime_state.set(ImeState::Ground); + } else { + tracing::warn!("Expected to have IME enabled when receiving unmarkText"); + } + } + + #[unsafe(method_id(validAttributesForMarkedText))] + fn valid_attributes_for_marked_text(&self) -> Retained> { + let _entered = trace_span!("validAttributesForMarkedText").entered(); + let underline_style = NSString::from_str("NSUnderlineStyle"); + let marked_clause = NSString::from_str("NSMarkedClauseSegment"); + NSArray::from_slice(&[&*underline_style, &*marked_clause]) + } + + #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))] + fn attributed_substring_for_proposed_range( + &self, + range: NSRange, + actual_range: *mut NSRange, + ) -> Option> { + let _entered = + trace_span!("attributedSubstringForProposedRange:actualRange:").entered(); + // leaf patch: the surrounding text the application reported. + self.surrounding_substring(range, actual_range) + } + + #[unsafe(method(characterIndexForPoint:))] + fn character_index_for_point(&self, _point: NSPoint) -> NSUInteger { + let _entered = debug_span!("characterIndexForPoint:").entered(); + 0 + } + + #[unsafe(method(firstRectForCharacterRange:actualRange:))] + fn first_rect_for_character_range( + &self, + _range: NSRange, + _actual_range: *mut NSRange, + ) -> NSRect { + let _entered = debug_span!("firstRectForCharacterRange:actualRange:").entered(); + + // Guard when the view is no longer in a window during teardown. + let Some(window) = (**self).window() else { + return CGRect::ZERO; + }; + + // Return value is expected to be in screen coordinates, so we need a conversion + let rect = NSRect::new(self.ivars().ime_position.get(), self.ivars().ime_size.get()); + let view_rect = self.convertRect_toView(rect, None); + window.convertRectToScreen(view_rect) + } + + #[unsafe(method(insertText:replacementRange:))] + fn insert_text(&self, string: &NSObject, replacement_range: NSRange) { + let _entered = debug_span!("insertText:replacementRange:").entered(); + self.ivars().text_activity.set(true); + self.ivars().accent_menu.set(false); + + let string = if let Some(string) = string.downcast_ref::() { + string.string().to_string() + } else if let Some(string) = string.downcast_ref::() { + string.to_string() + } else { + // This method is guaranteed to get either a `NSString` or a `NSAttributedString`. + panic!("unexpected text {string:?}") + }; + + let is_control = string.chars().next().is_some_and(|c| c.is_control()); + let has_marked = self.hasMarkedText(); + let pending_commit = self.ivars().pending_commit.get(); + let ime_enabled = self.is_ime_enabled(); + leaf_trace(|| { + format!( + "winit insertText {string:?} replacement={:?} in_key_down={} state {:?} \ + marked={has_marked} pending_commit={pending_commit}", + (replacement_range.location, replacement_range.length), + self.ivars().in_key_down.get(), + self.ivars().ime_state.get(), + ) + }); + + // Clear preedit if there is marked text. + if has_marked { + self.queue_event(WindowEvent::Ime(Ime::Preedit(String::new(), None))); + } + + // Only commit via IME if there was a real composition session. + // Some IMEs send insertText for all typing (e.g. spaces, English chars) + // which should go through keyboard input instead of paste. + if pending_commit && ime_enabled && !is_control { + self.ivars().pending_commit.set(false); + self.queue_event(WindowEvent::Ime(Ime::Commit(string))); + self.ivars().ime_state.set(ImeState::Committed); + } else if !is_control && self.delete_replaced(replacement_range) { + // leaf patch: text that replaces text already in the document — + // press-and-hold's accent, chosen with a click or a number key. + // The replaced text went as `DeleteSurrounding`; this is its + // replacement. + self.queue_ime_enabled(); + self.queue_event(WindowEvent::Ime(Ime::Commit(string))); + // `Committed` tells `keyDown:` that the key it is handling was + // the input method's, not typing — true only when this + // insertion happened *during* a keypress. The accent menu + // inserts after the key that picked from it has returned, so + // there `Committed` was left for the next key, which then + // vanished: the first letter typed after an accent, or the + // ⌘Z meant to undo it. + if self.ivars().in_key_down.get() { + self.ivars().ime_state.set(ImeState::Committed); + } + } else if !is_control && !self.ivars().in_key_down.get() { + // leaf patch: text with no keystroke behind it — the emoji and + // symbols picker, dictation, a service. No `KeyboardInput` + // will carry it, so this is the only way it reaches the app. + // Not `Committed`: that would swallow the next real key. + self.queue_ime_enabled(); + self.queue_event(WindowEvent::Ime(Ime::Commit(string))); + } + } + + // Basically, we're sent this message whenever a keyboard event that doesn't generate a + // "human readable" character happens, i.e. newlines, tabs, and Ctrl+C. + #[unsafe(method(doCommandBySelector:))] + fn do_command_by_selector(&self, command: Sel) { + let _entered = debug_span!("doCommandBySelector:").entered(); + + // We shouldn't forward any character from just committed text, since we'll end up + // sending it twice with some IMEs like Korean one. We'll also always send + // `Enter` in that case, which is not desired given it was used to confirm + // IME input. + if self.ivars().ime_state.get() == ImeState::Committed { + return; + } + + self.ivars().forward_key_to_app.set(true); + self.ivars().text_activity.set(true); + + if self.hasMarkedText() && self.ivars().ime_state.get() == ImeState::Preedit { + // Leave preedit so that we also report the key-up for this key. + self.ivars().ime_state.set(ImeState::Ground); + } + + // Send command action to user if they requested it. + let window_id = window_id(&self.window()); + self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| { + if let Some(handler) = app.macos_handler() { + handler.standard_key_binding( + event_loop, + window_id, + command.name().to_str().unwrap(), + ); + } + }); + + // The documentation for `-[NSTextInputClient doCommandBySelector:]` clearly states that + // we should not be forwarding this event up the responder chain, so no calling `super` + // here either. + } + } + + /// This documentation attribute makes rustfmt work for some reason? + impl WinitView { + #[unsafe(method(keyDown:))] + fn key_down(&self, event: &NSEvent) { + let _entered = debug_span!("keyDown:").entered(); + { + let mut prev_input_source = self.ivars().input_source.borrow_mut(); + let current_input_source = self.current_input_source(); + if *prev_input_source != current_input_source && self.is_ime_enabled() { + *prev_input_source = current_input_source; + drop(prev_input_source); + self.ivars().ime_state.set(ImeState::Disabled); + self.queue_event(WindowEvent::Ime(Ime::Disabled)); + } + } + + // Get the characters from the event. + let old_ime_state = self.ivars().ime_state.get(); + self.ivars().forward_key_to_app.set(false); + let event = replace_event(event, self.option_as_alt()); + + // The `interpretKeyEvents` function might call + // `setMarkedText`, `insertText`, and `doCommandBySelector`. + // It's important that we call this before queuing the KeyboardInput, because + // we must send the `KeyboardInput` event during IME if it triggered + // `doCommandBySelector`. (doCommandBySelector means that the keyboard input + // is not handled by IME and should be handled by the application) + self.ivars().text_activity.set(false); + if self.ivars().ime_capabilities.get().is_some() { + let events_for_nsview = NSArray::from_slice(&[&*event]); + self.ivars().in_key_down.set(true); + self.interpretKeyEvents(&events_for_nsview); + self.ivars().in_key_down.set(false); + + // If the text was committed we must treat the next keyboard event as IME related. + if self.ivars().ime_state.get() == ImeState::Committed { + // Remove any marked text, so normal input can continue. + *self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new(); + } + } + + self.update_modifiers(&event, false); + + let had_ime_input = match self.ivars().ime_state.get() { + ImeState::Committed => { + // Allow normal input after the commit. + self.ivars().ime_state.set(ImeState::Ground); + true + }, + ImeState::Preedit => true, + // `key_down` could result in preedit clear, so compare old and current state. + _ => old_ime_state != self.ivars().ime_state.get(), + }; + + // leaf patch: a repeat the input system took without inserting, + // marking or commanding anything is press-and-hold holding the + // key while its accent menu is up — forwarding it would type the + // letter over and over underneath the menu. + let ime_capable = self.ivars().ime_capabilities.get().is_some(); + let quiet = ime_capable && !self.ivars().text_activity.get(); + let swallowed_repeat = event.isARepeat() && quiet; + if swallowed_repeat { + self.ivars().accent_menu.set(true); + } + // While the accent menu is up, a key that reached nothing is the + // menu's: choosing, moving, or dismissing it. Any key the input + // system does pass on (typing on past the menu) ends it. + let for_the_menu = self.ivars().accent_menu.get() && quiet; + if !quiet { + self.ivars().accent_menu.set(false); + } + + let forward = (!had_ime_input || self.ivars().forward_key_to_app.get()) + && !swallowed_repeat + && !for_the_menu; + leaf_trace(|| { + format!( + "winit keyDown {:?} repeat={} state {:?}->{:?} activity={} menu={} \ + had_ime_input={} forward_key={} => forward={forward}", + event.characters().map(|c| c.to_string()), + event.isARepeat(), + old_ime_state, + self.ivars().ime_state.get(), + self.ivars().text_activity.get(), + self.ivars().accent_menu.get(), + had_ime_input, + self.ivars().forward_key_to_app.get(), + ) + }); + if forward { + let key_event = create_key_event(&event, true, event.isARepeat()); + self.queue_event(WindowEvent::KeyboardInput { + device_id: None, + event: key_event, + is_synthetic: false, + }); + } + } + + #[unsafe(method(keyUp:))] + fn key_up(&self, event: &NSEvent) { + let _entered = debug_span!("keyUp:").entered(); + + let event = replace_event(event, self.option_as_alt()); + self.update_modifiers(&event, false); + + // We want to send keyboard input when we are currently in the ground state. + if matches!(self.ivars().ime_state.get(), ImeState::Ground | ImeState::Disabled) { + self.queue_event(WindowEvent::KeyboardInput { + device_id: None, + event: create_key_event(&event, false, false), + is_synthetic: false, + }); + } + } + + #[unsafe(method(flagsChanged:))] + fn flags_changed(&self, event: &NSEvent) { + let _entered = debug_span!("flagsChanged:").entered(); + + self.update_modifiers(event, true); + } + + #[unsafe(method(insertTab:))] + fn insert_tab(&self, _sender: Option<&AnyObject>) { + let _entered = debug_span!("insertTab:").entered(); + let window = self.window(); + if let Some(first_responder) = window.firstResponder() { + if *first_responder == ***self { + window.selectNextKeyView(Some(self)) + } + } + } + + #[unsafe(method(insertBackTab:))] + fn insert_back_tab(&self, _sender: Option<&AnyObject>) { + let _entered = debug_span!("insertBackTab:").entered(); + let window = self.window(); + if let Some(first_responder) = window.firstResponder() { + if *first_responder == ***self { + window.selectPreviousKeyView(Some(self)) + } + } + } + + // Allows us to receive Cmd-. (the shortcut for closing a dialog) + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6 + #[unsafe(method(cancelOperation:))] + fn cancel_operation(&self, _sender: Option<&AnyObject>) { + let mtm = MainThreadMarker::from(self); + let _entered = debug_span!("cancelOperation:").entered(); + + let event = NSApplication::sharedApplication(mtm) + .currentEvent() + .expect("could not find current event"); + + self.update_modifiers(&event, false); + let event = create_key_event(&event, true, event.isARepeat()); + + self.queue_event(WindowEvent::KeyboardInput { + device_id: None, + event, + is_synthetic: false, + }); + } + + // In the past (?), `mouseMoved:` events were not generated when the + // user hovered over a window from a separate window, and as such the + // application might not know the location of the mouse in the event. + // + // To fix this, we emit `mouse_motion` inside of mouse click, mouse + // scroll, magnify and other gesture event handlers, to ensure that + // the application's state of where the mouse click was located is up + // to date. + // + // See https://github.com/rust-windowing/winit/pull/1490 for history. + + #[unsafe(method(mouseDown:))] + fn mouse_down(&self, event: &NSEvent) { + let _entered = debug_span!("mouseDown:").entered(); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Pressed); + } + + #[unsafe(method(mouseUp:))] + fn mouse_up(&self, event: &NSEvent) { + let _entered = debug_span!("mouseUp:").entered(); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Released); + } + + #[unsafe(method(rightMouseDown:))] + fn right_mouse_down(&self, event: &NSEvent) { + let _entered = debug_span!("rightMouseDown:").entered(); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Pressed); + } + + #[unsafe(method(rightMouseUp:))] + fn right_mouse_up(&self, event: &NSEvent) { + let _entered = debug_span!("rightMouseUp:").entered(); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Released); + } + + #[unsafe(method(otherMouseDown:))] + fn other_mouse_down(&self, event: &NSEvent) { + let _entered = debug_span!("otherMouseDown:").entered(); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Pressed); + } + + #[unsafe(method(otherMouseUp:))] + fn other_mouse_up(&self, event: &NSEvent) { + let _entered = debug_span!("otherMouseUp:").entered(); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Released); + } + + #[unsafe(method(mouseMoved:))] + fn mouse_moved(&self, event: &NSEvent) { + let _entered = debug_span!("mouseMoved:").entered(); + self.mouse_motion(event); + } + + #[unsafe(method(mouseDragged:))] + fn mouse_dragged(&self, event: &NSEvent) { + let _entered = debug_span!("mouseDragged:").entered(); + self.mouse_motion(event); + } + + #[unsafe(method(rightMouseDragged:))] + fn right_mouse_dragged(&self, event: &NSEvent) { + let _entered = debug_span!("rightMouseDragged:").entered(); + self.mouse_motion(event); + } + + #[unsafe(method(otherMouseDragged:))] + fn other_mouse_dragged(&self, event: &NSEvent) { + let _entered = debug_span!("otherMouseDragged:").entered(); + self.mouse_motion(event); + } + + #[unsafe(method(mouseEntered:))] + fn mouse_entered(&self, event: &NSEvent) { + let _entered = debug_span!("mouseEntered:").entered(); + + let position = self.mouse_view_point(event).to_physical(self.scale_factor()); + + self.queue_event(WindowEvent::PointerEntered { + device_id: None, + primary: true, + position, + kind: PointerKind::Mouse, + }); + } + + #[unsafe(method(mouseExited:))] + fn mouse_exited(&self, event: &NSEvent) { + let _entered = debug_span!("mouseExited:").entered(); + + let position = self.mouse_view_point(event).to_physical(self.scale_factor()); + + self.queue_event(WindowEvent::PointerLeft { + device_id: None, + primary: true, + position: Some(position), + kind: PointerKind::Mouse, + }); + } + + #[unsafe(method(scrollWheel:))] + fn scroll_wheel(&self, event: &NSEvent) { + let _entered = debug_span!("scrollWheel:").entered(); + + self.mouse_motion(event); + + let delta = { + let (x, y) = (event.scrollingDeltaX(), event.scrollingDeltaY()); + if event.hasPreciseScrollingDeltas() { + let delta = LogicalPosition::new(x, y).to_physical(self.scale_factor()); + MouseScrollDelta::PixelDelta(delta) + } else { + MouseScrollDelta::LineDelta(x as f32, y as f32) + } + }; + + // The "momentum phase," if any, has higher priority than touch phase (the two should + // be mutually exclusive anyhow, which is why the API is rather incoherent). If no + // momentum phase is recorded (or rather, the started/ended cases of the + // momentum phase) then we report the touch phase. + #[allow(non_upper_case_globals)] + let phase = match event.momentumPhase() { + NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started, + NSEventPhase::Ended | NSEventPhase::Cancelled => TouchPhase::Ended, + _ => match event.phase() { + NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started, + NSEventPhase::Ended | NSEventPhase::Cancelled => TouchPhase::Ended, + _ => TouchPhase::Moved, + }, + }; + + self.update_modifiers(event, false); + + self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| { + app.device_event(event_loop, None, DeviceEvent::MouseWheel { delta }) + }); + self.queue_event(WindowEvent::MouseWheel { device_id: None, delta, phase }); + } + + #[unsafe(method(magnifyWithEvent:))] + fn magnify_with_event(&self, event: &NSEvent) { + let _entered = debug_span!("magnifyWithEvent:").entered(); + + self.mouse_motion(event); + + #[allow(non_upper_case_globals)] + let phase = match event.phase() { + NSEventPhase::Began => TouchPhase::Started, + NSEventPhase::Changed => TouchPhase::Moved, + NSEventPhase::Cancelled => TouchPhase::Cancelled, + NSEventPhase::Ended => TouchPhase::Ended, + _ => return, + }; + + self.queue_event(WindowEvent::PinchGesture { + device_id: None, + delta: event.magnification(), + phase, + }); + } + + #[unsafe(method(smartMagnifyWithEvent:))] + fn smart_magnify_with_event(&self, event: &NSEvent) { + let _entered = debug_span!("smartMagnifyWithEvent:").entered(); + + self.mouse_motion(event); + + self.queue_event(WindowEvent::DoubleTapGesture { device_id: None }); + } + + #[unsafe(method(rotateWithEvent:))] + fn rotate_with_event(&self, event: &NSEvent) { + let _entered = debug_span!("rotateWithEvent:").entered(); + + self.mouse_motion(event); + + #[allow(non_upper_case_globals)] + let phase = match event.phase() { + NSEventPhase::Began => TouchPhase::Started, + NSEventPhase::Changed => TouchPhase::Moved, + NSEventPhase::Cancelled => TouchPhase::Cancelled, + NSEventPhase::Ended => TouchPhase::Ended, + _ => return, + }; + + self.queue_event(WindowEvent::RotationGesture { + device_id: None, + delta: event.rotation(), + phase, + }); + } + + #[unsafe(method(pressureChangeWithEvent:))] + fn pressure_change_with_event(&self, event: &NSEvent) { + let _entered = debug_span!("pressureChangeWithEvent:").entered(); + + self.queue_event(WindowEvent::TouchpadPressure { + device_id: None, + pressure: event.pressure(), + stage: event.stage() as i64, + }); + } + + // Allows us to receive Ctrl-Tab and Ctrl-Esc. + // Note that this *doesn't* help with any missing Cmd inputs. + // https://github.com/chromium/chromium/blob/a86a8a6bcfa438fa3ac2eba6f02b3ad1f8e0756f/ui/views/cocoa/bridged_content_view.mm#L816 + #[unsafe(method(_wantsKeyDownForEvent:))] + fn wants_key_down_for_event(&self, _event: &NSEvent) -> bool { + let _entered = debug_span!("_wantsKeyDownForEvent:").entered(); + true + } + + #[unsafe(method(acceptsFirstMouse:))] + fn accepts_first_mouse(&self, event: Option<&NSEvent>) -> bool { + let _entered = debug_span!("acceptsFirstMouse:").entered(); + // Always accept the click. The following `mouseDown:` is tagged with + // `is_macos_activation_click: true` so the application can decide per click + // whether to act on it. + // + // AppKit may pass nil here for synthetic queries that are not tied to a + // specific click; only set the flag when we actually have an event. + if event.is_some() { + self.ivars().next_click_is_activation.set(true); + } + true + } + } +); + +impl WinitView { + pub(super) fn new( + app_state: &Rc, + option_as_alt: OptionAsAlt, + mtm: MainThreadMarker, + ) -> Retained { + let this = mtm.alloc().set_ivars(ViewState { + app_state: Rc::clone(app_state), + dragging_session: Default::default(), + drag_operations: Cell::new(NSDragOperation::empty()), + cursor_state: Default::default(), + ime_position: Default::default(), + ime_size: Default::default(), + modifiers: Default::default(), + phys_modifiers: Default::default(), + ime_state: Default::default(), + input_source: Default::default(), + pending_commit: Default::default(), + ime_capabilities: Default::default(), + forward_key_to_app: Default::default(), + marked_text: Default::default(), + next_click_is_activation: Default::default(), + option_as_alt: Cell::new(option_as_alt), + surrounding: Default::default(), + in_key_down: Default::default(), + text_activity: Default::default(), + accent_menu: Default::default(), + }); + let this: Retained = unsafe { msg_send![super(this), init] }; + *this.ivars().input_source.borrow_mut() = this.current_input_source(); + + // Ask AppKit to redisplay the layer while the view is being resized so layer-backed + // surfaces keep painting. + this.setLayerContentsRedrawPolicy(NSViewLayerContentsRedrawPolicy::DuringViewResize); + + // `MouseEnteredAndExited` enables receiving events through `mouseEntered:` and + // `mouseExited:`. + // + // `MouseMoved` enables receiving events through `mouseMoved:` + // + // We do not set `CursorUpdate` because it is part of the "flexible" alternative to + // `cursorRect` based cursor image updates, and we currently still use + // `cursorRect`s. We also can't really switch to this approach because "The + // cursorUpdate(with:) message is not sent when the NSTrackingCursorUpdate option is + // specified along with [`ActiveAlways`]." + // + // `ActiveAlways` indicates we want to receive events when the window is not + // focused ("key window" in Cocoa terms), which matches the behavior on other + // platforms. + // + // We do not set `AssumeInside` because we want to avoid emitting `Left` events without a + // correspondering `Entered` to our consumers, and not setting this flag tells AppKit to + // handle this for us by synthesizing entry and exit events in some cases. + // + // `InVisibleRect` instructs the tracking area's `owner` (our `NSView`) to ignore the value + // we provide in `rect` and keep the tracking area's bounds up to date with the + // current view bounds automatically. + // + // We do not set `EnabledDuringMouseDrag` to match the platform behavior on Windows + // and Wayland, since neither emit events while being dragged over with an empty + // cursor without focus. + // + // See also https://developer.apple.com/documentation/appkit/nstrackingareaoptions. + + // Safety: the type of `owner` should be `NSView` and is. + // The type of `user_info` is irrelevant because it is None. + this.addTrackingArea(&*unsafe { + NSTrackingArea::initWithRect_options_owner_userInfo( + NSTrackingArea::alloc(), + NSRect::ZERO, + NSTrackingAreaOptions::MouseEnteredAndExited + | NSTrackingAreaOptions::MouseMoved + | NSTrackingAreaOptions::ActiveAlways + | NSTrackingAreaOptions::InVisibleRect, + Some(&this), + None, + ) + }); + + this + } + + fn window(&self) -> Retained { + (**self).window().expect("view must be installed in a window") + } + + fn queue_event(&self, event: WindowEvent) { + let window_id = window_id(&self.window()); + self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| { + app.window_event(event_loop, window_id, event); + }); + } + + pub(super) fn surface_resized(&self) { + let Some(window) = (**self).window() else { + return; + }; + let window_id = window_id(&window); + let view = self.retain(); + self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| { + let size = view.surface_size(); + app.window_event(event_loop, window_id, WindowEvent::SurfaceResized(size)); + }); + } + + /// Returns the drawable size from the view's backing-coordinate bounds. + pub(super) fn surface_size(&self) -> PhysicalSize { + // The view bounds are authoritative for full-size content views and during live resize. + // Deriving this from the window frame can exclude custom titlebar content or be stale. + let backing_bounds = self.convertRectToBacking(self.bounds()); + PhysicalSize::new( + backing_bounds.size.width.round().max(0.0) as u32, + backing_bounds.size.height.round().max(0.0) as u32, + ) + } + + fn redraw_during_live_resize(&self) { + let Some(window) = (**self).window() else { + return; + }; + if window.inLiveResize() { + self.ivars().app_state.handle_redraw(window_id(&window)); + } + } + + pub(crate) fn scale_factor(&self) -> f64 { + self.window().backingScaleFactor() as f64 + } + + fn is_ime_enabled(&self) -> bool { + !matches!(self.ivars().ime_state.get(), ImeState::Disabled) + } + + fn current_input_source(&self) -> String { + self.inputContext() + .expect("input context") + .selectedKeyboardInputSource() + .map(|input_source| input_source.to_string()) + .unwrap_or_default() + } + + pub(super) fn cursor_icon(&self) -> Retained { + self.ivars().cursor_state.borrow().cursor.clone() + } + + pub(super) fn set_cursor_icon(&self, icon: Retained) { + let mut cursor_state = self.ivars().cursor_state.borrow_mut(); + cursor_state.cursor = icon; + } + + /// Set whether the cursor should be visible or not. + /// + /// Returns whether the state changed. + pub(super) fn set_cursor_visible(&self, visible: bool) -> bool { + let mut cursor_state = self.ivars().cursor_state.borrow_mut(); + if visible != cursor_state.visible { + cursor_state.visible = visible; + true + } else { + false + } + } + pub(super) fn enable_ime(&self, capabilities: ImeCapabilities) { + // This seems reasonable but the prior behavior of `set_ime_allowed` doesn't do this + // (it was also broken but let's not break things worse) + + // if self.ivars().ime_capabilities.get().is_none() { + // self.ivars().ime_state.set(ImeState::Ground); + // } + + // why are we disabling things in an enable fn? who knows. it's what the previous one did + // though + if self.ivars().ime_state.get() != ImeState::Disabled { + self.ivars().ime_state.set(ImeState::Disabled); + self.queue_event(WindowEvent::Ime(Ime::Disabled)); + } + self.ivars().ime_capabilities.set(Some(capabilities)); + *self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new(); + self.ivars().pending_commit.set(false); + } + pub(super) fn disable_ime(&self) { + // see above + self.ivars().ime_capabilities.set(None); + if self.ivars().ime_state.get() != ImeState::Disabled { + self.ivars().ime_state.set(ImeState::Disabled); + self.queue_event(WindowEvent::Ime(Ime::Disabled)); + } + // we probably don't need to do this, but again this mirrors the prior behavior of + // `set_ime_allowed` + *self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new(); + self.ivars().pending_commit.set(false); + } + + pub(super) fn ime_capabilities(&self) -> Option { + self.ivars().ime_capabilities.get() + } + + /// leaf patch: `attributedSubstringForProposedRange:actualRange:` over the + /// surrounding text the application reported. + fn surrounding_substring( + &self, + range: NSRange, + actual_range: *mut NSRange, + ) -> Option> { + let surrounding = self.ivars().surrounding.borrow(); + let text = surrounding.as_ref()?.text(); + let len = utf16_len(text); + if range.location > len { + return None; + } + let end = range.end().min(len); + let lo = utf16_to_utf8_offset(text, range.location); + let hi = utf16_to_utf8_offset(text, end); + if !actual_range.is_null() { + // SAFETY: AppKit passes either null or a valid out-pointer. + unsafe { *actual_range = NSRange::new(range.location, end - range.location) }; + } + Some(NSAttributedString::from_nsstring(&NSString::from_str(&text[lo..hi]))) + } + + /// leaf patch: the text around the caret, from the application. + pub(super) fn set_ime_surrounding_text(&self, text: Option) { + *self.ivars().surrounding.borrow_mut() = text; + } + + /// leaf patch: `Ime::Enabled` if the application has not been told yet, + /// as the event's docs promise before any `Commit`. + fn queue_ime_enabled(&self) { + if self.ivars().ime_state.get() == ImeState::Disabled { + *self.ivars().input_source.borrow_mut() = self.current_input_source(); + self.queue_event(WindowEvent::Ime(Ime::Enabled)); + self.ivars().ime_state.set(ImeState::Ground); + } + } + + /// leaf patch: resolve a `replacementRange` against the surrounding text + /// and ask the application to delete it, as `Ime::DeleteSurrounding` + /// relative to the caret. Returns whether there was anything to delete. + fn delete_replaced(&self, range: NSRange) -> bool { + if range.location == NSNotFound as NSUInteger || range.length == 0 { + return false; + } + let deleted = { + let surrounding = self.ivars().surrounding.borrow(); + let Some(s) = surrounding.as_ref() else { return false }; + let lo = utf16_to_utf8_offset(s.text(), range.location); + let hi = utf16_to_utf8_offset(s.text(), range.end()); + let cursor = s.cursor().min(s.anchor()); + (lo < hi).then(|| (cursor.saturating_sub(lo), hi.saturating_sub(cursor.max(lo)))) + }; + let Some((before_bytes, after_bytes)) = deleted else { return false }; + self.queue_ime_enabled(); + self.queue_event(WindowEvent::Ime(Ime::DeleteSurrounding { before_bytes, after_bytes })); + // The text it described is gone; the application reports anew. + *self.ivars().surrounding.borrow_mut() = None; + true + } + + pub(super) fn set_ime_cursor_area(&self, position: NSPoint, size: NSSize) { + self.ivars().ime_position.set(position); + self.ivars().ime_size.set(size); + let input_context = self.inputContext().expect("input context"); + input_context.invalidateCharacterCoordinates(); + } + + /// Reset modifiers and emit a synthetic ModifiersChanged event if deemed necessary. + pub(super) fn reset_modifiers(&self) { + if !self.ivars().modifiers.get().state().is_empty() { + self.ivars().modifiers.set(Modifiers::default()); + self.queue_event(WindowEvent::ModifiersChanged(self.ivars().modifiers.get())); + } + } + + pub(super) fn set_option_as_alt(&self, value: OptionAsAlt) { + self.ivars().option_as_alt.set(value) + } + + pub(super) fn option_as_alt(&self) -> OptionAsAlt { + self.ivars().option_as_alt.get() + } + + /// Update modifiers if `event` has something different + fn update_modifiers(&self, ns_event: &NSEvent, is_flags_changed_event: bool) { + use ElementState::{Pressed, Released}; + + let current_modifiers = event_mods(ns_event); + let prev_modifiers = self.ivars().modifiers.get(); + self.ivars().modifiers.set(current_modifiers); + + // This function was called form the flagsChanged event, which is triggered + // when the user presses/releases a modifier even if the same kind of modifier + // has already been pressed. + // + // When flags changed event has key code of zero it means that event doesn't carry any key + // event, thus we can't generate regular presses based on that. The `ModifiersChanged` + // later will work though, since the flags are attached to the event and contain valid + // information. + 'send_event: { + if is_flags_changed_event && ns_event.keyCode() != 0 { + let scancode = ns_event.keyCode(); + let physical_key = scancode_to_physicalkey(scancode as u32); + + let logical_key = code_to_key(physical_key, scancode); + // Ignore processing of unknown modifiers because we can't determine whether + // it was pressed or release reliably. + // + // Furthermore, sometimes normal keys are reported inside flagsChanged:, such as + // when holding Caps Lock while pressing another key, see: + // https://github.com/alacritty/alacritty/issues/8268 + let Some(event_modifier) = key_to_modifier(&logical_key) else { + break 'send_event; + }; + + let mut event = KeyEvent { + location: code_to_location(physical_key), + logical_key: logical_key.clone(), + physical_key, + repeat: false, + // We'll correct this later. + state: Pressed, + text: None, + text_with_all_modifiers: None, + key_without_modifiers: logical_key.clone(), + }; + + let location_mask = ModLocationMask::from_location(event.location); + + let mut phys_mod_state = self.ivars().phys_modifiers.borrow_mut(); + let phys_mod = + phys_mod_state.entry(logical_key).or_insert(ModLocationMask::empty()); + + let is_active = current_modifiers.state().contains(event_modifier); + let mut events = VecDeque::with_capacity(2); + + // There is no API for getting whether the button was pressed or released + // during this event. For this reason we have to do a bit of magic below + // to come up with a good guess whether this key was pressed or released. + // (This is not trivial because there are multiple buttons that may affect + // the same modifier) + if !is_active { + event.state = Released; + if phys_mod.contains(ModLocationMask::LEFT) { + let mut event = event.clone(); + event.location = KeyLocation::Left; + event.physical_key = get_left_modifier_code(&event.logical_key).into(); + events.push_back(WindowEvent::KeyboardInput { + device_id: None, + event, + is_synthetic: false, + }); + } + if phys_mod.contains(ModLocationMask::RIGHT) { + event.location = KeyLocation::Right; + event.physical_key = get_right_modifier_code(&event.logical_key).into(); + events.push_back(WindowEvent::KeyboardInput { + device_id: None, + event, + is_synthetic: false, + }); + } + *phys_mod = ModLocationMask::empty(); + } else { + if *phys_mod == location_mask { + // Here we hit a contradiction: + // The modifier state was "changed" to active, + // yet the only pressed modifier key was the one that we + // just got a change event for. + // This seemingly means that the only pressed modifier is now released, + // but at the same time the modifier became active. + // + // But this scenario is possible if we released modifiers + // while the application was not in focus. (Because we don't + // get informed of modifier key events while the application + // is not focused) + + // In this case we prioritize the information + // about the current modifier state which means + // that the button was pressed. + event.state = Pressed; + } else { + phys_mod.toggle(location_mask); + let is_pressed = phys_mod.contains(location_mask); + event.state = if is_pressed { Pressed } else { Released }; + } + + events.push_back(WindowEvent::KeyboardInput { + device_id: None, + event, + is_synthetic: false, + }); + } + + drop(phys_mod_state); + + for event in events { + self.queue_event(event); + } + } + } + + if prev_modifiers == current_modifiers { + return; + } + + self.queue_event(WindowEvent::ModifiersChanged(self.ivars().modifiers.get())); + } + + pub(crate) fn set_dragging_session( + &self, + drag: Retained, + action_mask: NSDragOperation, + ) { + let vars = self.ivars(); + vars.dragging_session.replace(Some(drag)); + vars.drag_operations.set(action_mask); + } + + pub(crate) fn drag_operations(&self) -> NSDragOperation { + self.ivars().drag_operations.get() + } + + pub(crate) fn clear_dragging_session(&self, drag: &NSDraggingSession) -> bool { + let vars = self.ivars(); + vars.drag_operations.set(NSDragOperation::empty()); + let mut dragging_session = vars.dragging_session.borrow_mut(); + dragging_session + .take_if(|session| session.draggingSequenceNumber() == drag.draggingSequenceNumber()) + .is_some() + } + + fn mouse_click(&self, event: &NSEvent, button_state: ElementState) { + let position = self.mouse_view_point(event).to_physical(self.scale_factor()); + let button = mouse_button(event); + + self.update_modifiers(event, false); + + // `acceptsFirstMouse:` fires only for the left button, so the activation flag is + // applied to the left press and held until the matching left release. This lets + // apps short-circuit both events with a single `if is_macos_activation_click` check + // without having to track gesture state themselves. + let is_macos_activation_click = matches!(button, MouseButton::Left) + && match button_state { + ElementState::Pressed => self.ivars().next_click_is_activation.get(), + ElementState::Released => self.ivars().next_click_is_activation.replace(false), + }; + + self.queue_event(WindowEvent::PointerButton { + device_id: None, + primary: true, + state: button_state, + position, + button: button.into(), + is_macos_activation_click, + }); + } + + fn mouse_motion(&self, event: &NSEvent) { + let view_point = self.mouse_view_point(event); + let frame = self.frame(); + + if view_point.x.is_sign_negative() + || view_point.y.is_sign_negative() + || view_point.x > frame.size.width + || view_point.y > frame.size.height + { + let mouse_buttons_down = NSEvent::pressedMouseButtons(); + if mouse_buttons_down == 0 { + // Point is outside of the client area (view) and no buttons are pressed + return; + } + } + + self.update_modifiers(event, false); + + self.queue_event(WindowEvent::PointerMoved { + device_id: None, + primary: true, + position: view_point.to_physical(self.scale_factor()), + source: PointerSource::Mouse, + }); + } + + fn mouse_view_point(&self, event: &NSEvent) -> LogicalPosition { + let window_point = event.locationInWindow(); + let view_point = self.convertPoint_fromView(window_point, None); + + LogicalPosition::new(view_point.x, view_point.y) + } +} + +/// Get the mouse button from the NSEvent. +fn mouse_button(event: &NSEvent) -> MouseButton { + // The buttonNumber property only makes sense for the mouse events: + // NSLeftMouse.../NSRightMouse.../NSOtherMouse... + // For the other events, it's always set to 0. + // MacOS only defines the left, right and middle buttons, 3..=31 are left as generic buttons, + // but 3 and 4 are very commonly used as Back and Forward by hardware vendors and applications. + let b: isize = event.buttonNumber(); + b.try_into() + .ok() + .and_then(MouseButton::try_from_u8) + .expect("expected MacOS button number in the range 0..=31") +} + +// NOTE: to get option as alt working we need to rewrite events +// we're getting from the operating system, which makes it +// impossible to provide such events as extra in `KeyEvent`. +fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained { + let ev_mods = event_mods(event).state(); + let ignore_alt_characters = match option_as_alt { + OptionAsAlt::OnlyLeft if lalt_pressed(event) => true, + OptionAsAlt::OnlyRight if ralt_pressed(event) => true, + OptionAsAlt::Both if ev_mods.alt_key() => true, + _ => false, + } && !ev_mods.control_key() + && !ev_mods.meta_key(); + + if ignore_alt_characters { + let ns_chars = + event.charactersIgnoringModifiers().expect("expected characters to be non-null"); + + NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode( + event.r#type(), + event.locationInWindow(), + event.modifierFlags(), + event.timestamp(), + event.windowNumber(), + None, + &ns_chars, + &ns_chars, + event.isARepeat(), + event.keyCode(), + ) + .unwrap() + } else { + event.copy() + } +} + +/// Convert a UTF-16 code unit offset into the corresponding UTF-8 byte offset within `s`. +/// +/// IMEs are not required to send well-formed offsets, so this is defensive: an offset that +/// would split a surrogate pair is snapped down to the start of that character, and an +/// out-of-bounds offset is clamped to the end of the string (e.g. native Pinyin sends +/// out-of-bounds indices, see ). +/// +/// The mapping is monotone non-decreasing, so applying it to the location and end of an +/// `NSRange` (where `location <= end`) can never produce an inverted byte range. +/// leaf patch: with `LEAF_TRACE` set, say on stderr what the text input +/// client decided — the editor's own trace, one layer down. +fn leaf_trace(line: impl FnOnce() -> String) { + use std::sync::OnceLock; + static ON: OnceLock = OnceLock::new(); + if *ON.get_or_init(|| std::env::var_os("LEAF_TRACE").is_some()) { + eprintln!("{}", line()); + } +} + +/// leaf patch: a string's length in UTF-16 code units, AppKit's unit. +fn utf16_len(s: &str) -> usize { + s.encode_utf16().count() +} + +fn utf16_to_utf8_offset(s: &str, utf16_offset: usize) -> usize { + let mut utf16_pos = 0; + for (utf8_pos, ch) in s.char_indices() { + if utf16_pos >= utf16_offset { + return utf8_pos; + } + utf16_pos += ch.len_utf16(); + // The target offset lands strictly inside this character's UTF-16 representation, + // i.e. it splits a surrogate pair: snap down to the character boundary. + if utf16_pos > utf16_offset { + return utf8_pos; + } + } + s.len() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Apply the UTF-16 -> UTF-8 conversion to both ends of a `selectedRange {loc, len}`, + /// mirroring what `set_marked_text` does for the emitted `Ime::Preedit` cursor range. + fn convert(s: &str, loc: usize, len: usize) -> (usize, usize) { + (utf16_to_utf8_offset(s, loc), utf16_to_utf8_offset(s, loc + len)) + } + + #[test] + fn mid_surrogate_offset_snaps_down() { + // "😀a": 😀 is one char = 2 UTF-16 units = 4 UTF-8 bytes; offset 1 is mid-pair. + assert_eq!(utf16_to_utf8_offset("\u{1F600}a", 1), 0); + // Offset 2 is the boundary just after the pair. + assert_eq!(utf16_to_utf8_offset("\u{1F600}a", 2), 4); + } + + #[test] + fn no_longer_inverted() { + // "a😀b" with selectedRange {1,1}: previously emitted (1, 0) -- lower > upper, a + // slice-panic vector. The boundary-snapping conversion keeps lower <= upper. + assert_eq!(convert("a\u{1F600}b", 1, 1), (1, 1)); + } + + #[test] + fn prefix_preserved_on_mid_pair_collapse() { + // "a😀b" with selectedRange {2,0}: previously collapsed to (0, 0), discarding the + // valid "a" prefix; now snaps to the char boundary after "a". + assert_eq!(convert("a\u{1F600}b", 2, 0), (1, 1)); + } + + #[test] + fn out_of_bounds_clamps_to_len() { + // Subsumes the #4494 `.min(len)` clamp: an out-of-bounds offset maps to the string + // length instead of triggering an NSRangeException. + assert_eq!(convert("\u{1F600}a", 99, 0), (5, 5)); + } + + #[test] + fn well_formed_inputs_are_identity() { + // The common case (well-formed boundary indices) must be byte-for-byte unchanged. + assert_eq!(convert("a\u{1F600}b", 3, 0), (5, 5)); + assert_eq!(convert("a\u{1F600}b", 4, 0), (6, 6)); + // BMP multi-byte (Japanese): each char is 1 UTF-16 unit and 3 UTF-8 bytes. + assert_eq!(convert("\u{3053}\u{3093}", 1, 1), (3, 6)); + } + + #[test] + fn monotone_non_decreasing() { + // Sweep every UTF-16 offset (including out-of-bounds) over a string mixing BMP and + // non-BMP characters and assert the conversion never goes backwards, which is what + // guarantees `lower <= upper` for any `NSRange`. + let s = "a\u{1F600}b\u{3053}\u{1F4A9}c"; + let mut prev = 0; + for off in 0..=20 { + let cur = utf16_to_utf8_offset(s, off); + assert!(cur >= prev, "non-monotone at offset {off}: {cur} < {prev}"); + assert!(cur <= s.len(), "offset {off} mapped past end: {cur} > {}", s.len()); + prev = cur; + } + } +} diff --git a/patches/winit-appkit/src/window.rs b/patches/winit-appkit/src/window.rs new file mode 100644 index 0000000000..810b9fe021 --- /dev/null +++ b/patches/winit-appkit/src/window.rs @@ -0,0 +1,408 @@ +#![allow(clippy::unnecessary_cast)] + +use std::sync::Arc; + +use dispatch2::MainThreadBound; +use dpi::{Position, Size}; +use objc2::rc::{Retained, autoreleasepool}; +use objc2::{MainThreadMarker, Message, define_class}; +use objc2_app_kit::{NSPanel, NSResponder, NSWindow}; +use objc2_foundation::NSObject; +use tracing::trace_span; +use winit_core::cursor::Cursor; +use winit_core::error::RequestError; +use winit_core::icon::Icon; +use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; +use winit_core::window::{ + ImeCapabilities, ImeRequest, ImeRequestError, Theme, UserAttentionType, Window as CoreWindow, + WindowAttributes, WindowButtons, WindowId, WindowLevel, WindowPositioner, WindowType, +}; + +use super::event_loop::ActiveEventLoop; +use super::window_delegate::WindowDelegate; + +#[derive(Debug)] +pub(crate) struct Window { + window: MainThreadBound>, + /// The window only keeps a weak reference to this, so we must keep it around here. + delegate: MainThreadBound>, +} + +impl Window { + pub(crate) fn new( + window_target: &ActiveEventLoop, + attributes: WindowAttributes, + ) -> Result { + let mtm = window_target.mtm; + let delegate = + autoreleasepool(|_| WindowDelegate::new(&window_target.app_state, attributes, mtm))?; + window_target.app_state.register_window(&delegate, mtm); + let window = Window { + window: MainThreadBound::new(delegate.window().retain(), mtm), + delegate: MainThreadBound::new(delegate, mtm), + }; + window.reposition(); + Ok(window) + } + + /// Recomputes this window's position (and, if constrained, its size) from its positioner + /// state, using [`winit_common::positioner::place_window`], and applies the result. No-op if + /// this window isn't anchored, or if it has no parent. + fn reposition(&self) { + self.maybe_wait_on_main(|delegate| delegate.reposition()); + } + + pub(crate) fn maybe_wait_on_main( + &self, + f: impl FnOnce(&WindowDelegate) -> R + Send, + ) -> R { + self.delegate.get_on_main(|delegate| f(delegate)) + } + + #[inline] + pub(crate) fn raw_window_handle_rwh_06( + &self, + ) -> Result { + if let Some(mtm) = MainThreadMarker::new() { + Ok(self.delegate.get(mtm).raw_window_handle_rwh_06()) + } else { + Err(rwh_06::HandleError::Unavailable) + } + } + + #[inline] + pub(crate) fn raw_display_handle_rwh_06( + &self, + ) -> Result { + Ok(rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new())) + } +} + +impl Drop for Window { + fn drop(&mut self) { + // Restore the video mode. + if matches!(self.fullscreen(), Some(Fullscreen::Exclusive(_, _))) { + self.set_fullscreen(None); + } + + self.window.get_on_main(|window| autoreleasepool(|_| window.close())) + } +} + +impl rwh_06::HasDisplayHandle for Window { + fn display_handle(&self) -> Result, rwh_06::HandleError> { + let raw = self.raw_display_handle_rwh_06()?; + unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) } + } +} + +impl rwh_06::HasWindowHandle for Window { + fn window_handle(&self) -> Result, rwh_06::HandleError> { + let raw = self.raw_window_handle_rwh_06()?; + unsafe { Ok(rwh_06::WindowHandle::borrow_raw(raw)) } + } +} + +impl CoreWindow for Window { + fn window_type(&self) -> WindowType { + self.maybe_wait_on_main(|delegate| delegate.window_type()) + } + + fn positioner(&self) -> WindowPositioner { + self.maybe_wait_on_main(|delegate| delegate.popup_positioner()) + } + + fn set_positioner(&self, positioner: WindowPositioner) { + self.maybe_wait_on_main(|delegate| delegate.set_popup_positioner(positioner)); + } + + fn id(&self) -> winit_core::window::WindowId { + self.maybe_wait_on_main(|delegate| delegate.id()) + } + + fn scale_factor(&self) -> f64 { + self.maybe_wait_on_main(|delegate| delegate.scale_factor()) + } + + fn request_redraw(&self) { + self.maybe_wait_on_main(|delegate| delegate.request_redraw()); + } + + fn pre_present_notify(&self) { + self.maybe_wait_on_main(|delegate| delegate.pre_present_notify()); + } + + fn reset_dead_keys(&self) { + self.maybe_wait_on_main(|delegate| delegate.reset_dead_keys()); + } + + fn surface_position(&self) -> dpi::PhysicalPosition { + self.maybe_wait_on_main(|delegate| delegate.surface_position()) + } + + fn outer_position(&self) -> Result, RequestError> { + self.maybe_wait_on_main(|delegate| delegate.outer_position()) + } + + fn set_outer_position(&self, position: Position) { + self.maybe_wait_on_main(|delegate| delegate.set_outer_position(position)); + } + + fn surface_size(&self) -> dpi::PhysicalSize { + self.maybe_wait_on_main(|delegate| delegate.surface_size()) + } + + fn request_surface_size(&self, size: Size) -> Option> { + self.maybe_wait_on_main(|delegate| delegate.request_surface_size(size)) + } + + fn outer_size(&self) -> dpi::PhysicalSize { + self.maybe_wait_on_main(|delegate| delegate.outer_size()) + } + + fn safe_area(&self) -> dpi::PhysicalInsets { + self.maybe_wait_on_main(|delegate| delegate.safe_area()) + } + + fn set_min_surface_size(&self, min_size: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_min_surface_size(min_size)) + } + + fn set_max_surface_size(&self, max_size: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_max_surface_size(max_size)); + } + + fn surface_resize_increments(&self) -> Option> { + self.maybe_wait_on_main(|delegate| delegate.surface_resize_increments()) + } + + fn set_surface_resize_increments(&self, increments: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_surface_resize_increments(increments)); + } + + fn set_title(&self, title: &str) { + self.maybe_wait_on_main(|delegate| delegate.set_title(title)); + } + + fn set_transparent(&self, transparent: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_transparent(transparent)); + } + + fn set_blur(&self, blur: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_blur(blur)); + } + + fn set_visible(&self, visible: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_visible(visible)); + } + + fn is_visible(&self) -> Option { + self.maybe_wait_on_main(|delegate| delegate.is_visible()) + } + + fn set_resizable(&self, resizable: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_resizable(resizable)) + } + + fn is_resizable(&self) -> bool { + self.maybe_wait_on_main(|delegate| delegate.is_resizable()) + } + + fn set_enabled_buttons(&self, buttons: WindowButtons) { + self.maybe_wait_on_main(|delegate| delegate.set_enabled_buttons(buttons)) + } + + fn enabled_buttons(&self) -> WindowButtons { + self.maybe_wait_on_main(|delegate| delegate.enabled_buttons()) + } + + fn set_minimized(&self, minimized: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_minimized(minimized)); + } + + fn is_minimized(&self) -> Option { + self.maybe_wait_on_main(|delegate| delegate.is_minimized()) + } + + fn set_maximized(&self, maximized: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_maximized(maximized)); + } + + fn is_maximized(&self) -> bool { + self.maybe_wait_on_main(|delegate| delegate.is_maximized()) + } + + fn set_fullscreen(&self, fullscreen: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_fullscreen(fullscreen)) + } + + fn fullscreen(&self) -> Option { + self.maybe_wait_on_main(|delegate| delegate.fullscreen()) + } + + fn set_decorations(&self, decorations: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_decorations(decorations)); + } + + fn is_decorated(&self) -> bool { + self.maybe_wait_on_main(|delegate| delegate.is_decorated()) + } + + fn set_window_level(&self, level: WindowLevel) { + self.maybe_wait_on_main(|delegate| delegate.set_window_level(level)); + } + + fn set_window_icon(&self, window_icon: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_window_icon(window_icon)); + } + + fn request_ime_update(&self, request: ImeRequest) -> Result<(), ImeRequestError> { + self.maybe_wait_on_main(|delegate| delegate.request_ime_update(request)) + } + + fn ime_capabilities(&self) -> Option { + self.maybe_wait_on_main(|delegate| delegate.ime_capabilities()) + } + + fn focus_window(&self) { + self.maybe_wait_on_main(|delegate| delegate.focus_window()); + } + + fn has_focus(&self) -> bool { + self.maybe_wait_on_main(|delegate| delegate.has_focus()) + } + + fn request_user_attention(&self, request_type: Option) { + self.maybe_wait_on_main(|delegate| delegate.request_user_attention(request_type)); + } + + fn set_theme(&self, theme: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_theme(theme)); + } + + fn theme(&self) -> Option { + self.maybe_wait_on_main(|delegate| delegate.theme()) + } + + fn set_content_protected(&self, protected: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_content_protected(protected)); + } + + fn title(&self) -> String { + self.maybe_wait_on_main(|delegate| delegate.title()) + } + + fn set_cursor(&self, cursor: Cursor) { + self.maybe_wait_on_main(|delegate| delegate.set_cursor(cursor)); + } + + fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { + self.maybe_wait_on_main(|delegate| delegate.set_cursor_position(position)) + } + + fn set_cursor_grab( + &self, + mode: winit_core::window::CursorGrabMode, + ) -> Result<(), RequestError> { + self.maybe_wait_on_main(|delegate| delegate.set_cursor_grab(mode)) + } + + fn set_cursor_visible(&self, visible: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_cursor_visible(visible)) + } + + fn drag_window(&self) -> Result<(), RequestError> { + self.maybe_wait_on_main(|delegate| delegate.drag_window()) + } + + fn drag_resize_window( + &self, + direction: winit_core::window::ResizeDirection, + ) -> Result<(), RequestError> { + Ok(self.maybe_wait_on_main(|delegate| delegate.drag_resize_window(direction))?) + } + + fn show_window_menu(&self, position: Position) { + self.maybe_wait_on_main(|delegate| delegate.show_window_menu(position)) + } + + fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { + self.maybe_wait_on_main(|delegate| delegate.set_cursor_hittest(hittest)); + Ok(()) + } + + fn current_monitor(&self) -> Option { + self.maybe_wait_on_main(|delegate| { + delegate.current_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + }) + } + + fn available_monitors(&self) -> Box> { + self.maybe_wait_on_main(|delegate| { + Box::new( + delegate + .available_monitors() + .into_iter() + .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), + ) + }) + } + + fn primary_monitor(&self) -> Option { + self.maybe_wait_on_main(|delegate| { + delegate.primary_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + }) + } + + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } + + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { + self + } +} + +define_class!( + #[unsafe(super(NSWindow, NSResponder, NSObject))] + #[name = "WinitWindow"] + #[derive(Debug)] + pub struct WinitWindow; + + /// This documentation attribute makes rustfmt work for some reason? + impl WinitWindow { + #[unsafe(method(canBecomeMainWindow))] + fn can_become_main_window(&self) -> bool { + let _entered = trace_span!("canBecomeMainWindow").entered(); + true + } + + #[unsafe(method(canBecomeKeyWindow))] + fn can_become_key_window(&self) -> bool { + let _entered = trace_span!("canBecomeKeyWindow").entered(); + true + } + } +); + +define_class!( + #[unsafe(super(NSPanel, NSWindow, NSResponder, NSObject))] + #[name = "WinitPanel"] + #[derive(Debug)] + pub struct WinitPanel; + + /// This documentation attribute makes rustfmt work for some reason? + impl WinitPanel { + // although NSPanel can become key window + // it doesn't if window doesn't have NSWindowStyleMask::Titled + #[unsafe(method(canBecomeKeyWindow))] + fn can_become_key_window(&self) -> bool { + let _entered = trace_span!("canBecomeKeyWindow").entered(); + true + } + } +); + +pub(super) fn window_id(window: &NSWindow) -> WindowId { + WindowId::from_raw(window as *const _ as usize) +} diff --git a/patches/winit-appkit/src/window_delegate.rs b/patches/winit-appkit/src/window_delegate.rs new file mode 100644 index 0000000000..e04c3963f1 --- /dev/null +++ b/patches/winit-appkit/src/window_delegate.rs @@ -0,0 +1,2571 @@ +#![allow(clippy::unnecessary_cast)] +use std::cell::{Cell, RefCell}; +use std::collections::VecDeque; +use std::ffi::c_void; +use std::ptr; +use std::rc::Rc; +use std::sync::{Arc, Mutex}; + +use dispatch2::MainThreadBound; +use dpi::{ + LogicalInsets, LogicalPosition, LogicalSize, PhysicalInsets, PhysicalPosition, PhysicalSize, + Position, Size, +}; +use objc2::rc::{Retained, autoreleasepool}; +use objc2::runtime::{AnyObject, ProtocolObject}; +use objc2::{ + ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, Message, available, define_class, + msg_send, sel, +}; +use objc2_app_kit::{ + NSAppKitVersionNumber, NSAppKitVersionNumber10_12, NSAppearance, NSAppearanceCustomization, + NSAppearanceNameAqua, NSApplication, NSApplicationPresentationOptions, + NSAutoresizingMaskOptions, NSBackingStoreType, NSColor, NSDragOperation, NSDraggingContext, + NSDraggingDestination, NSDraggingInfo, NSDraggingSession, NSDraggingSource, + NSPasteboardTypeFileURL, NSPasteboardTypeHTML, NSPasteboardTypePNG, NSPasteboardTypeSound, + NSPasteboardTypeString, NSPasteboardTypeTIFF, NSRequestUserAttentionType, NSScreen, NSToolbar, + NSView, NSViewFrameDidChangeNotification, NSWindow, NSWindowButton, NSWindowCollectionBehavior, + NSWindowDelegate, NSWindowLevel, NSWindowOcclusionState, NSWindowOrderingMode, + NSWindowSharingType, NSWindowStyleMask, NSWindowTabbingMode, NSWindowTitleVisibility, + NSWindowToolbarStyle, +}; +#[cfg(not(feature = "private-apple-apis"))] +use objc2_app_kit::{ + NSVisualEffectBlendingMode, NSVisualEffectMaterial, NSVisualEffectState, NSVisualEffectView, +}; +use objc2_core_foundation::{CGFloat, CGPoint}; +use objc2_core_graphics::{ + CGAcquireDisplayFadeReservation, CGAssociateMouseAndMouseCursorPosition, CGDisplayCapture, + CGDisplayFade, CGDisplayRelease, CGDisplaySetDisplayMode, CGReleaseDisplayFadeReservation, + CGRestorePermanentDisplayConfiguration, CGShieldingWindowLevel, CGWarpMouseCursorPosition, + kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, kCGDisplayFadeReservationInvalidToken, + kCGFloatingWindowLevel, kCGNormalWindowLevel, +}; +use objc2_foundation::{ + NSArray, NSDictionary, NSEdgeInsets, NSKeyValueChangeKey, NSKeyValueChangeNewKey, + NSKeyValueChangeOldKey, NSKeyValueObservingOptions, NSNotificationCenter, NSObject, + NSObjectNSDelayedPerforming, NSObjectNSKeyValueObserverRegistration, NSObjectProtocol, NSPoint, + NSRect, NSSize, NSString, ns_string, +}; +use tracing::{debug_span, trace, warn}; +use winit_common::core_foundation::MainRunLoop; +use winit_common::positioner::place_window; +use winit_core::cursor::Cursor; +use winit_core::data_transfer::DataTransferId; +use winit_core::error::{NotSupportedError, RequestError}; +use winit_core::event::{SurfaceSizeWriter, WindowEvent}; +use winit_core::icon::Icon; +use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle, MonitorHandleProvider}; +use winit_core::window::{ + CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, + UserAttentionType, WindowAttributes, WindowButtons, WindowId, WindowLevel, WindowPositioner, + WindowType, +}; + +use super::app_state::AppState; +use super::cursor::{CustomCursor, cursor_from_icon}; +use super::monitor::{self, MonitorHandle, flip_window_screen_coordinates, get_display_id}; +use super::util::cgerr; +use super::view::WinitView; +use super::window::{WinitPanel, WinitWindow, window_id}; +use crate::app_state::DragState; +use crate::dnd::{ + dnd_action_to_ns_drag_operation, ns_drag_operation_to_dnd_action, preferred_drag_operation, +}; +use crate::{BlurMaterial, OptionAsAlt, WindowAttributesMacOS, WindowExtMacOS}; + +#[derive(Debug)] +pub(crate) struct State { + /// Strong reference to the global application state. + app_state: Rc, + + window: Retained, + + view: Retained, + + #[cfg(not(feature = "private-apple-apis"))] + blur_view: RefCell>>, + + blur_material: Cell, + + // During `windowDidResize`, we use this to only send Moved if the position changed. + // + // This is expressed in desktop coordinates, and flipped to match Winit's coordinate system. + previous_position: Cell, + + // Used to prevent redundant events. + previous_scale_factor: Cell, + + /// The current resize increments for the window content. + surface_resize_increments: Cell, + /// Whether the window is showing decorations. + decorations: Cell, + resizable: Cell, + maximized: Cell, + + /// Presentation options saved before entering `set_simple_fullscreen`, and + /// restored upon exiting it. Also used when transitioning from Borderless to + /// Exclusive fullscreen in `set_fullscreen` because we need to disable the menu + /// bar in exclusive fullscreen but want to restore the original options when + /// transitioning back to borderless fullscreen. + save_presentation_opts: Cell>, + // This is set when WindowAttributes::with_fullscreen was set, + // see comments of `window_did_fail_to_enter_fullscreen` + initial_fullscreen: Cell, + /// This field tracks the current fullscreen state of the window + /// (as seen by `WindowDelegate`). + fullscreen: RefCell>, + // If it is attempted to toggle fullscreen when in_fullscreen_transition is true, + // Set target_fullscreen and do after fullscreen transition is end. + target_fullscreen: RefCell>>, + // This is true between windowWillEnterFullScreen and windowDidEnterFullScreen + // or windowWillExitFullScreen and windowDidExitFullScreen. + // We must not toggle fullscreen when this is true. + in_fullscreen_transition: Cell, + standard_frame: Cell>, + is_simple_fullscreen: Cell, + saved_style: Cell>, + is_borderless_game: Cell, + /// The window's role, used for creation/role behavior (decorations, activation/keyboard-grab + /// default, initial placement). Does *not* determine whether the window is anchor-positioned + /// -- see `anchored`. + window_type: WindowType, + /// Whether this window is positioned relative to its parent using the anchor/gravity/ + /// positioner system, either because it's a [`WindowType::Popup`] or because anchor + /// attributes were set on a [`WindowType::Window`]. Gates the parent-relative coordinate + /// frame used when applying anchor/gravity/positioner-offset changes. + anchored: bool, + positioner: RefCell, +} + +define_class!( + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "WinitWindowDelegate"] + #[ivars = State] + pub(crate) struct WindowDelegate; + + unsafe impl NSObjectProtocol for WindowDelegate {} + + unsafe impl NSWindowDelegate for WindowDelegate { + #[unsafe(method(windowShouldClose:))] + fn window_should_close(&self, _: Option<&AnyObject>) -> bool { + let _entered = debug_span!("windowShouldClose:").entered(); + self.queue_event(WindowEvent::CloseRequested); + false + } + + #[unsafe(method(windowWillClose:))] + fn window_will_close(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowWillClose:").entered(); + // `setDelegate:` retains the previous value and then autoreleases it + autoreleasepool(|_| { + // Since El Capitan, we need to be careful that delegate methods can't + // be called after the window closes. + self.window().setDelegate(None); + }); + self.queue_event(WindowEvent::Destroyed); + } + + #[unsafe(method(windowDidResize:))] + fn window_did_resize(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidResize:").entered(); + // NOTE: WindowEvent::SurfaceResized is reported using NSViewFrameDidChangeNotification. + self.emit_move_event(); + // `windowDidMove:` isn't triggered when a move is part of a resize (e.g. dragging the + // top or left edge), so anchored children need repositioning here too. + self.reposition_child_windows(); + } + + #[unsafe(method(windowWillStartLiveResize:))] + fn window_will_start_live_resize(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowWillStartLiveResize:").entered(); + + let increments = self.ivars().surface_resize_increments.get(); + self.set_resize_increments_inner(increments); + } + + #[unsafe(method(windowDidEndLiveResize:))] + fn window_did_end_live_resize(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidEndLiveResize:").entered(); + self.set_resize_increments_inner(NSSize::new(1., 1.)); + } + + // This won't be triggered if the move was part of a resize. + #[unsafe(method(windowDidMove:))] + fn window_did_move(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidMove:").entered(); + self.emit_move_event(); + self.reposition_child_windows(); + } + + #[unsafe(method(windowDidChangeBackingProperties:))] + fn window_did_change_backing_properties(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidChangeBackingProperties:").entered(); + let scale_factor = self.scale_factor(); + if scale_factor == self.ivars().previous_scale_factor.get() { + return; + }; + self.ivars().previous_scale_factor.set(scale_factor); + + let mtm = MainThreadMarker::from(self); + let this = self.retain(); + MainRunLoop::get(mtm).queue_closure(move || { + this.handle_scale_factor_changed(scale_factor); + }); + } + + #[unsafe(method(windowDidBecomeKey:))] + fn window_did_become_key(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidBecomeKey:").entered(); + // TODO: center the cursor if the window had mouse grab when it + // lost focus + self.queue_event(WindowEvent::Focused(true)); + } + + #[unsafe(method(windowDidResignKey:))] + fn window_did_resign_key(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidResignKey:").entered(); + // It happens rather often, e.g. when the user is Cmd+Tabbing, that the + // NSWindowDelegate will receive a didResignKey event despite no event + // being received when the modifiers are released. This is because + // flagsChanged events are received by the NSView instead of the + // NSWindowDelegate, and as a result a tracked modifiers state can quite + // easily fall out of synchrony with reality. This requires us to emit + // a synthetic ModifiersChanged event when we lose focus. + self.view().reset_modifiers(); + + self.queue_event(WindowEvent::Focused(false)); + } + + /// Invoked when before enter fullscreen + #[unsafe(method(windowWillEnterFullScreen:))] + fn window_will_enter_fullscreen(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowWillEnterFullScreen:").entered(); + + self.ivars().maximized.set(self.is_zoomed()); + let mut fullscreen = self.ivars().fullscreen.borrow_mut(); + match &*fullscreen { + // Exclusive mode sets the state in `set_fullscreen` as the user + // can't enter exclusive mode by other means (like the + // fullscreen button on the window decorations) + Some(Fullscreen::Exclusive(..)) => (), + // `window_will_enter_fullscreen` was triggered and we're already + // in fullscreen, so we must've reached here by `set_fullscreen` + // as it updates the state + Some(Fullscreen::Borderless(_)) => (), + Some(_) => (), + // Otherwise, we must've reached fullscreen by the user clicking + // on the green fullscreen button. Update state! + None => { + let current_monitor = self + .current_monitor_inner() + .map(|monitor| CoreMonitorHandle(Arc::new(monitor))); + *fullscreen = Some(Fullscreen::Borderless(current_monitor)); + }, + } + self.ivars().in_fullscreen_transition.set(true); + } + + /// Invoked when before exit fullscreen + #[unsafe(method(windowWillExitFullScreen:))] + fn window_will_exit_fullscreen(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowWillExitFullScreen:").entered(); + + self.ivars().in_fullscreen_transition.set(true); + } + + #[unsafe(method(window:willUseFullScreenPresentationOptions:))] + fn window_will_use_fullscreen_presentation_options( + &self, + _: Option<&AnyObject>, + proposed_options: NSApplicationPresentationOptions, + ) -> NSApplicationPresentationOptions { + let _entered = debug_span!("window:willUseFullScreenPresentationOptions:").entered(); + // Generally, games will want to disable the menu bar and the dock. Ideally, + // this would be configurable by the user. Unfortunately because of our + // `CGShieldingWindowLevel() + 1` hack (see `set_fullscreen`), our window is + // placed on top of the menu bar in exclusive fullscreen mode. This looks + // broken so we always disable the menu bar in exclusive fullscreen. We may + // still want to make this configurable for borderless fullscreen. Right now + // we don't, for consistency. If we do, it should be documented that the + // user-provided options are ignored in exclusive fullscreen. + let mut options = proposed_options; + let fullscreen = self.ivars().fullscreen.borrow(); + if let Some(Fullscreen::Exclusive(..)) = &*fullscreen { + options = NSApplicationPresentationOptions::FullScreen + | NSApplicationPresentationOptions::HideDock + | NSApplicationPresentationOptions::HideMenuBar; + } + + options + } + + /// Invoked when entered fullscreen + #[unsafe(method(windowDidEnterFullScreen:))] + fn window_did_enter_fullscreen(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidEnterFullScreen:").entered(); + self.ivars().initial_fullscreen.set(false); + self.ivars().in_fullscreen_transition.set(false); + if let Some(target_fullscreen) = self.ivars().target_fullscreen.take() { + self.set_fullscreen(target_fullscreen); + } + } + + /// Invoked when exited fullscreen + #[unsafe(method(windowDidExitFullScreen:))] + fn window_did_exit_fullscreen(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidExitFullScreen:").entered(); + + self.restore_state_from_fullscreen(); + self.ivars().in_fullscreen_transition.set(false); + if let Some(target_fullscreen) = self.ivars().target_fullscreen.take() { + self.set_fullscreen(target_fullscreen); + } + } + + /// Invoked when fail to enter fullscreen + /// + /// When this window launch from a fullscreen app (e.g. launch from VS Code + /// terminal), it creates a new virtual desktop and a transition animation. + /// This animation takes one second and cannot be disable without + /// elevated privileges. In this animation time, all toggleFullscreen events + /// will be failed. In this implementation, we will try again by using + /// performSelector:withObject:afterDelay: until window_did_enter_fullscreen. + /// It should be fine as we only do this at initialization (i.e with_fullscreen + /// was set). + /// + /// From Apple doc: + /// In some cases, the transition to enter full-screen mode can fail, + /// due to being in the midst of handling some other animation or user gesture. + /// This method indicates that there was an error, and you should clean up any + /// work you may have done to prepare to enter full-screen mode. + #[unsafe(method(windowDidFailToEnterFullScreen:))] + fn window_did_fail_to_enter_fullscreen(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidFailToEnterFullScreen:").entered(); + self.ivars().in_fullscreen_transition.set(false); + self.ivars().target_fullscreen.replace(None); + if self.ivars().initial_fullscreen.get() { + unsafe { + self.window().performSelector_withObject_afterDelay( + sel!(toggleFullScreen:), + None, + 0.5, + ) + }; + } else { + self.restore_state_from_fullscreen(); + } + } + + // Invoked when the occlusion state of the window changes + #[unsafe(method(windowDidChangeOcclusionState:))] + fn window_did_change_occlusion_state(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidChangeOcclusionState:").entered(); + let visible = self.window().occlusionState().contains(NSWindowOcclusionState::Visible); + self.queue_event(WindowEvent::Occluded(!visible)); + + // We do this here rather than in `window:willUseFullScreenPresentationOptions` + // because doing it there leaves the menu bar interactable despite being hidden. + // Moving it here produces the most consistent results. + if self.is_borderless_game() + && matches!(*self.ivars().fullscreen.borrow(), Some(Fullscreen::Borderless(_))) + { + let mtm = MainThreadMarker::from(self); + let app = NSApplication::sharedApplication(mtm); + app.setPresentationOptions( + NSApplicationPresentationOptions::HideDock + | NSApplicationPresentationOptions::HideMenuBar, + ); + } + } + + #[unsafe(method(windowDidChangeScreen:))] + fn window_did_change_screen(&self, _: Option<&AnyObject>) { + let _entered = debug_span!("windowDidChangeScreen:").entered(); + let is_simple_fullscreen = self.ivars().is_simple_fullscreen.get(); + if is_simple_fullscreen { + if let Some(screen) = self.window().screen() { + self.window().setFrame_display(screen.frame(), true); + } + } + } + } + + unsafe impl NSDraggingSource for WindowDelegate { + #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))] + fn dragging_session_source_operation_mask( + &self, + _: &NSDraggingSession, + _: NSDraggingContext, + ) -> NSDragOperation { + self.view().drag_operations() + } + + #[unsafe(method(draggingSession:endedAtPoint:operation:))] + fn dragging_session_ended_at_point( + &self, + session: &NSDraggingSession, + _: NSPoint, + operation: NSDragOperation, + ) { + let id = DataTransferId::from_raw(session.draggingSequenceNumber() as i64); + if operation == NSDragOperation::None { + self.queue_event(WindowEvent::OutgoingDragCanceled { id }); + } else { + self.queue_event(WindowEvent::OutgoingDragDropped { + id, + action: ns_drag_operation_to_dnd_action(operation), + }); + } + + self.view().clear_dragging_session(session); + } + } + + unsafe impl NSDraggingDestination for WindowDelegate { + /// Invoked when the dragged image enters destination bounds or frame + #[unsafe(method(draggingEntered:))] + fn dragging_entered(&self, sender: &ProtocolObject) -> NSDragOperation { + let _entered = debug_span!("draggingEntered:").entered(); + + let pb = + MainThreadBound::new(sender.draggingPasteboard(), MainThreadMarker::new().unwrap()); + + let dl = sender.draggingLocation(); + let dl = self.view().convertPoint_fromView(dl, None); + let position = + LogicalPosition::::from((dl.x, dl.y)).to_physical(self.scale_factor()); + + let window_id = self.id(); + + let vars = self.ivars(); + + let source_operations = sender.draggingSourceOperationMask(); + + let transfer_id = DataTransferId::from_raw(sender.draggingSequenceNumber() as i64); + vars.app_state.pasteboards().insert(transfer_id, &pb, window_id); + + vars.app_state + .drag_state() + .replace(Some(DragState { id: transfer_id, valid_actions: vec![] })); + + self.queue_event(WindowEvent::DragEntered { + id: transfer_id, + position: Some(position), + }); + + let drag_state = vars.app_state.drag_state().borrow(); + + drag_state + .as_ref() + .and_then(|drag_state| { + preferred_drag_operation(source_operations, &drag_state.valid_actions) + }) + .map(dnd_action_to_ns_drag_operation) + .unwrap_or(NSDragOperation::empty()) + } + + #[unsafe(method(wantsPeriodicDraggingUpdates))] + fn wants_periodic_dragging_updates(&self) -> bool { + let _entered = debug_span!("wantsPeriodicDraggingUpdates:").entered(); + true + } + + /// Invoked periodically as the image is held within the destination area, allowing + /// modification of the dragging operation or mouse-pointer position. + #[unsafe(method(draggingUpdated:))] + fn dragging_updated(&self, sender: &ProtocolObject) -> NSDragOperation { + let _entered = debug_span!("draggingUpdated:").entered(); + + let vars = self.ivars(); + + let Some(transfer_id) = + vars.app_state.drag_state().borrow().as_ref().map(|state| state.id) + else { + return NSDragOperation::empty(); + }; + + let pb = + MainThreadBound::new(sender.draggingPasteboard(), MainThreadMarker::new().unwrap()); + + let source_operations = sender.draggingSourceOperationMask(); + + vars.app_state.pasteboards().set_pasteboard(transfer_id, &pb); + + let dl = sender.draggingLocation(); + let dl = self.view().convertPoint_fromView(dl, None); + let position = + LogicalPosition::::from((dl.x, dl.y)).to_physical(self.scale_factor()); + + let proposed_action = vars.app_state.proposed_drag_action(source_operations); + + self.queue_event(WindowEvent::DragPosition { + id: transfer_id, + position, + proposed_action, + }); + + let drag_state = vars.app_state.drag_state().borrow(); + + drag_state + .as_ref() + .and_then(|drag_state| { + preferred_drag_operation(source_operations, &drag_state.valid_actions) + }) + .map(dnd_action_to_ns_drag_operation) + .unwrap_or(NSDragOperation::empty()) + } + + /// Invoked when the image is released + #[unsafe(method(prepareForDragOperation:))] + fn prepare_for_drag_operation(&self, _sender: &NSObject) -> bool { + let _entered = debug_span!("prepareForDragOperation:").entered(); + true + } + + /// Invoked after the released image has been removed from the screen + #[unsafe(method(performDragOperation:))] + fn perform_drag_operation(&self, sender: &ProtocolObject) -> bool { + let _entered = debug_span!("performDragOperation:").entered(); + + let vars = self.ivars(); + + let Some(transfer_id) = + vars.app_state.drag_state().borrow().as_ref().map(|state| state.id) + else { + return false.into(); + }; + + let pb = + MainThreadBound::new(sender.draggingPasteboard(), MainThreadMarker::new().unwrap()); + + let source_operations = sender.draggingSourceOperationMask(); + // let operations = ns_drag_operation_to_dnd_actions(source_operations); + + vars.app_state.pasteboards().set_pasteboard(transfer_id, &pb); + + let dl = sender.draggingLocation(); + let dl = self.view().convertPoint_fromView(dl, None); + let position = + LogicalPosition::::from((dl.x, dl.y)).to_physical(self.scale_factor()); + + let proposed_action = vars.app_state.proposed_drag_action(source_operations); + + self.queue_event(WindowEvent::DragPosition { + id: transfer_id, + position, + proposed_action, + }); + + // Check again, in case the application updated + let proposed_action = vars.app_state.proposed_drag_action(source_operations); + + self.queue_event(WindowEvent::DragDropped { id: transfer_id, proposed_action }); + + // We assume that if the OS has sent `perform_drag_operation`, that the drag succeeded. + // We may want to extend this API in the future to allow signalling that the final drop + // failed. + true + } + + /// Invoked when the dragging operation is complete + #[unsafe(method(concludeDragOperation:))] + fn conclude_drag_operation(&self, _sender: Option<&NSObject>) { + let _entered = debug_span!("concludeDragOperation:").entered(); + let vars = self.ivars(); + + vars.app_state.pasteboards().remove_deloaded_pasteboards(); + vars.app_state.drag_state().take(); + } + + /// Invoked when the dragging operation is cancelled + #[unsafe(method(draggingExited:))] + fn dragging_exited(&self, sender: Option<&ProtocolObject>) { + let _entered = debug_span!("draggingExited:").entered(); + + let vars = self.ivars(); + + let Some(transfer_id) = + vars.app_state.drag_state().borrow().as_ref().map(|state| state.id) + else { + return; + }; + + if let Some(sender) = sender { + let pb = MainThreadBound::new( + sender.draggingPasteboard(), + MainThreadMarker::new().unwrap(), + ); + vars.app_state.pasteboards().set_pasteboard(transfer_id, &pb); + + let dl = sender.draggingLocation(); + let dl = self.view().convertPoint_fromView(dl, None); + let position = + LogicalPosition::::from((dl.x, dl.y)).to_physical(self.scale_factor()); + + let source_operations = sender.draggingSourceOperationMask(); + let proposed_action = vars.app_state.proposed_drag_action(source_operations); + + self.queue_event(WindowEvent::DragPosition { + id: transfer_id, + position, + proposed_action, + }); + } + + self.queue_event(WindowEvent::DragLeft { id: transfer_id }); + + vars.app_state.drag_state().take(); + } + } + + /// Key-Value Observing + impl WindowDelegate { + #[unsafe(method(observeValueForKeyPath:ofObject:change:context:))] + fn observe_value( + &self, + key_path: Option<&NSString>, + _object: Option<&AnyObject>, + change: Option<&NSDictionary>, + _context: *mut c_void, + ) { + let _entered = debug_span!("observeValueForKeyPath:ofObject:change:context:").entered(); + // NOTE: We don't _really_ need to check the key path, as there should only be one, but + // in the future we might want to observe other key paths. + if key_path == Some(ns_string!("effectiveAppearance")) { + let change = change.expect( + "requested a change dictionary in `addObserver`, but none was provided", + ); + let old = change + .objectForKey(unsafe { NSKeyValueChangeOldKey }) + .expect("requested change dictionary did not contain `NSKeyValueChangeOldKey`"); + let new = change + .objectForKey(unsafe { NSKeyValueChangeNewKey }) + .expect("requested change dictionary did not contain `NSKeyValueChangeNewKey`"); + + // The value of `effectiveAppearance` is `NSAppearance` + let old = old.downcast::().unwrap(); + let new = new.downcast::().unwrap(); + + trace!(old = %old.name(), new = %new.name(), "effectiveAppearance changed"); + + // Ignore the change if the window's theme is customized by the user (since in that + // case the `effectiveAppearance` is only emitted upon said customization, and then + // it's triggered directly by a user action, and we don't want to emit the event). + if self.window().appearance().is_some() { + return; + } + + let old = appearance_to_theme(&old); + let new = appearance_to_theme(&new); + // Check that the theme changed in Winit's terms (the theme might have changed on + // other parameters, such as level of contrast, but the event should not be emitted + // in those cases). + if old == new { + return; + } + + self.queue_event(WindowEvent::ThemeChanged(new)); + } else { + panic!("unknown observed keypath {key_path:?}"); + } + } + } +); + +impl Drop for WindowDelegate { + fn drop(&mut self) { + unsafe { self.window().removeObserver_forKeyPath(self, ns_string!("effectiveAppearance")) }; + } +} + +fn new_window( + app_state: &Rc, + attrs: &WindowAttributes, + macos_attrs: &WindowAttributesMacOS, + anchored: bool, + mtm: MainThreadMarker, +) -> Option<(Retained, Retained)> { + autoreleasepool(|_| { + let screen = match attrs.fullscreen.clone() { + Some(Fullscreen::Borderless(Some(monitor))) + | Some(Fullscreen::Exclusive(monitor, _)) => { + let monitor = monitor.cast_ref::().unwrap(); + monitor.ns_screen(mtm).or_else(|| NSScreen::mainScreen(mtm)) + }, + Some(Fullscreen::Borderless(None)) => NSScreen::mainScreen(mtm), + Some(_) => NSScreen::mainScreen(mtm), + None => None, + }; + let frame = match &screen { + Some(screen) => screen.frame(), + None => { + let scale_factor = NSScreen::mainScreen(mtm) + .map(|screen| screen.backingScaleFactor() as f64) + .unwrap_or(1.0); + let size = match attrs.surface_size { + Some(size) => { + let size = size.to_logical(scale_factor); + NSSize::new(size.width, size.height) + }, + None => NSSize::new(800.0, 600.0), + }; + let position = match attrs.position { + // An anchored window's position is parent-relative; it's applied in + // `WindowDelegate::new` (after the delegate exists) via the shared + // translation in `set_outer_position`. A parentless anchored window can't be + // positioned that way, so it falls through to the same handling as a + // non-anchored window below. + _ if anchored && attrs.parent_window().is_some() => NSPoint::new(0.0, 0.0), + Some(position) => { + let position = position.to_logical(scale_factor); + flip_window_screen_coordinates(NSRect::new( + NSPoint::new(position.x, position.y), + size, + )) + }, + // This value is ignored by calling win.center() below + None => NSPoint::new(0.0, 0.0), + }; + NSRect::new(position, size) + }, + }; + + let mut masks = if (!attrs.decorations && screen.is_none()) || macos_attrs.titlebar_hidden { + // Resizable without a titlebar or borders + // if decorations is set to false, ignore pl_attrs + // + // if the titlebar is hidden, ignore other pl_attrs + NSWindowStyleMask::Borderless + | NSWindowStyleMask::Resizable + | NSWindowStyleMask::Miniaturizable + } else { + // default case, resizable window with titlebar and titlebar buttons + NSWindowStyleMask::Closable + | NSWindowStyleMask::Miniaturizable + | NSWindowStyleMask::Resizable + | NSWindowStyleMask::Titled + }; + + if !attrs.resizable { + masks &= !NSWindowStyleMask::Resizable; + } + + if !attrs.enabled_buttons.contains(WindowButtons::MINIMIZE) { + masks &= !NSWindowStyleMask::Miniaturizable; + } + + if !attrs.enabled_buttons.contains(WindowButtons::CLOSE) { + masks &= !NSWindowStyleMask::Closable; + } + + if macos_attrs.fullsize_content_view { + // NOTE: If we decide to add an option to change this at runtime, we must emit a + // `SurfaceResized` event to let applications know that the safe area changed. + // + // An alternative would be to add a `WindowEvent::SafeAreaChanged` event, this could be + // done with an observer on `safeAreaRect` / `contentLayoutRect`, see: + // + masks |= NSWindowStyleMask::FullSizeContentView; + } + + // NOTE: This should only be created after the application has started launching, + // (`applicationWillFinishLaunching:` at the earliest), otherwise you'll run into very + // confusing issues with the window not being properly activated. + // + // Winit ensures this by not allowing access to `ActiveEventLoop` before handling events. + // Panels (including popups) are non-activating so they don't steal key focus + // from their parent (matching menu/combobox semantics). + let window: Retained = if macos_attrs.panel { + masks |= NSWindowStyleMask::NonactivatingPanel; + + let window: Option> = unsafe { + msg_send![ + super(mtm.alloc().set_ivars(())), + initWithContentRect: frame, + styleMask: masks, + backing: NSBackingStoreType::Buffered, + defer: false, + ] + }; + + window?.as_super().as_super().retain() + } else { + let window: Option> = unsafe { + msg_send![ + super(mtm.alloc().set_ivars(())), + initWithContentRect: frame, + styleMask: masks, + backing: NSBackingStoreType::Buffered, + defer: false, + ] + }; + + window?.as_super().retain() + }; + + // It is very important for correct memory management that we + // disable the extra release that would otherwise happen when + // calling `close` on the window. + unsafe { window.setReleasedWhenClosed(false) }; + + window.setTitle(&NSString::from_str(&attrs.title)); + window.setAcceptsMouseMovedEvents(true); + + if let Some(identifier) = &macos_attrs.tabbing_identifier { + window.setTabbingIdentifier(&NSString::from_str(identifier)); + window.setTabbingMode(NSWindowTabbingMode::Preferred); + } + + if attrs.content_protected { + window.setSharingType(NSWindowSharingType::None); + } + + if macos_attrs.titlebar_transparent { + window.setTitlebarAppearsTransparent(true); + } + if macos_attrs.title_hidden { + window.setTitleVisibility(NSWindowTitleVisibility::Hidden); + } + if macos_attrs.titlebar_buttons_hidden { + for titlebar_button in &[ + #[allow(deprecated)] + objc2_app_kit::NSWindowFullScreenButton, + NSWindowButton::MiniaturizeButton, + NSWindowButton::CloseButton, + NSWindowButton::ZoomButton, + ] { + if let Some(button) = window.standardWindowButton(*titlebar_button) { + button.setHidden(true); + } + } + } + if macos_attrs.movable_by_window_background { + window.setMovableByWindowBackground(true); + } + if macos_attrs.unified_titlebar { + // The toolbar style is ignored if there is no toolbar, so it is + // necessary to add one. + window.setToolbar(Some(&NSToolbar::new(mtm))); + window.setToolbarStyle(NSWindowToolbarStyle::Unified); + } + + if !attrs.enabled_buttons.contains(WindowButtons::MAXIMIZE) { + if let Some(button) = window.standardWindowButton(NSWindowButton::ZoomButton) { + button.setEnabled(false); + } + } + + if !macos_attrs.has_shadow { + window.setHasShadow(false); + } + if macos_attrs.fullscreen_auxiliary { + // This must happen before the window is ordered on screen (below, and in + // `WindowDelegate::new`), so that showing the window doesn't make macOS + // switch away from an active fullscreen Space or attempt Split View tiling. + window.setCollectionBehavior( + window.collectionBehavior() | NSWindowCollectionBehavior::FullScreenAuxiliary, + ); + } + // Center window if the position is not set or it doesn't have any parent + if attrs.position.is_none() && !(anchored && attrs.parent_window().is_some()) { + window.center(); + } + + let view = WinitView::new(app_state, macos_attrs.option_as_alt, mtm); + + // The default value of `setWantsBestResolutionOpenGLSurface:` was `false` until + // macos 10.14 and `true` after 10.15, we should set it to `YES` or `NO` to avoid + // always the default system value in favour of the user's code + #[allow(deprecated)] + view.setWantsBestResolutionOpenGLSurface(!macos_attrs.disallow_hidpi); + + // On Mojave, views automatically become layer-backed shortly after being added to + // a window. Changing the layer-backedness of a view breaks the association between + // the view and its associated OpenGL context. To work around this, on Mojave we + // explicitly make the view layer-backed up front so that AppKit doesn't do it + // itself and break the association with its context. + if unsafe { NSAppKitVersionNumber }.floor() > NSAppKitVersionNumber10_12 { + view.setWantsLayer(true); + } + + let content_view = NSView::new(mtm); + window.setContentView(Some(&content_view)); + + view.setFrame(content_view.bounds()); + view.setAutoresizingMask( + NSAutoresizingMaskOptions::ViewWidthSizable + | NSAutoresizingMaskOptions::ViewHeightSizable, + ); + content_view.addSubview(&view); + + // Configure the new view as the "key view" for the window + window.setInitialFirstResponder(Some(&view)); + + // Configure the view to send notifications whenever its frame rectangle changes. + // + // We explicitly do this _after_ adding the view to the window, to + // avoid a resize event when creating the window. + view.setPostsFrameChangedNotifications(true); + // `setPostsFrameChangedNotifications` posts the notification immediately, so register the + // observer _after_, again so that the event isn't triggered initially. + let notification_center = NSNotificationCenter::defaultCenter(); + unsafe { + notification_center.addObserver_selector_name_object( + &view, + sel!(viewFrameDidChangeNotification:), + Some(NSViewFrameDidChangeNotification), + Some(&view), + ) + } + + if attrs.transparent { + window.setOpaque(false); + // See `set_transparent` for details on why we do this. + window.setBackgroundColor(Some(&NSColor::clearColor())); + } + + Some((window, view)) + }) +} + +impl WindowDelegate { + pub(super) fn new( + app_state: &Rc, + mut attrs: WindowAttributes, + mtm: MainThreadMarker, + ) -> Result, RequestError> { + let mut macos_attrs = attrs + .platform + .take() + .and_then(|attrs| attrs.cast::().ok()) + .unwrap_or_default(); + + let window_type = attrs.window_type(); + let is_popup = matches!(window_type, WindowType::Popup); + let anchored = is_popup || attrs.positioner.is_some(); + if is_popup { + // A popup is an undecorated, non-activating panel with no titlebar buttons. Model it + // as such so it flows through the existing borderless + panel paths in `new_window` + // instead of needing dedicated branches. + attrs.decorations = false; + attrs.enabled_buttons = WindowButtons::empty(); + // Unless grab_keyboard is requested, use a non-activating panel so the popup doesn't + // steal keyboard focus from the parent window. + if !attrs.active { + macos_attrs.panel = true; + } + } + + let (window, view) = new_window(app_state, &attrs, &macos_attrs, anchored, mtm) + .ok_or_else(|| os_error!("couldn't create `NSWindow`"))?; + + match attrs.parent_window() { + Some(rwh_06::RawWindowHandle::AppKit(handle)) => { + // SAFETY: Caller ensures the pointer is valid or NULL + // Unwrap is fine, since the pointer comes from `NonNull`. + let parent_view: Retained = + unsafe { Retained::retain(handle.ns_view.as_ptr().cast()) }.unwrap(); + let parent = parent_view + .window() + .ok_or_else(|| os_error!("parent view should be installed in a window"))?; + + // SAFETY: We know that there are no parent -> child -> parent cycles since the only + // place in `winit` where we allow making a window a child window is + // right here, just after it's been created. + unsafe { parent.addChildWindow_ordered(&window, NSWindowOrderingMode::Above) }; + }, + Some(raw) => panic!("invalid raw window handle {raw:?} on macOS"), + None if is_popup => { + return Err(RequestError::NotSupported(NotSupportedError::new( + "a popup window requires a parent window", + ))); + }, + None => (), + } + + let surface_resize_increments = match attrs + .surface_resize_increments + .map(|i| i.to_logical(window.backingScaleFactor() as _)) + { + Some(LogicalSize { width, height }) if width >= 1. && height >= 1. => { + NSSize::new(width, height) + }, + _ => NSSize::new(1., 1.), + }; + + let scale_factor = window.backingScaleFactor() as _; + + if let Some(appearance) = theme_to_appearance(attrs.preferred_theme) { + window.setAppearance(Some(&appearance)); + } + + let delegate = mtm.alloc().set_ivars(State { + app_state: Rc::clone(app_state), + window: window.retain(), + view, + #[cfg(not(feature = "private-apple-apis"))] + blur_view: RefCell::new(None), + blur_material: Cell::new(macos_attrs.blur_material), + previous_position: Cell::new(flip_window_screen_coordinates(window.frame())), + previous_scale_factor: Cell::new(scale_factor), + surface_resize_increments: Cell::new(surface_resize_increments), + decorations: Cell::new(attrs.decorations), + resizable: Cell::new(attrs.resizable), + maximized: Cell::new(attrs.maximized), + save_presentation_opts: Cell::new(None), + initial_fullscreen: Cell::new(attrs.fullscreen.is_some()), + fullscreen: RefCell::new(None), + target_fullscreen: RefCell::new(None), + in_fullscreen_transition: Cell::new(false), + standard_frame: Cell::new(None), + is_simple_fullscreen: Cell::new(false), + saved_style: Cell::new(None), + is_borderless_game: Cell::new(macos_attrs.borderless_game), + window_type, + anchored, + positioner: RefCell::new(attrs.positioner.unwrap_or_default()), + }); + let delegate: Retained = unsafe { msg_send![super(delegate), init] }; + + window.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); + + let drag_types = unsafe { + // Advertize support for the set of types which correspond to variants of `TypeHint`. + // If the user wants to support other pasteboard types which don't have a cross-platform + // equivalent, they can downcast the window and manually call `registerForDraggedTypes` + // themselves. + NSArray::from_slice(&[ + NSPasteboardTypeFileURL, + NSPasteboardTypeHTML, + NSPasteboardTypePNG, + NSPasteboardTypeSound, + NSPasteboardTypeString, + NSPasteboardTypeTIFF, + ]) + }; + window.registerForDraggedTypes(&drag_types); + + // Listen for theme change event. + // + // SAFETY: The observer is un-registered in the `Drop` of the delegate. + unsafe { + window.addObserver_forKeyPath_options_context( + &delegate, + ns_string!("effectiveAppearance"), + NSKeyValueObservingOptions::New | NSKeyValueObservingOptions::Old, + ptr::null_mut(), + ) + }; + + if attrs.blur { + delegate.set_blur(attrs.blur); + } + + if let Some(dim) = attrs.min_surface_size { + delegate.set_min_surface_size(Some(dim)); + } + if let Some(dim) = attrs.max_surface_size { + delegate.set_max_surface_size(Some(dim)); + } + + delegate.set_window_level(attrs.window_level); + + // An anchored window's position is relative to the parent window, and the parent is + // only attached above, so apply the (translated) position now. Default to the parent's + // content top-left when no position was given. + if anchored { + let position = attrs.position.unwrap_or_else(|| LogicalPosition::new(0.0, 0.0).into()); + delegate.set_outer_position(position); + } + + delegate.set_cursor(attrs.cursor); + + // Set fullscreen mode after we setup everything + delegate.set_fullscreen(attrs.fullscreen); + + // Setting the window as key has to happen *after* we set the fullscreen + // state, since otherwise we'll briefly see the window at normal size + // before it transitions. + if attrs.visible { + if attrs.active { + // Tightly linked with `app_state::window_activation_hack` + window.makeKeyAndOrderFront(None); + } else { + window.orderFront(None); + } + } + + if attrs.maximized { + delegate.set_maximized(attrs.maximized); + } + + Ok(delegate) + } + + pub(super) fn view(&self) -> Retained { + self.ivars().view.clone() + } + + #[track_caller] + pub(super) fn window(&self) -> &NSWindow { + &self.ivars().window + } + + #[track_caller] + pub(crate) fn id(&self) -> WindowId { + window_id(self.window()) + } + + pub(crate) fn queue_event(&self, event: WindowEvent) { + let window_id = window_id(self.window()); + self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| { + app.window_event(event_loop, window_id, event); + }); + } + + fn defer_if_handling_event(&self, f: impl FnOnce(Retained) + 'static) -> bool { + // AppKit state transitions such as zoom/fullscreen can synchronously run resize/display + // callbacks. Starting them from inside a winit event callback prevents those callbacks + // from being delivered immediately, so defer the transition to the next run-loop turn. + if !self.ivars().app_state.is_handling_event() { + return false; + } + + let mtm = MainThreadMarker::from(self); + let this = self.retain(); + MainRunLoop::get(mtm).queue_closure(move || f(this)); + true + } + + fn handle_scale_factor_changed(&self, scale_factor: CGFloat) { + let window = self.window(); + + let suggested_size = self.view().surface_size(); + let new_surface_size = Arc::new(Mutex::new(suggested_size)); + self.queue_event(WindowEvent::ScaleFactorChanged { + scale_factor, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)), + }); + let physical_size = *new_surface_size.lock().unwrap(); + drop(new_surface_size); + + if physical_size != suggested_size { + let logical_size = physical_size.to_logical(scale_factor); + let size = NSSize::new(logical_size.width, logical_size.height); + window.setContentSize(size); + } + self.view().surface_resized(); + } + + fn emit_move_event(&self) { + let position = flip_window_screen_coordinates(self.window().frame()); + if self.ivars().previous_position.get() == position { + return; + } + self.ivars().previous_position.set(position); + + let position = + LogicalPosition::new(position.x, position.y).to_physical(self.scale_factor()); + self.queue_event(WindowEvent::Moved(position)); + } + + fn set_style_mask(&self, mask: NSWindowStyleMask) { + self.window().setStyleMask(mask); + // If we don't do this, key handling will break + // (at least until the window is clicked again/etc.) + let _ = self.window().makeFirstResponder(Some(&self.view())); + } + + pub fn set_title(&self, title: &str) { + self.window().setTitle(&NSString::from_str(title)) + } + + pub fn set_transparent(&self, transparent: bool) { + // This is just a hint for Quartz, it doesn't actually speculate with window alpha. + // Providing a wrong value here could result in visual artifacts, when the window is + // transparent. + self.window().setOpaque(!transparent); + + // AppKit draws the window with a background color by default, which is usually really + // nice, but gets in the way when we want to allow the contents of the window to be + // transparent, as in that case, the transparent contents will just be drawn on top of + // the background color. As such, to allow the window to be transparent, we must also set + // the background color to one with an empty alpha channel. + let color = + if transparent { NSColor::clearColor() } else { NSColor::windowBackgroundColor() }; + + self.window().setBackgroundColor(Some(&color)); + } + + pub fn set_blur(&self, blur: bool) { + #[cfg(feature = "private-apple-apis")] + { + #[link(name = "CoreGraphics", kind = "framework")] + unsafe extern "C" { + // Wildly used private APIs; Apple uses them for their Terminal.app. + pub fn CGSMainConnectionID() -> *mut objc2::runtime::AnyObject; + pub fn CGSSetWindowBackgroundBlurRadius( + connection_id: *mut objc2::runtime::AnyObject, + window_id: objc2_foundation::NSInteger, + radius: i64, + ) -> i32; + } + + // NOTE: in general we want to specify the blur radius, but the choice of 80 + // should be a reasonable default. + let radius = if blur { 80 } else { 0 }; + let window_number = self.window().windowNumber(); + unsafe { + CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, radius) + }; + } + + #[cfg(not(feature = "private-apple-apis"))] + { + if !blur { + let installed = self.ivars().blur_view.borrow_mut().take(); + if let Some(installed) = installed { + installed.removeFromSuperview(); + } + return; + } + + if self.ivars().blur_view.borrow().is_some() { + return; + } + + let mtm = MainThreadMarker::from(self); + let view = self.view(); + let content_view = + self.window().contentView().expect("window always has a content view"); + + let new_blur_view = NSVisualEffectView::new(mtm); + new_blur_view.setBlendingMode(NSVisualEffectBlendingMode::BehindWindow); + new_blur_view.setState(NSVisualEffectState::Active); + if let Some(material) = ns_visual_effect_material(self.ivars().blur_material.get()) { + new_blur_view.setMaterial(material); + } + new_blur_view.setFrame(content_view.bounds()); + new_blur_view.setAutoresizingMask( + NSAutoresizingMaskOptions::ViewWidthSizable + | NSAutoresizingMaskOptions::ViewHeightSizable, + ); + content_view.addSubview_positioned_relativeTo( + &new_blur_view, + NSWindowOrderingMode::Below, + Some(&view), + ); + + *self.ivars().blur_view.borrow_mut() = Some(new_blur_view); + } + } + + pub fn set_visible(&self, visible: bool) { + match visible { + true => self.window().makeKeyAndOrderFront(None), + false => self.window().orderOut(None), + } + } + + #[inline] + pub fn is_visible(&self) -> Option { + Some(self.window().isVisible()) + } + + pub fn request_redraw(&self) { + self.ivars().app_state.queue_redraw(window_id(self.window())); + } + + #[inline] + pub fn pre_present_notify(&self) {} + + pub fn outer_position(&self) -> Result, RequestError> { + let position = flip_window_screen_coordinates(self.window().frame()); + let position = self + .translate_anchored_position_to_parent(LogicalPosition::new(position.x, position.y)); + Ok(position.to_physical(self.scale_factor())) + } + + pub fn surface_position(&self) -> PhysicalPosition { + // The calculation here is a bit awkward because we've gotta reconcile the + // different origins (Winit prefers top-left vs. NSWindow's bottom-left), + // and I couldn't find a built-in way to do so. + + // The position of the window and the view, both in Winit screen coordinates. + let window_position = flip_window_screen_coordinates(self.window().frame()); + let view_position = flip_window_screen_coordinates( + self.window().contentRectForFrameRect(self.window().frame()), + ); + + // And use that to convert the view position to window coordinates. + let surface_position = + NSPoint::new(view_position.x - window_position.x, view_position.y - window_position.y); + + let logical = LogicalPosition::new(surface_position.x, surface_position.y); + logical.to_physical(self.scale_factor()) + } + + pub fn set_outer_position(&self, position: Position) { + let position = position.to_logical(self.scale_factor()); + let position = self.translate_anchored_position(position); + let point = flip_window_screen_coordinates(NSRect::new( + NSPoint::new(position.x, position.y), + self.window().frame().size, + )); + self.window().setFrameOrigin(point); + } + + /// Anchored windows receive their position relative to the top-left of the parent window's + /// content area (matching the Win32 and Wayland backends). macOS positions windows + /// in global screen coordinates, so add the parent content area's origin. + fn translate_anchored_position(&self, position: LogicalPosition) -> LogicalPosition { + if !self.ivars().anchored { + return position; + } + let Some(parent) = self.window().parentWindow() else { + return position; + }; + let parent_origin = + flip_window_screen_coordinates(parent.contentRectForFrameRect(parent.frame())); + LogicalPosition::new(parent_origin.x + position.x, parent_origin.y + position.y) + } + + /// Inverse of [`Self::translate_anchored_position`]. Anchored windows report their position + /// relative to the top-left of the parent window's content area (matching the + /// Win32 and Wayland backends), so subtract the parent content area's origin from + /// the global screen coordinates. Non-anchored windows are returned unchanged. + fn translate_anchored_position_to_parent( + &self, + position: LogicalPosition, + ) -> LogicalPosition { + if !self.ivars().anchored { + return position; + } + let Some(parent) = self.window().parentWindow() else { + return position; + }; + let parent_origin = + flip_window_screen_coordinates(parent.contentRectForFrameRect(parent.frame())); + LogicalPosition::new(position.x - parent_origin.x, position.y - parent_origin.y) + } + + /// The parent window's content area origin, in global (Winit, top-left/y-down) screen + /// coordinates. `None` if this window isn't anchored, or it has no parent. + pub fn parent_content_origin(&self) -> Option> { + if !self.ivars().anchored { + return None; + } + let parent = self.window().parentWindow()?; + let origin = flip_window_screen_coordinates(parent.contentRectForFrameRect(parent.frame())); + Some(LogicalPosition::new(origin.x, origin.y)) + } + + pub fn window_type(&self) -> WindowType { + self.ivars().window_type + } + + pub fn popup_positioner(&self) -> WindowPositioner { + *self.ivars().positioner.borrow() + } + + pub fn set_popup_positioner(&self, positioner: WindowPositioner) { + *self.ivars().positioner.borrow_mut() = positioner; + self.reposition(); + } + + /// Recomputes this window's position (and, if constrained, its size) from its positioner + /// state, using [`winit_common::positioner::place_window`], and applies the result. No-op if + /// this window isn't anchored. If it has no parent, the positioner is resolved relative to + /// the screen instead of the parent's content area. + pub(crate) fn reposition(&self) { + if !self.ivars().anchored { + return; + } + + let positioner = *self.ivars().positioner.borrow(); + + let parent_origin = self.parent_content_origin().unwrap_or_default(); + + let Some(monitor) = self.current_monitor() else { return }; + // Clip to the monitor's work area rather than its full bounds, so anchored popups don't + // get placed underneath the menu bar or the Dock. + let Some((work_area_position, work_area_size)) = monitor.work_area() else { return }; + + let scale_factor = self.scale_factor(); + + // The anchor rect's position is relative to the parent's content area, and + // `set_outer_position` re-adds the parent's screen origin for anchored windows (see + // `translate_anchored_position`). To stay in the same coordinate space, the clip region + // also needs to be expressed relative to the parent's content area. + let work_area_position = work_area_position.to_logical::(scale_factor); + let clip_position = LogicalPosition::new( + work_area_position.x - parent_origin.x, + work_area_position.y - parent_origin.y, + ); + let clip_size = work_area_size.to_logical::(scale_factor); + + let current_outer_size = self.outer_size().to_logical::(scale_factor); + + let (origin, new_outer_size) = + place_window(&positioner, scale_factor, current_outer_size, (clip_position, clip_size)); + + self.set_outer_position(Position::Logical(origin)); + if new_outer_size != current_outer_size { + // `place_window` positions the window by its outer/frame corner, so it operates on + // the outer size; convert back to the surface (content) size that + // `request_surface_size` expects, via AppKit's frame/content rect conversion. + let frame = NSRect::new( + NSPoint::new(0.0, 0.0), + NSSize::new(new_outer_size.width, new_outer_size.height), + ); + let content_size = self.window().contentRectForFrameRect(frame).size; + let content_size = LogicalSize::new(content_size.width, content_size.height); + let _ = self.request_surface_size(Size::Logical(content_size)); + } + } + + /// Repositions any anchored children owned by this window. AppKit's `addChildWindow:ordered:` + /// only manages ordering and visibility for child windows -- it doesn't keep their position + /// in sync with the parent -- so this has to be done manually whenever this window moves. + fn reposition_child_windows(&self) { + let Some(children) = self.window().childWindows() else { return }; + for child in children.iter() { + let Some(child_delegate) = child.delegate() else { continue }; + let Ok(child_delegate) = child_delegate.downcast::() else { continue }; + if child_delegate.ivars().anchored { + child_delegate.reposition(); + } + } + } + + #[inline] + pub fn surface_size(&self) -> PhysicalSize { + self.view().surface_size() + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize { + let frame = self.window().frame(); + let logical = LogicalSize::new(frame.size.width, frame.size.height); + logical.to_physical(self.scale_factor()) + } + + pub fn safe_area(&self) -> PhysicalInsets { + // Only available on macOS 11.0 + let insets = if self.view().respondsToSelector(sel!(safeAreaInsets)) { + // Includes NSWindowStyleMask::FullSizeContentView by default, and the notch because + // we've set it up with `additionalSafeAreaInsets`. + self.view().safeAreaInsets() + } else { + // If `safeAreaInsets` is not available, we'll have to do the calculation ourselves. + + let window_rect = self.window().convertRectFromScreen( + self.window().contentRectForFrameRect(self.window().frame()), + ); + // This includes NSWindowStyleMask::FullSizeContentView. + let layout_rect = self.window().contentLayoutRect(); + + // Calculate the insets from window coordinates in AppKit's coordinate system. + NSEdgeInsets { + top: (window_rect.size.height + window_rect.origin.y) + - (layout_rect.size.height + layout_rect.origin.y), + left: layout_rect.origin.x - window_rect.origin.x, + bottom: layout_rect.origin.y - window_rect.origin.y, + right: (window_rect.size.width + window_rect.origin.x) + - (layout_rect.size.width + layout_rect.origin.x), + } + }; + let insets = LogicalInsets::new(insets.top, insets.left, insets.bottom, insets.right); + insets.to_physical(self.scale_factor()) + } + + #[inline] + pub fn request_surface_size(&self, size: Size) -> Option> { + let scale_factor = self.scale_factor(); + let size = size.to_logical(scale_factor); + self.window().setContentSize(NSSize::new(size.width, size.height)); + None + } + + pub fn set_min_surface_size(&self, dimensions: Option) { + let dimensions = + dimensions.unwrap_or(Size::Logical(LogicalSize { width: 0.0, height: 0.0 })); + let min_size = dimensions.to_logical::(self.scale_factor()); + + let min_size = NSSize::new(min_size.width, min_size.height); + self.window().setContentMinSize(min_size); + + // If necessary, resize the window to match constraint + let mut current_size = self.window().contentRectForFrameRect(self.window().frame()).size; + if current_size.width < min_size.width { + current_size.width = min_size.width; + } + if current_size.height < min_size.height { + current_size.height = min_size.height; + } + self.window().setContentSize(current_size); + } + + pub fn set_max_surface_size(&self, dimensions: Option) { + let dimensions = dimensions.unwrap_or(Size::Logical(LogicalSize { + width: f32::MAX as f64, + height: f32::MAX as f64, + })); + let scale_factor = self.scale_factor(); + let max_size = dimensions.to_logical::(scale_factor); + + let max_size = NSSize::new(max_size.width, max_size.height); + self.window().setContentMaxSize(max_size); + + // If necessary, resize the window to match constraint + let mut current_size = self.window().contentRectForFrameRect(self.window().frame()).size; + if max_size.width < current_size.width { + current_size.width = max_size.width; + } + if max_size.height < current_size.height { + current_size.height = max_size.height; + } + self.window().setContentSize(current_size); + } + + pub fn surface_resize_increments(&self) -> Option> { + let increments = self.ivars().surface_resize_increments.get(); + let (w, h) = (increments.width, increments.height); + if w > 1.0 || h > 1.0 { + Some(LogicalSize::new(w, h).to_physical(self.scale_factor())) + } else { + None + } + } + + pub fn set_surface_resize_increments(&self, increments: Option) { + // XXX the resize increments are only used during live resizes. + self.ivars().surface_resize_increments.set( + increments + .map(|increments| { + let logical = increments.to_logical::(self.scale_factor()); + NSSize::new(logical.width.max(1.0), logical.height.max(1.0)) + }) + .unwrap_or_else(|| NSSize::new(1.0, 1.0)), + ); + } + + pub(crate) fn set_resize_increments_inner(&self, size: NSSize) { + // It was concluded (#2411) that there is never a use-case for + // "outer" resize increments, hence we set "inner" ones here. + // ("outer" in macOS being just resizeIncrements, and "inner" - contentResizeIncrements) + // This is consistent with X11 size hints behavior + self.window().setContentResizeIncrements(size); + } + + #[inline] + pub fn set_resizable(&self, resizable: bool) { + self.ivars().resizable.set(resizable); + let fullscreen = self.ivars().fullscreen.borrow().is_some(); + if !fullscreen { + let mut mask = self.window().styleMask(); + if resizable { + mask |= NSWindowStyleMask::Resizable; + } else { + mask &= !NSWindowStyleMask::Resizable; + } + self.set_style_mask(mask); + } + // Otherwise, we don't change the mask until we exit fullscreen. + } + + #[inline] + pub fn is_resizable(&self) -> bool { + self.window().isResizable() + } + + #[inline] + pub fn set_enabled_buttons(&self, buttons: WindowButtons) { + let mut mask = self.window().styleMask(); + + if buttons.contains(WindowButtons::CLOSE) { + mask |= NSWindowStyleMask::Closable; + } else { + mask &= !NSWindowStyleMask::Closable; + } + + if buttons.contains(WindowButtons::MINIMIZE) { + mask |= NSWindowStyleMask::Miniaturizable; + } else { + mask &= !NSWindowStyleMask::Miniaturizable; + } + + // This must happen before the button's "enabled" status has been set, + // hence we do it synchronously. + self.set_style_mask(mask); + + // We edit the button directly instead of using `NSResizableWindowMask`, + // since that mask also affect the resizability of the window (which is + // controllable by other means in `winit`). + if let Some(button) = self.window().standardWindowButton(NSWindowButton::ZoomButton) { + button.setEnabled(buttons.contains(WindowButtons::MAXIMIZE)); + } + } + + #[inline] + pub fn enabled_buttons(&self) -> WindowButtons { + let mut buttons = WindowButtons::empty(); + if self.window().isMiniaturizable() { + buttons |= WindowButtons::MINIMIZE; + } + if self + .window() + .standardWindowButton(NSWindowButton::ZoomButton) + .map(|b| b.isEnabled()) + .unwrap_or(true) + { + buttons |= WindowButtons::MAXIMIZE; + } + if self.window().hasCloseBox() { + buttons |= WindowButtons::CLOSE; + } + buttons + } + + pub fn set_cursor(&self, cursor: Cursor) { + let view = self.view(); + + let cursor = match cursor { + Cursor::Icon(icon) => cursor_from_icon(icon), + Cursor::Custom(cursor) => match cursor.cast_ref::() { + Some(cursor) => cursor.0.clone(), + None => { + tracing::error!("unrecognized cursor passed to macOS backend"); + return; + }, + }, + }; + + if view.cursor_icon() == cursor { + return; + } + + view.set_cursor_icon(cursor); + self.window().invalidateCursorRectsForView(&view); + } + + #[inline] + pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> { + let associate_mouse_cursor = match mode { + CursorGrabMode::Locked => false, + CursorGrabMode::None => true, + CursorGrabMode::Confined => { + return Err(NotSupportedError::new("confined cursor is not supported").into()); + }, + }; + + // TODO: Do this for real https://stackoverflow.com/a/40922095/5435443 + cgerr(CGAssociateMouseAndMouseCursorPosition(associate_mouse_cursor))?; + + Ok(()) + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + let view = self.view(); + let state_changed = view.set_cursor_visible(visible); + if state_changed { + self.window().invalidateCursorRectsForView(&view); + } + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + self.window().backingScaleFactor() as _ + } + + #[inline] + pub fn set_cursor_position(&self, cursor_position: Position) -> Result<(), RequestError> { + let content_rect = self.window().contentRectForFrameRect(self.window().frame()); + let window_position = flip_window_screen_coordinates(content_rect); + let cursor_position = cursor_position.to_logical::(self.scale_factor()); + let point = CGPoint { + x: window_position.x + cursor_position.x, + y: window_position.y + cursor_position.y, + }; + cgerr(CGWarpMouseCursorPosition(point))?; + cgerr(CGAssociateMouseAndMouseCursorPosition(true))?; + + Ok(()) + } + + #[inline] + pub fn drag_window(&self) -> Result<(), RequestError> { + let mtm = MainThreadMarker::from(self); + let event = + NSApplication::sharedApplication(mtm).currentEvent().ok_or(RequestError::Ignored)?; + self.window().performWindowDragWithEvent(&event); + Ok(()) + } + + #[inline] + pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), NotSupportedError> { + Err(NotSupportedError::new("drag_resize_window is not supported")) + } + + #[inline] + pub fn show_window_menu(&self, _position: Position) {} + + #[inline] + pub fn set_cursor_hittest(&self, hittest: bool) { + self.window().setIgnoresMouseEvents(!hittest); + } + + pub(crate) fn is_zoomed(&self) -> bool { + // because `isZoomed` doesn't work if the window's borderless, + // we make it resizable temporarily. + let curr_mask = self.window().styleMask(); + + let required = NSWindowStyleMask::Titled | NSWindowStyleMask::Resizable; + let needs_temp_mask = !curr_mask.contains(required); + if needs_temp_mask { + self.set_style_mask(required); + } + + let is_zoomed = self.window().isZoomed(); + + // Roll back temp styles + if needs_temp_mask { + self.set_style_mask(curr_mask); + } + + is_zoomed + } + + fn saved_style(&self) -> NSWindowStyleMask { + let base_mask = + self.ivars().saved_style.take().unwrap_or_else(|| self.window().styleMask()); + if self.ivars().resizable.get() { + base_mask | NSWindowStyleMask::Resizable + } else { + base_mask & !NSWindowStyleMask::Resizable + } + } + + /// This is called when the window is exiting fullscreen, whether by the + /// user clicking on the green fullscreen button or programmatically by + /// `toggleFullScreen:` + pub(crate) fn restore_state_from_fullscreen(&self) { + self.ivars().fullscreen.replace(None); + + let maximized = self.ivars().maximized.get(); + let mask = self.saved_style(); + + self.set_style_mask(mask); + self.set_maximized(maximized); + } + + #[inline] + pub fn set_minimized(&self, minimized: bool) { + let is_minimized = self.window().isMiniaturized(); + if is_minimized == minimized { + return; + } + + if minimized { + self.window().miniaturize(Some(self)); + } else { + self.window().deminiaturize(Some(self)); + } + } + + #[inline] + pub fn is_minimized(&self) -> Option { + Some(self.window().isMiniaturized()) + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + if self.defer_if_handling_event(move |this| this.set_maximized(maximized)) { + return; + } + + let mtm = MainThreadMarker::from(self); + let is_zoomed = self.is_zoomed(); + if is_zoomed == maximized { + return; + }; + + // Save the standard frame sized if it is not zoomed + if !is_zoomed { + self.ivars().standard_frame.set(Some(self.window().frame())); + } + + self.ivars().maximized.set(maximized); + + if self.ivars().fullscreen.borrow().is_some() { + // Handle it in window_did_exit_fullscreen + return; + } + + if self.window().styleMask().contains(NSWindowStyleMask::Resizable) { + // Just use the native zoom if resizable + self.window().zoom(None); + } else { + // if it's not resizable, we set the frame directly + let new_rect = if maximized { + let screen = NSScreen::mainScreen(mtm).expect("no screen found"); + screen.visibleFrame() + } else { + self.ivars().standard_frame.get().unwrap_or(DEFAULT_STANDARD_FRAME) + }; + self.window().setFrame_display(new_rect, false); + } + } + + #[inline] + pub(crate) fn fullscreen(&self) -> Option { + self.ivars().fullscreen.borrow().clone() + } + + #[inline] + pub fn is_maximized(&self) -> bool { + self.is_zoomed() + } + + #[inline] + pub(crate) fn set_fullscreen(&self, fullscreen: Option) { + if self.ivars().is_simple_fullscreen.get() { + return; + } + if fullscreen.is_some() + && self + .window() + .collectionBehavior() + .contains(NSWindowCollectionBehavior::FullScreenAuxiliary) + { + // `toggleFullScreen:` is silently ignored on such windows, which would leave our + // internal fullscreen state out of sync, so bail out early instead. + warn!( + "cannot fullscreen a window marked as fullscreen auxiliary; call \ + `set_fullscreen_auxiliary(false)` first" + ); + return; + } + if self.ivars().in_fullscreen_transition.get() { + // We can't set fullscreen here. + // Set fullscreen after transition. + self.ivars().target_fullscreen.replace(Some(fullscreen)); + return; + } + let old_fullscreen = self.ivars().fullscreen.borrow().clone(); + if fullscreen == old_fullscreen { + return; + } + + if !self.ivars().initial_fullscreen.get() + && self.defer_if_handling_event({ + let fullscreen = fullscreen.clone(); + move |this| this.set_fullscreen(fullscreen) + }) + { + return; + } + + let mtm = MainThreadMarker::from(self); + let app = NSApplication::sharedApplication(mtm); + + // If the fullscreen is on a different monitor, we must move the window + // to that monitor before we toggle fullscreen (as `toggleFullScreen` + // does not take a screen parameter, but uses the current screen) + if let Some(ref fullscreen) = fullscreen { + let new_screen = match fullscreen { + Fullscreen::Borderless(Some(monitor)) | Fullscreen::Exclusive(monitor, _) => { + let monitor = monitor.cast_ref::().unwrap(); + monitor.ns_screen(mtm) + }, + _ => { + if let Some(monitor) = self.current_monitor_inner() { + monitor.ns_screen(mtm) + } else { + return; + } + }, + } + .unwrap(); + + let old_screen = self.window().screen().unwrap(); + if old_screen != new_screen { + self.window().setFrameOrigin(new_screen.frame().origin); + } + } + + if let Some(Fullscreen::Exclusive(ref monitor, ref video_mode)) = fullscreen { + // Note: `enterFullScreenMode:withOptions:` seems to do the exact + // same thing as we're doing here (captures the display, sets the + // video mode, and hides the menu bar and dock), with the exception + // of that I couldn't figure out how to set the display mode with + // it. I think `enterFullScreenMode:withOptions:` is still using the + // older display mode API where display modes were of the type + // `CFDictionary`, but this has changed, so we can't obtain the + // correct parameter for this any longer. Apple's code samples for + // this function seem to just pass in "YES" for the display mode + // parameter, which is not consistent with the docs saying that it + // takes a `NSDictionary`.. + + let display_id = monitor.native_id() as _; + + let mut fade_token = kCGDisplayFadeReservationInvalidToken; + + if matches!(old_fullscreen, Some(Fullscreen::Borderless(_))) { + self.ivars().save_presentation_opts.replace(Some(app.presentationOptions())); + } + + // Fade to black (and wait for the fade to complete) to hide the + // flicker from capturing the display and switching display mode + if cgerr(unsafe { CGAcquireDisplayFadeReservation(5.0, &mut fade_token) }).is_ok() { + CGDisplayFade( + fade_token, + 0.3, + kCGDisplayBlendNormal, + kCGDisplayBlendSolidColor, + 0.0, + 0.0, + 0.0, + true, + ); + } + + cgerr(CGDisplayCapture(display_id)).unwrap(); + + let monitor = monitor.cast_ref::().unwrap(); + let video_mode = + match monitor.video_mode_handles().find(|mode| &mode.mode == video_mode) { + Some(video_mode) => video_mode, + None => return, + }; + + cgerr(unsafe { + CGDisplaySetDisplayMode(display_id, Some(&video_mode.native_mode.0), None) + }) + .expect("failed to set video mode"); + + // After the display has been configured, fade back in + // asynchronously + if fade_token != kCGDisplayFadeReservationInvalidToken { + CGDisplayFade( + fade_token, + 0.6, + kCGDisplayBlendSolidColor, + kCGDisplayBlendNormal, + 0.0, + 0.0, + 0.0, + false, + ); + CGReleaseDisplayFadeReservation(fade_token); + } + } + + self.ivars().fullscreen.replace(fullscreen.clone()); + + fn toggle_fullscreen(window: &NSWindow) { + // Window level must be restored from `CGShieldingWindowLevel() + // + 1` back to normal in order for `toggleFullScreen` to do + // anything + window.setLevel(kCGNormalWindowLevel as NSWindowLevel); + window.toggleFullScreen(None); + } + + match (old_fullscreen, fullscreen) { + (None, Some(_)) => { + // `toggleFullScreen` doesn't work if the `StyleMask` is none, so we + // set a normal style temporarily. The previous state will be + // restored in `WindowDelegate::window_did_exit_fullscreen`. + let curr_mask = self.window().styleMask(); + let required = NSWindowStyleMask::Titled | NSWindowStyleMask::Resizable; + if !curr_mask.contains(required) { + self.set_style_mask(required); + self.ivars().saved_style.set(Some(curr_mask)); + } + + toggle_fullscreen(self.window()); + }, + (Some(Fullscreen::Borderless(_)), None) => { + // State is restored by `window_did_exit_fullscreen` + toggle_fullscreen(self.window()); + }, + (Some(Fullscreen::Exclusive(monitor, _)), None) => { + let monitor = monitor.cast_ref::().unwrap(); + restore_and_release_display(monitor); + toggle_fullscreen(self.window()); + }, + (Some(Fullscreen::Borderless(_)), Some(Fullscreen::Exclusive(..))) => { + // If we're already in fullscreen mode, calling + // `CGDisplayCapture` will place the shielding window on top of + // our window, which results in a black display and is not what + // we want. So, we must place our window on top of the shielding + // window. Unfortunately, this also makes our window be on top + // of the menu bar, and this looks broken, so we must make sure + // that the menu bar is disabled. This is done in the window + // delegate in `window:willUseFullScreenPresentationOptions:`. + self.ivars().save_presentation_opts.set(Some(app.presentationOptions())); + + let presentation_options = NSApplicationPresentationOptions::FullScreen + | NSApplicationPresentationOptions::HideDock + | NSApplicationPresentationOptions::HideMenuBar; + app.setPresentationOptions(presentation_options); + + let window_level = CGShieldingWindowLevel() as NSWindowLevel + 1; + self.window().setLevel(window_level); + }, + (Some(Fullscreen::Exclusive(monitor, _)), Some(Fullscreen::Borderless(_))) => { + let presentation_options = self.ivars().save_presentation_opts.get().unwrap_or( + NSApplicationPresentationOptions::FullScreen + | NSApplicationPresentationOptions::AutoHideDock + | NSApplicationPresentationOptions::AutoHideMenuBar, + ); + app.setPresentationOptions(presentation_options); + + let monitor = monitor.cast_ref::().unwrap(); + restore_and_release_display(monitor); + + // Restore the normal window level following the Borderless fullscreen + // `CGShieldingWindowLevel() + 1` hack. + self.window().setLevel(kCGNormalWindowLevel as NSWindowLevel); + }, + _ => {}, + }; + } + + #[inline] + pub fn set_decorations(&self, decorations: bool) { + if decorations == self.ivars().decorations.get() { + return; + } + + self.ivars().decorations.set(decorations); + + let fullscreen = self.ivars().fullscreen.borrow().is_some(); + let resizable = self.ivars().resizable.get(); + + // If we're in fullscreen mode, we wait to apply decoration changes + // until we're in `window_did_exit_fullscreen`. + if fullscreen { + return; + } + + let new_mask = { + let mut new_mask = if decorations { + NSWindowStyleMask::Closable + | NSWindowStyleMask::Miniaturizable + | NSWindowStyleMask::Resizable + | NSWindowStyleMask::Titled + } else { + NSWindowStyleMask::Borderless | NSWindowStyleMask::Resizable + }; + if !resizable { + new_mask &= !NSWindowStyleMask::Resizable; + } + new_mask + }; + self.set_style_mask(new_mask); + } + + #[inline] + pub fn is_decorated(&self) -> bool { + self.ivars().decorations.get() + } + + #[inline] + pub fn set_window_level(&self, level: WindowLevel) { + // Note: There are two different things at play here: + // `CGWindowLevel` and `CGWindowLevelKey`. + // + // It seems like there was a push towards using "key" values instead of the + // raw window level values, and then you were supposed to use + // `CGWindowLevelForKey` to get the actual level. + // + // But the values that `NSWindowLevel` has are compiled in, and as such has + // to remain ABI compatible, so they're safe for us to hardcode as well. + let level = match level { + WindowLevel::AlwaysOnTop => kCGFloatingWindowLevel as NSWindowLevel, + WindowLevel::AlwaysOnBottom => (kCGNormalWindowLevel - 1) as NSWindowLevel, + WindowLevel::Normal => kCGNormalWindowLevel as NSWindowLevel, + }; + self.window().setLevel(level); + } + + #[inline] + pub fn set_window_icon(&self, _icon: Option) { + // macOS doesn't have window icons. Though, there is + // `setRepresentedFilename`, but that's semantically distinct and should + // only be used when the window is in some way representing a specific + // file/directory. For instance, Terminal.app uses this for the CWD. + // Anyway, that should eventually be implemented as + // `WindowAttributesExt::with_represented_file` or something, and doesn't + // have anything to do with `set_window_icon`. + // https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/WinPanel/Tasks/SettingWindowTitle.html + } + + pub fn request_ime_update(&self, request: ImeRequest) -> Result<(), ImeRequestError> { + let current_caps = self.view().ime_capabilities(); + let request_data = match request { + ImeRequest::Enable(enable) => { + let (capabilities, request_data) = enable.into_raw(); + if current_caps.is_some() { + return Err(ImeRequestError::AlreadyEnabled); + } + self.view().enable_ime(capabilities); + request_data + }, + ImeRequest::Update(request_data) => { + if current_caps.is_none() { + return Err(ImeRequestError::NotEnabled); + } + request_data + }, + ImeRequest::Disable => { + self.view().disable_ime(); + return Ok(()); + }, + _ => return Err(ImeRequestError::NotSupported), + }; + + // leaf patch: keep the text around the caret for the text input + // client's queries (see `WinitView::selected_range`). + if self.view().ime_capabilities().unwrap().surrounding_text() { + if let Some(text) = request_data.surrounding_text.clone() { + self.view().set_ime_surrounding_text(Some(text)); + } + } + + if let Some((spot, size)) = request_data.cursor_area { + if self.view().ime_capabilities().unwrap().cursor_area() { + let scale_factor = self.scale_factor(); + let logical_spot = spot.to_logical(scale_factor); + let logical_spot = NSPoint::new(logical_spot.x, logical_spot.y); + + let size = size.to_logical(scale_factor); + let size = NSSize::new(size.width, size.height); + self.view().set_ime_cursor_area(logical_spot, size); + } else { + warn!("discarding IME cursor area update without capability enabled."); + } + } + + Ok(()) + } + + pub fn ime_capabilities(&self) -> Option { + self.view().ime_capabilities() + } + + #[inline] + pub fn focus_window(&self) { + let mtm = MainThreadMarker::from(self); + let is_minimized = self.window().isMiniaturized(); + let is_visible = self.window().isVisible(); + + if !is_minimized && is_visible { + #[allow(deprecated)] + NSApplication::sharedApplication(mtm).activateIgnoringOtherApps(true); + self.window().makeKeyAndOrderFront(None); + } + } + + #[inline] + pub fn request_user_attention(&self, request_type: Option) { + let mtm = MainThreadMarker::from(self); + let ns_request_type = request_type.map(|ty| match ty { + UserAttentionType::Critical => NSRequestUserAttentionType::CriticalRequest, + UserAttentionType::Informational => NSRequestUserAttentionType::InformationalRequest, + }); + if let Some(ty) = ns_request_type { + NSApplication::sharedApplication(mtm).requestUserAttention(ty); + } + } + + #[inline] + // Allow directly accessing the current monitor internally without unwrapping. + pub(crate) fn current_monitor_inner(&self) -> Option { + let display_id = get_display_id(&*self.window().screen()?); + if let Some(monitor) = MonitorHandle::new(display_id) { + Some(monitor) + } else { + // NOTE: Display ID was just fetched from live NSScreen, but can still result in `None` + // with certain Thunderbolt docked monitors. + warn!(display_id, "got screen with invalid display ID"); + None + } + } + + #[inline] + pub fn current_monitor(&self) -> Option { + self.current_monitor_inner() + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque { + monitor::available_monitors() + } + + #[inline] + pub fn primary_monitor(&self) -> Option { + let monitor = monitor::primary_monitor(); + Some(monitor) + } + + #[inline] + pub fn raw_window_handle_rwh_06(&self) -> rwh_06::RawWindowHandle { + let window_handle = rwh_06::AppKitWindowHandle::new({ + let ptr = Retained::as_ptr(&self.view()) as *mut _; + std::ptr::NonNull::new(ptr).expect("Retained should never be null") + }); + rwh_06::RawWindowHandle::AppKit(window_handle) + } + + fn toggle_style_mask(&self, mask: NSWindowStyleMask, on: bool) { + let current_style_mask = self.window().styleMask(); + if on { + self.set_style_mask(current_style_mask | mask); + } else { + self.set_style_mask(current_style_mask & !mask); + } + } + + #[inline] + pub fn has_focus(&self) -> bool { + self.window().isKeyWindow() + } + + pub fn theme(&self) -> Option { + self.window().appearance().map(|appearance| appearance_to_theme(&appearance)).or_else( + || { + let mtm = MainThreadMarker::from(self); + let app = NSApplication::sharedApplication(mtm); + + if available!(macos = 10.14) { + Some(super::window_delegate::appearance_to_theme(&app.effectiveAppearance())) + } else { + Some(Theme::Light) + } + }, + ) + } + + pub fn set_theme(&self, theme: Option) { + self.window().setAppearance(theme_to_appearance(theme).as_deref()); + } + + #[inline] + pub fn set_content_protected(&self, protected: bool) { + self.window().setSharingType(if protected { + NSWindowSharingType::None + } else { + NSWindowSharingType::ReadOnly + }) + } + + pub fn title(&self) -> String { + self.window().title().to_string() + } + + pub fn reset_dead_keys(&self) { + // (Artur) I couldn't find a way to implement this. + } +} + +fn restore_and_release_display(monitor: &MonitorHandle) { + let available_monitors = monitor::available_monitors(); + if available_monitors.contains(monitor) { + CGRestorePermanentDisplayConfiguration(); + cgerr(CGDisplayRelease(monitor.native_id() as _)).unwrap(); + } else { + warn!( + monitor = monitor.name().map(|name| name.to_string()), + "Tried to restore exclusive fullscreen on a monitor that is no longer available" + ); + } +} + +#[cfg(not(feature = "private-apple-apis"))] +fn ns_visual_effect_material(material: BlurMaterial) -> Option { + match material { + BlurMaterial::Titlebar => Some(NSVisualEffectMaterial::Titlebar), + BlurMaterial::Selection => Some(NSVisualEffectMaterial::Selection), + BlurMaterial::Menu => available!(macos = 10.11).then_some(NSVisualEffectMaterial::Menu), + BlurMaterial::Popover => { + available!(macos = 10.11).then_some(NSVisualEffectMaterial::Popover) + }, + BlurMaterial::Sidebar => { + available!(macos = 10.11).then_some(NSVisualEffectMaterial::Sidebar) + }, + BlurMaterial::HeaderView => { + available!(macos = 10.14).then_some(NSVisualEffectMaterial::HeaderView) + }, + BlurMaterial::FullScreenUI => { + available!(macos = 10.14).then_some(NSVisualEffectMaterial::FullScreenUI) + }, + BlurMaterial::HudWindow => { + available!(macos = 10.14).then_some(NSVisualEffectMaterial::HUDWindow) + }, + BlurMaterial::ToolTip => { + available!(macos = 10.14).then_some(NSVisualEffectMaterial::ToolTip) + }, + BlurMaterial::UnderWindowBackground => { + available!(macos = 10.14).then_some(NSVisualEffectMaterial::UnderWindowBackground) + }, + } +} + +impl WindowExtMacOS for WindowDelegate { + #[inline] + fn simple_fullscreen(&self) -> bool { + self.ivars().is_simple_fullscreen.get() + } + + #[inline] + fn set_simple_fullscreen(&self, fullscreen: bool) -> bool { + let mtm = MainThreadMarker::from(self); + + let app = NSApplication::sharedApplication(mtm); + let is_native_fullscreen = self.ivars().fullscreen.borrow().is_some(); + let is_simple_fullscreen = self.ivars().is_simple_fullscreen.get(); + + // Do nothing if native fullscreen is active. + if is_native_fullscreen + || (fullscreen && is_simple_fullscreen) + || (!fullscreen && !is_simple_fullscreen) + { + return false; + } + + if fullscreen { + // Remember the original window's settings + // Exclude title bar + self.ivars() + .standard_frame + .set(Some(self.window().contentRectForFrameRect(self.window().frame()))); + self.ivars().saved_style.set(Some(self.window().styleMask())); + self.ivars().save_presentation_opts.set(Some(app.presentationOptions())); + + // Tell our window's state that we're in fullscreen + self.ivars().is_simple_fullscreen.set(true); + + // Simulate pre-Lion fullscreen by hiding the dock and menu bar + let presentation_options = if self.is_borderless_game() { + NSApplicationPresentationOptions::HideDock + | NSApplicationPresentationOptions::HideMenuBar + } else { + NSApplicationPresentationOptions::AutoHideDock + | NSApplicationPresentationOptions::AutoHideMenuBar + }; + app.setPresentationOptions(presentation_options); + + // Hide the titlebar + self.toggle_style_mask(NSWindowStyleMask::Titled, false); + + // Set the window frame to the screen frame size + let screen = self.window().screen().expect("expected screen to be available"); + self.window().setFrame_display(screen.frame(), true); + + // Configure the safe area rectangle, to ensure that we don't obscure the notch. + if NSScreen::class().responds_to(sel!(safeAreaInsets)) { + self.view().setAdditionalSafeAreaInsets(screen.safeAreaInsets()); + } + + // Fullscreen windows can't be resized, minimized, or moved + self.toggle_style_mask(NSWindowStyleMask::Miniaturizable, false); + self.toggle_style_mask(NSWindowStyleMask::Resizable, false); + self.window().setMovable(false); + } else { + let new_mask = self.saved_style(); + self.ivars().is_simple_fullscreen.set(false); + + let save_presentation_opts = self.ivars().save_presentation_opts.get(); + let frame = self.ivars().standard_frame.get().unwrap_or(DEFAULT_STANDARD_FRAME); + + if let Some(presentation_opts) = save_presentation_opts { + app.setPresentationOptions(presentation_opts); + } + + if NSScreen::class().responds_to(sel!(safeAreaInsets)) { + self.view().setAdditionalSafeAreaInsets(NSEdgeInsets { + top: 0.0, + left: 0.0, + bottom: 0.0, + right: 0.0, + }); + } + + self.window().setFrame_display(frame, true); + self.window().setMovable(true); + self.set_style_mask(new_mask); + } + + true + } + + #[inline] + fn has_shadow(&self) -> bool { + self.window().hasShadow() + } + + #[inline] + fn set_has_shadow(&self, has_shadow: bool) { + self.window().setHasShadow(has_shadow) + } + + #[inline] + fn set_tabbing_identifier(&self, identifier: &str) { + self.window().setTabbingIdentifier(&NSString::from_str(identifier)) + } + + #[inline] + fn tabbing_identifier(&self) -> String { + self.window().tabbingIdentifier().to_string() + } + + #[inline] + fn select_next_tab(&self) { + self.window().selectNextTab(None) + } + + #[inline] + fn select_previous_tab(&self) { + self.window().selectPreviousTab(None) + } + + #[inline] + fn select_tab_at_index(&self, index: usize) { + if !available!(macos = 10.13) { + tracing::warn!("window tab groups are only available on macOS 10.13+"); + return; + } + if let Some(group) = self.window().tabGroup() { + if let Some(windows) = self.window().tabbedWindows() { + if index < windows.len() { + group.setSelectedWindow(Some(&windows.objectAtIndex(index))); + } + } + } + } + + #[inline] + fn num_tabs(&self) -> usize { + self.window().tabbedWindows().map(|windows| windows.len()).unwrap_or(1) + } + + fn is_document_edited(&self) -> bool { + self.window().isDocumentEdited() + } + + fn set_document_edited(&self, edited: bool) { + self.window().setDocumentEdited(edited) + } + + fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) { + self.view().set_option_as_alt(option_as_alt); + } + + fn set_blur_material(&self, blur_material: BlurMaterial) { + self.ivars().blur_material.set(blur_material); + + #[cfg(not(feature = "private-apple-apis"))] + if let Some(blur_view) = self.ivars().blur_view.borrow().as_ref() { + if let Some(material) = ns_visual_effect_material(blur_material) { + blur_view.setMaterial(material); + } + } + } + + fn blur_material(&self) -> BlurMaterial { + self.ivars().blur_material.get() + } + + fn option_as_alt(&self) -> OptionAsAlt { + self.view().option_as_alt() + } + + fn set_borderless_game(&self, borderless_game: bool) { + self.ivars().is_borderless_game.set(borderless_game); + } + + fn is_borderless_game(&self) -> bool { + self.ivars().is_borderless_game.get() + } + + fn set_unified_titlebar(&self, unified_titlebar: bool) { + let window = self.window(); + + if unified_titlebar { + let mtm = MainThreadMarker::from(self); + + // The toolbar style is ignored if there is no toolbar, so it is + // necessary to add one. + window.setToolbar(Some(&NSToolbar::new(mtm))); + window.setToolbarStyle(NSWindowToolbarStyle::Unified); + } else { + window.setToolbar(None); + window.setToolbarStyle(NSWindowToolbarStyle::Automatic); + } + } + + fn unified_titlebar(&self) -> bool { + let window = self.window(); + + window.toolbar().is_some() && window.toolbarStyle() == NSWindowToolbarStyle::Unified + } + + #[inline] + fn set_fullscreen_auxiliary(&self, fullscreen_auxiliary: bool) { + let window = self.window(); + let behavior = window.collectionBehavior(); + if fullscreen_auxiliary { + window + .setCollectionBehavior(behavior | NSWindowCollectionBehavior::FullScreenAuxiliary); + } else { + window + .setCollectionBehavior(behavior - NSWindowCollectionBehavior::FullScreenAuxiliary); + } + } + + #[inline] + fn fullscreen_auxiliary(&self) -> bool { + self.window().collectionBehavior().contains(NSWindowCollectionBehavior::FullScreenAuxiliary) + } +} + +const DEFAULT_STANDARD_FRAME: NSRect = + NSRect::new(NSPoint::new(50.0, 50.0), NSSize::new(800.0, 600.0)); + +fn dark_appearance_name() -> &'static NSString { + // Don't use the static `NSAppearanceNameDarkAqua` to allow linking on macOS < 10.14 + ns_string!("NSAppearanceNameDarkAqua") +} + +pub fn appearance_to_theme(appearance: &NSAppearance) -> Theme { + let best_match = appearance.bestMatchFromAppearancesWithNames(&NSArray::from_slice(&[ + unsafe { NSAppearanceNameAqua }, + dark_appearance_name(), + ])); + if let Some(best_match) = best_match { + if *best_match == *dark_appearance_name() { Theme::Dark } else { Theme::Light } + } else { + warn!(?appearance, "failed to determine the theme of the appearance"); + // Default to light in this case + Theme::Light + } +} + +fn theme_to_appearance(theme: Option) -> Option> { + let appearance = match theme? { + Theme::Light => unsafe { NSAppearance::appearanceNamed(NSAppearanceNameAqua) }, + Theme::Dark => NSAppearance::appearanceNamed(dark_appearance_name()), + }; + if let Some(appearance) = appearance { + Some(appearance) + } else { + warn!(?theme, "could not find appearance for theme"); + // Assume system appearance in this case + None + } +} diff --git a/patches/winit-appkit/upstream/0001-macOS-surrounding-text-replacement-ranges-and-keyles.patch b/patches/winit-appkit/upstream/0001-macOS-surrounding-text-replacement-ranges-and-keyles.patch new file mode 100644 index 0000000000..18819e531e --- /dev/null +++ b/patches/winit-appkit/upstream/0001-macOS-surrounding-text-replacement-ranges-and-keyles.patch @@ -0,0 +1,376 @@ +From 0f447dc0764ee6730b59c2c7158e7d1a05baf3c7 Mon Sep 17 00:00:00 2001 +From: Adam Harris +Date: Thu, 15 Oct 2026 17:37:27 -0600 +Subject: [PATCH] macOS: surrounding text, replacement ranges and keyless + insertText in the text input client +MIME-Version: 1.0 +Content-Type: text/plain; charset=UTF-8 +Content-Transfer-Encoding: 8bit + +winit's NSTextInputClient answered nothing about the document: +`selectedRange` was always `{NSNotFound, 0}`, `attributedSubstringForProposedRange:` +always nil, and the `replacementRange` of `insertText:` and `setMarkedText:` was +ignored (two TODOs, "requires changing the event to report surrounding text" — +which winit-core has since done with `ImeRequestData::surrounding_text` and +`Ime::DeleteSurrounding`). And `insertText:` was reported only when it ended a +composition, on the assumption that any other text arrives as `KeyboardInput`. + +Two macOS text features fell through: + +- Press-and-hold accents: the input system reads the character before the + caret, marks it, and replaces it with the chosen accent. With no text to read + it never opened its menu, and the held key just repeated. +- The Emoji & Symbols picker, dictation and services insert with + `insertText:` and no keystroke, so their text was dropped. + +This change: + +- keeps the surrounding text the application reports and answers + `selectedRange` and `attributedSubstringForProposedRange:actualRange:` from it; +- resolves a `replacementRange` against it and reports `Ime::DeleteSurrounding` + (relative to the caret) before the `Ime::Commit` in `insertText:`, or before + the preedit in `setMarkedText:`; +- reports `insertText:` from outside `keyDown:` as `Ime::Commit`; +- does not forward a key repeat the input system swallowed (press-and-hold's + menu is up), nor the key that then picks from the menu, as `KeyboardInput`. + +An application that does not ask for the surrounding-text capability sees the +old behaviour, except that keyless insertions now arrive as `Ime::Commit` and a +swallowed repeat is no longer forwarded. +--- + winit-appkit/src/view.rs | 176 ++++++++++++++++++++++++++-- + winit-appkit/src/window_delegate.rs | 8 ++ + winit/src/changelog/unreleased.md | 11 ++ + 3 files changed, 186 insertions(+), 9 deletions(-) + +diff --git a/winit-appkit/src/view.rs b/winit-appkit/src/view.rs +index 64dc7080..99a8dc87 100644 +--- a/winit-appkit/src/view.rs ++++ b/winit-appkit/src/view.rs +@@ -23,7 +23,7 @@ use winit_core::event::{ + PointerKind, PointerSource, TouchPhase, WindowEvent, + }; + use winit_core::keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey}; +-use winit_core::window::ImeCapabilities; ++use winit_core::window::{ImeCapabilities, ImeSurroundingText}; + + use super::app_state::AppState; + use super::cursor::{default_cursor, invisible_cursor}; +@@ -148,6 +148,30 @@ pub struct ViewState { + + /// The state of the `Option` as `Alt`. + option_as_alt: Cell, ++ ++ // the text around the caret, as the application last reported ++ // it with `ImeRequestData::with_surrounding_text`. What `selectedRange` and ++ // `attributedSubstringForProposedRange:` answer from, and what a ++ // `replacementRange` is resolved against — without it the input system ++ // cannot see the character before the caret, so press-and-hold never ++ // opens its accent menu. ++ surrounding: RefCell>, ++ /// inside `keyDown:`'s `interpretKeyEvents:`, so `insertText:` ++ /// can tell a keystroke's own text (which `KeyboardInput` carries) from ++ /// text inserted with no key at all — the emoji picker, dictation. ++ in_key_down: Cell, ++ /// whether `interpretKeyEvents:` reached the client at all — ++ /// inserted, marked or commanded. A key repeat the input system swallowed ++ /// without any of those is press-and-hold holding the key, not typing. ++ text_activity: Cell, ++ /// press-and-hold's accent menu is up — a repeat was ++ /// swallowed and nothing has been inserted since. The key that picks an ++ /// accent (a digit, an arrow, Return) reaches none of the client's ++ /// methods while it is pressed: the menu inserts its choice *after* ++ /// `keyDown:` returns, so without this the digit was forwarded as typing ++ /// and the accent's `DeleteSurrounding` then took the digit, not the ++ /// letter. ++ accent_menu: Cell, + } + + define_class!( +@@ -256,6 +280,13 @@ define_class!( + #[unsafe(method(selectedRange))] + fn selected_range(&self) -> NSRange { + let _entered = debug_span!("selectedRange").entered(); ++ // answer from the surrounding text when the ++ // application reported it. ++ if let Some(s) = &*self.ivars().surrounding.borrow() { ++ let (lo, hi) = (s.cursor().min(s.anchor()), s.cursor().max(s.anchor())); ++ let start = utf16_len(&s.text()[..lo]); ++ return NSRange::new(start, utf16_len(&s.text()[lo..hi])); ++ } + // Documented to return `{NSNotFound, 0}` if there is no selection. + NSRange::new(NSNotFound as NSUInteger, 0) + } +@@ -265,10 +296,16 @@ define_class!( + &self, + string: &NSObject, + selected_range: NSRange, +- _replacement_range: NSRange, ++ replacement_range: NSRange, + ) { +- // TODO: Use _replacement_range, requires changing the event to report surrounding text. + let _entered = debug_span!("setMarkedText:selectedRange:replacementRange:").entered(); ++ self.ivars().text_activity.set(true); ++ // marking text that is already in the document — ++ // press-and-hold marks the character it is offering accents for — ++ // takes that text out first, so the preedit stands in its place. ++ if !self.hasMarkedText() { ++ self.delete_replaced(replacement_range); ++ } + + let (marked_text, string) = if let Some(string) = + string.downcast_ref::() +@@ -348,12 +385,13 @@ define_class!( + #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))] + fn attributed_substring_for_proposed_range( + &self, +- _range: NSRange, +- _actual_range: *mut NSRange, ++ range: NSRange, ++ actual_range: *mut NSRange, + ) -> Option> { + let _entered = + trace_span!("attributedSubstringForProposedRange:actualRange:").entered(); +- None ++ // the surrounding text the application reported. ++ self.surrounding_substring(range, actual_range) + } + + #[unsafe(method(characterIndexForPoint:))] +@@ -382,9 +420,10 @@ define_class!( + } + + #[unsafe(method(insertText:replacementRange:))] +- fn insert_text(&self, string: &NSObject, _replacement_range: NSRange) { +- // TODO: Use _replacement_range, requires changing the event to report surrounding text. ++ fn insert_text(&self, string: &NSObject, replacement_range: NSRange) { + let _entered = debug_span!("insertText:replacementRange:").entered(); ++ self.ivars().text_activity.set(true); ++ self.ivars().accent_menu.set(false); + + let string = if let Some(string) = string.downcast_ref::() { + string.string().to_string() +@@ -412,6 +451,30 @@ define_class!( + self.ivars().pending_commit.set(false); + self.queue_event(WindowEvent::Ime(Ime::Commit(string))); + self.ivars().ime_state.set(ImeState::Committed); ++ } else if !is_control && self.delete_replaced(replacement_range) { ++ // text that replaces text already in the document — ++ // press-and-hold's accent, chosen with a click or a number key. ++ // The replaced text went as `DeleteSurrounding`; this is its ++ // replacement. ++ self.queue_ime_enabled(); ++ self.queue_event(WindowEvent::Ime(Ime::Commit(string))); ++ // `Committed` tells `keyDown:` that the key it is handling was ++ // the input method's, not typing — true only when this ++ // insertion happened *during* a keypress. The accent menu ++ // inserts after the key that picked from it has returned, so ++ // there `Committed` was left for the next key, which then ++ // vanished: the first letter typed after an accent, or the ++ // ⌘Z meant to undo it. ++ if self.ivars().in_key_down.get() { ++ self.ivars().ime_state.set(ImeState::Committed); ++ } ++ } else if !is_control && !self.ivars().in_key_down.get() { ++ // text with no keystroke behind it — the emoji and ++ // symbols picker, dictation, a service. No `KeyboardInput` ++ // will carry it, so this is the only way it reaches the app. ++ // Not `Committed`: that would swallow the next real key. ++ self.queue_ime_enabled(); ++ self.queue_event(WindowEvent::Ime(Ime::Commit(string))); + } + } + +@@ -430,6 +493,7 @@ define_class!( + } + + self.ivars().forward_key_to_app.set(true); ++ self.ivars().text_activity.set(true); + + if self.hasMarkedText() && self.ivars().ime_state.get() == ImeState::Preedit { + // Leave preedit so that we also report the key-up for this key. +@@ -481,9 +545,12 @@ define_class!( + // we must send the `KeyboardInput` event during IME if it triggered + // `doCommandBySelector`. (doCommandBySelector means that the keyboard input + // is not handled by IME and should be handled by the application) ++ self.ivars().text_activity.set(false); + if self.ivars().ime_capabilities.get().is_some() { + let events_for_nsview = NSArray::from_slice(&[&*event]); ++ self.ivars().in_key_down.set(true); + self.interpretKeyEvents(&events_for_nsview); ++ self.ivars().in_key_down.set(false); + + // If the text was committed we must treat the next keyboard event as IME related. + if self.ivars().ime_state.get() == ImeState::Committed { +@@ -505,7 +572,28 @@ define_class!( + _ => old_ime_state != self.ivars().ime_state.get(), + }; + +- if !had_ime_input || self.ivars().forward_key_to_app.get() { ++ // a repeat the input system took without inserting, ++ // marking or commanding anything is press-and-hold holding the ++ // key while its accent menu is up — forwarding it would type the ++ // letter over and over underneath the menu. ++ let ime_capable = self.ivars().ime_capabilities.get().is_some(); ++ let quiet = ime_capable && !self.ivars().text_activity.get(); ++ let swallowed_repeat = event.isARepeat() && quiet; ++ if swallowed_repeat { ++ self.ivars().accent_menu.set(true); ++ } ++ // While the accent menu is up, a key that reached nothing is the ++ // menu's: choosing, moving, or dismissing it. Any key the input ++ // system does pass on (typing on past the menu) ends it. ++ let for_the_menu = self.ivars().accent_menu.get() && quiet; ++ if !quiet { ++ self.ivars().accent_menu.set(false); ++ } ++ ++ let forward = (!had_ime_input || self.ivars().forward_key_to_app.get()) ++ && !swallowed_repeat ++ && !for_the_menu; ++ if forward { + let key_event = create_key_event(&event, true, event.isARepeat()); + self.queue_event(WindowEvent::KeyboardInput { + device_id: None, +@@ -839,6 +927,10 @@ impl WinitView { + marked_text: Default::default(), + next_click_is_activation: Default::default(), + option_as_alt: Cell::new(option_as_alt), ++ surrounding: Default::default(), ++ in_key_down: Default::default(), ++ text_activity: Default::default(), ++ accent_menu: Default::default(), + }); + let this: Retained = unsafe { msg_send![super(this), init] }; + *this.ivars().input_source.borrow_mut() = this.current_input_source(); +@@ -1009,6 +1101,67 @@ impl WinitView { + self.ivars().ime_capabilities.get() + } + ++ /// `attributedSubstringForProposedRange:actualRange:` over the ++ /// surrounding text the application reported. ++ fn surrounding_substring( ++ &self, ++ range: NSRange, ++ actual_range: *mut NSRange, ++ ) -> Option> { ++ let surrounding = self.ivars().surrounding.borrow(); ++ let text = surrounding.as_ref()?.text(); ++ let len = utf16_len(text); ++ if range.location > len { ++ return None; ++ } ++ let end = range.end().min(len); ++ let lo = utf16_to_utf8_offset(text, range.location); ++ let hi = utf16_to_utf8_offset(text, end); ++ if !actual_range.is_null() { ++ // SAFETY: AppKit passes either null or a valid out-pointer. ++ unsafe { *actual_range = NSRange::new(range.location, end - range.location) }; ++ } ++ Some(NSAttributedString::from_nsstring(&NSString::from_str(&text[lo..hi]))) ++ } ++ ++ /// the text around the caret, from the application. ++ pub(super) fn set_ime_surrounding_text(&self, text: Option) { ++ *self.ivars().surrounding.borrow_mut() = text; ++ } ++ ++ /// `Ime::Enabled` if the application has not been told yet, ++ /// as the event's docs promise before any `Commit`. ++ fn queue_ime_enabled(&self) { ++ if self.ivars().ime_state.get() == ImeState::Disabled { ++ *self.ivars().input_source.borrow_mut() = self.current_input_source(); ++ self.queue_event(WindowEvent::Ime(Ime::Enabled)); ++ self.ivars().ime_state.set(ImeState::Ground); ++ } ++ } ++ ++ /// resolve a `replacementRange` against the surrounding text ++ /// and ask the application to delete it, as `Ime::DeleteSurrounding` ++ /// relative to the caret. Returns whether there was anything to delete. ++ fn delete_replaced(&self, range: NSRange) -> bool { ++ if range.location == NSNotFound as NSUInteger || range.length == 0 { ++ return false; ++ } ++ let deleted = { ++ let surrounding = self.ivars().surrounding.borrow(); ++ let Some(s) = surrounding.as_ref() else { return false }; ++ let lo = utf16_to_utf8_offset(s.text(), range.location); ++ let hi = utf16_to_utf8_offset(s.text(), range.end()); ++ let cursor = s.cursor().min(s.anchor()); ++ (lo < hi).then(|| (cursor.saturating_sub(lo), hi.saturating_sub(cursor.max(lo)))) ++ }; ++ let Some((before_bytes, after_bytes)) = deleted else { return false }; ++ self.queue_ime_enabled(); ++ self.queue_event(WindowEvent::Ime(Ime::DeleteSurrounding { before_bytes, after_bytes })); ++ // The text it described is gone; the application reports anew. ++ *self.ivars().surrounding.borrow_mut() = None; ++ true ++ } ++ + pub(super) fn set_ime_cursor_area(&self, position: NSPoint, size: NSSize) { + self.ivars().ime_position.set(position); + self.ivars().ime_size.set(size); +@@ -1299,6 +1452,11 @@ fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained usize { ++ s.encode_utf16().count() ++} ++ + fn utf16_to_utf8_offset(s: &str, utf16_offset: usize) -> usize { + let mut utf16_pos = 0; + for (utf8_pos, ch) in s.char_indices() { +diff --git a/winit-appkit/src/window_delegate.rs b/winit-appkit/src/window_delegate.rs +index bb73006d..94c0a009 100644 +--- a/winit-appkit/src/window_delegate.rs ++++ b/winit-appkit/src/window_delegate.rs +@@ -2132,6 +2132,14 @@ impl WindowDelegate { + _ => return Err(ImeRequestError::NotSupported), + }; + ++ // keep the text around the caret for the text input ++ // client's queries (see `WinitView::selected_range`). ++ if self.view().ime_capabilities().unwrap().surrounding_text() { ++ if let Some(text) = request_data.surrounding_text.clone() { ++ self.view().set_ime_surrounding_text(Some(text)); ++ } ++ } ++ + if let Some((spot, size)) = request_data.cursor_area { + if self.view().ime_capabilities().unwrap().cursor_area() { + let scale_factor = self.scale_factor(); +diff --git a/winit/src/changelog/unreleased.md b/winit/src/changelog/unreleased.md +index 7bd0d705..9a3dbc59 100644 +--- a/winit/src/changelog/unreleased.md ++++ b/winit/src/changelog/unreleased.md +@@ -40,6 +40,13 @@ changelog entry. + + ## Unreleased + ++### Added ++ ++- On macOS, honour `ImeRequestData::with_surrounding_text`: the text input client answers ++ `selectedRange` and `attributedSubstringForProposedRange:actualRange:` from it, and a ++ `replacementRange` it resolves is reported as `Ime::DeleteSurrounding` before the commit or ++ preedit that replaces it. ++ + ### Fixed + + - On Windows, fix a crash occurring when trying to create a DXGI surface on a window that is both fullscreen and always on top. +@@ -50,6 +57,10 @@ changelog entry. + - On Wayland, fix the text input being destroyed whenever a seat capability changed. This made IME input stop working in already-running applications after the seat's capabilities were updated. + - On Wayland, fix a panic when a popup is dropped before its queued compositor + updates are processed. ++- On macOS, fix the press-and-hold accent menu never opening, and the key that picks from it being ++ typed as well, for an application that reports surrounding text. ++- On macOS, fix text inserted with no keystroke behind it (the Emoji & Symbols picker, dictation, ++ services) being dropped; it is now reported as `Ime::Commit`. + + ### Changed + +-- +2.54.0 (Apple Git-157) + diff --git a/patches/winit-appkit/upstream/PR.md b/patches/winit-appkit/upstream/PR.md new file mode 100644 index 0000000000..c74c6e1258 --- /dev/null +++ b/patches/winit-appkit/upstream/PR.md @@ -0,0 +1,80 @@ +# Upstream PR, prepared and not sent + +The leaf patch to winit-appkit (see `../PATCH.md`), redone against winit's +`master` as one commit, ready to open as a pull request on +`rust-windowing/winit`. **Not sent: Adam approves it first.** + +- Base: winit `250cd01a` ("wayland: ignore queued updates for destroyed + windows (#4760)"), 2026-10-15. +- Patch: `0001-macOS-surrounding-text-replacement-ranges-and-keyles.patch` + (`git am` it onto that base). It touches `winit-appkit/src/view.rs`, + `winit-appkit/src/window_delegate.rs` and `winit/src/changelog/unreleased.md`; + none of the leaf-only `LEAF_TRACE` logging or `leaf patch` markers. +- Checked on that base: `cargo build`, `cargo clippy --all-targets` (no + warnings) and `cargo test` for `winit-appkit`, on macOS. + +## Before opening it + +1. `cargo +nightly fmt -p winit-appkit` — winit formats with nightly-only + rustfmt options, and this machine's nightly has no rustfmt component, so the + patch has not been through it. +2. Try it with winit's own `examples/` (an IME-using example) as well as leaf: + reviewers will ask how to reproduce it without Dioxus. +3. Decide whether to split it: the surrounding text and replacement ranges + (press-and-hold) and the keyless `insertText:` (picker, dictation) are + independent, and the repeat rule is the part a reviewer is likeliest to push + back on. One PR keeps the story whole; two would land the uncontroversial + half sooner. + +## Title + +macOS: surrounding text, replacement ranges and keyless insertText in the text input client + +## Description + +winit's `NSTextInputClient` on macOS answers nothing about the document: +`selectedRange` is always `{NSNotFound, 0}`, `attributedSubstringForProposedRange:actualRange:` +always `nil`, and the `replacementRange` of `insertText:` and `setMarkedText:` is +ignored — two `TODO`s say it "requires changing the event to report surrounding +text", which winit-core has since done with `ImeRequestData::surrounding_text` +and `Ime::DeleteSurrounding`. And `insertText:` is reported only when it ends a +composition, on the assumption that any other text arrives as `KeyboardInput`. + +Two macOS text features fall through those gaps: + +- **Press-and-hold accents.** The input system reads the character before the + caret, marks it, and replaces it with the chosen accent. With no text to read + it never opens its menu, and the held key just repeats. +- **The Emoji & Symbols picker**, dictation and services insert with + `insertText:` and no keystroke behind it, so their text is dropped. + +This PR: + +- keeps the surrounding text the application reports + (`ImeRequestData::with_surrounding_text`, with the capability) and answers + `selectedRange` and `attributedSubstringForProposedRange:actualRange:` from it; +- resolves a `replacementRange` against it and reports `Ime::DeleteSurrounding`, + relative to the caret, before the `Ime::Commit` in `insertText:` or the + preedit in `setMarkedText:` (press-and-hold marks the letter it offers + accents for); +- reports `insertText:` from outside `keyDown:` as `Ime::Commit`, with + `Ime::Enabled` first if the application has not had it; +- does not forward a key repeat the input system swallowed — nothing inserted, + marked or commanded, which is press-and-hold holding the key under its menu — + nor the key that then picks from the menu, as `KeyboardInput`. + +An application that does not ask for the surrounding-text capability sees the +old behaviour, except that keyless insertions now arrive as `Ime::Commit` and a +swallowed repeat is no longer forwarded. + +Found and tested in an editor built on Dioxus native (Blitz), which reports the +caret's line as surrounding text and handles `DeleteSurrounding`: press-and-hold +accents (with the digit, the arrow keys and a click choosing), their undo, and +emoji from the picker, on macOS. + +- [x] Tested on all platforms changed (macOS) +- [x] Added an entry to the `changelog` module +- [ ] Updated documentation — `ImeRequestData::with_surrounding_text`'s docs + could say macOS now uses it +- [ ] Example program — none; reproducible with any IME-enabled example that + reports surrounding text diff --git a/patches/winit-uikit/Cargo.toml b/patches/winit-uikit/Cargo.toml new file mode 100644 index 0000000000..521b232424 --- /dev/null +++ b/patches/winit-uikit/Cargo.toml @@ -0,0 +1,153 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +rust-version = "1.86" +name = "winit-uikit" +version = "0.31.0-beta.3" +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Winit's UIKit (iOS/tvOS/visionOS) backend" +documentation = "https://docs.rs/winit-uikit" +readme = "README.md" +license = "Apache-2.0" +repository = "https://github.com/rust-windowing/winit" + +[package.metadata.docs.rs] +all-features = true +targets = [ + "aarch64-apple-ios", + "aarch64-apple-ios-macabi", +] + +[features] +serde = [ + "dep:serde", + "bitflags/serde", + "smol_str/serde", + "dpi/serde", +] + +[lib] +name = "winit_uikit" +path = "src/lib.rs" + +[dependencies.bitflags] +version = "2" + +[dependencies.dpi] +version = "0.1.2" + +[dependencies.rwh_06] +version = "0.6" +features = ["std"] +package = "raw-window-handle" + +[dependencies.serde] +version = "1" +features = ["serde_derive"] +optional = true + +[dependencies.smol_str] +version = "0.3" + +[dependencies.tracing] +version = "0.1.40" +default-features = false + +[dependencies.winit-core] +version = "=0.31.0-beta.3" + +[target.'cfg(target_vendor = "apple")'.dependencies.block2] +version = "0.6.1" + +[target.'cfg(target_vendor = "apple")'.dependencies.dispatch2] +version = "0.3.0" +features = [ + "std", + "objc2", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2] +version = "0.6.1" +features = ["relax-sign-encoding"] + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-foundation] +version = "0.3.2" +features = [ + "std", + "CFCGTypes", + "CFBase", + "CFRunLoop", + "CFString", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-foundation] +version = "0.3.2" +features = [ + "std", + "block2", + "objc2-core-foundation", + "NSArray", + "NSEnumerator", + "NSGeometry", + "NSObjCRuntime", + "NSOperation", + "NSString", + "NSThread", + "NSSet", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-ui-kit] +version = "0.3.2" +features = [ + "std", + "objc2-core-foundation", + "UIApplication", + "UIDevice", + "UIEvent", + "UIGeometry", + "UIGestureRecognizer", + "UITextInput", + "UITextInputTraits", + "UIOrientation", + "UIPanGestureRecognizer", + "UIPinchGestureRecognizer", + "UIResponder", + "UIRotationGestureRecognizer", + "UIScene", + "UIScreen", + "UIScreenMode", + "UITapGestureRecognizer", + "UITouch", + "UITraitCollection", + "UIView", + "UIViewController", + "UIWindow", + "UIWindowScene", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.winit-common] +version = "=0.31.0-beta.3" +features = [ + "core-foundation", + "event-handler", + "foundation", +] diff --git a/patches/winit-uikit/LICENSE b/patches/winit-uikit/LICENSE new file mode 100644 index 0000000000..ad410e1130 --- /dev/null +++ b/patches/winit-uikit/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/patches/winit-uikit/PATCH.md b/patches/winit-uikit/PATCH.md new file mode 100644 index 0000000000..980cd8a295 --- /dev/null +++ b/patches/winit-uikit/PATCH.md @@ -0,0 +1,37 @@ +# winit-uikit 0.31.0-beta.3, patched + +The crate dioxus-native pins, kept here, in diaryx-org's Blitz fork, beside +the Blitz it is built with. It came from diaryx-org/leaf's +`patches/winit-uikit`, where it was vendored unmodified ("chore(patches): +vendor winit-uikit 0.31.0-beta.3 unmodified") and patched ("fix(patches): +adopt the UIScene lifecycle in winit-uikit, for iOS 27"): `git log -p -- +patches/winit-uikit` there is the patch. + +Consumers take it with `[patch.crates-io]` in their root manifest, as they +take `../winit-appkit`, from this repository's branch the rest of their +Blitz comes from, `{ git = "https://github.com/diaryx-org/blitz", branch = +"leaf" }`. + +## What was wrong + +An app built with the iOS 27 SDK must adopt the UIScene lifecycle, declaring +a scene configuration in its `Info.plist`; iOS 27 refuses to launch one that +does not. winit-uikit 0.31.0-beta.3 knows nothing of scenes: it makes its +window from the application's lifecycle, which a scene app no longer has. + +## What the patch does + +rust-windowing/winit#4723, "ios: support the UIScene lifecycle", applied +verbatim to `src/` (`app_state.rs`, `event_loop.rs`, `lib.rs`, `window.rs`), +and the two UIKit features it needs added to `Cargo.toml` (`UIScene`, +`UIWindowScene`) by hand, as the PR's manifest hunk does not apply to the +published crate. No `leaf patch` marks: the diff is the PR's. + +The app declares the scene configuration (`lib.rs`'s "Scenes" says how); no +scene delegate is needed. `spikes/blitz-ios-a11y/ios/Info.plist` has one. + +## When it goes + +When #4723 is in a winit release that dioxus-native takes. Until then the +proposal "A shared, patched winit for the Dioxus work" says to support the PR +upstream rather than open another. diff --git a/patches/winit-uikit/README.md b/patches/winit-uikit/README.md new file mode 100644 index 0000000000..affc454a4e --- /dev/null +++ b/patches/winit-uikit/README.md @@ -0,0 +1,79 @@ +# winit - Cross-platform window creation and management in Rust + +[![Crates.io](https://img.shields.io/crates/v/winit.svg)](https://crates.io/crates/winit) +[![Docs.rs](https://docs.rs/winit/badge.svg)](https://docs.rs/winit) +[![UNSTABLE docs](https://img.shields.io/github/actions/workflow/status/rust-windowing/winit/docs.yml?branch=master&label=UNSTABLE%20docs +)](https://rust-windowing.github.io/winit/winit/index.html) +[![CI Status](https://github.com/rust-windowing/winit/workflows/CI/badge.svg)](https://github.com/rust-windowing/winit/actions) + +```toml +[dependencies] +winit = "0.31.0-beta.3" +``` + +## [Documentation](https://docs.rs/winit) + +For features _within_ the scope of winit, see [FEATURES.md](FEATURES.md). + +For features _outside_ the scope of winit, see [Are we GUI Yet?](https://areweguiyet.com/) and [Are we game yet?](https://arewegameyet.rs/), depending on what kind of project you're looking to do. + +## Contact Us + +Join us in our [![Matrix](https://img.shields.io/badge/Matrix-%23rust--windowing%3Amatrix.org-blueviolet.svg)](https://matrix.to/#/#rust-windowing:matrix.org) room. + +The maintainers have a meeting every friday at UTC 15. The meeting notes can be found [here](https://hackmd.io/@winit-meetings). + +## Usage + +Winit is a window creation and management library. It can create windows and lets you handle +events (for example: the window being resized, a key being pressed, a mouse movement, etc.) +produced by the window. + +Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to +show something on the window you need to use the platform-specific getters provided by winit, or +another library. + +## CONTRIBUTING + +For contributing guidelines see [CONTRIBUTING.md](./CONTRIBUTING.md). + +## MSRV Policy + +This crate's Minimum Supported Rust Version (MSRV) is **1.86**. Changes to +the MSRV will be accompanied by a minor version bump. + +As a **tentative** policy, the upper bound of the MSRV is given by the following +formula: + +``` +min(sid, stable - 3) +``` + +Where `sid` is the current version of `rustc` provided by [Debian Sid], and +`stable` is the latest stable version of Rust. This bound may be broken in case of a major ecosystem shift or a security vulnerability. + +[Debian Sid]: https://packages.debian.org/sid/rustc + +An exception is made for the Android platform, where a higher Rust version +must be used for certain Android features. In this case, the MSRV will be +capped at the latest stable version of Rust minus three. This inconsistency is +not reflected in Cargo metadata, as it is not powerful enough to expose this +restriction. + +Redox OS is also not covered by this MSRV policy, as it requires a Rust nightly +toolchain to compile. + +All crates in the [`rust-windowing`] organizations have the +same MSRV policy. + +[`rust-windowing`]: https://github.com/rust-windowing + +### Platform-specific usage + +Check out the [`winit::platform`](https://docs.rs/winit/latest/winit/platform/index.html) module for platform-specific usage. + +### Repository License + +Note that the license in `LICENSE` doesn't apply in full to the DPI package [./dpi](./dpi). +Full details can be found in that folder's README. + diff --git a/patches/winit-uikit/src/app_state.rs b/patches/winit-uikit/src/app_state.rs new file mode 100644 index 0000000000..da6536fffa --- /dev/null +++ b/patches/winit-uikit/src/app_state.rs @@ -0,0 +1,549 @@ +#![deny(unused_results)] + +use std::cell::{Cell, OnceCell}; +use std::collections::HashSet; +use std::os::raw::c_void; +use std::sync::{Arc, Mutex}; +use std::time::Instant; +use std::{fmt, ptr}; + +use dispatch2::MainThreadBound; +use dpi::PhysicalSize; +use objc2::rc::Retained; +use objc2::{MainThreadMarker, available}; +use objc2_core_foundation::{ + CFAbsoluteTimeGetCurrent, CFRetained, CFRunLoop, CFRunLoopTimer, CGRect, CGSize, + kCFRunLoopCommonModes, +}; +use objc2_ui_kit::{UIApplication, UICoordinateSpace, UIView}; +use winit_common::core_foundation::EventLoopProxy; +use winit_common::event_handler::EventHandler; +use winit_core::application::ApplicationHandler; +use winit_core::event::{StartCause, SurfaceSizeWriter, WindowEvent}; +use winit_core::event_loop::ControlFlow; +use winit_core::window::WindowId; + +use crate::event_loop::ActiveEventLoop; +use crate::window::WinitUIWindow; + +macro_rules! bug { + ($($msg:tt)*) => { + panic!("winit iOS bug, file an issue: {}", format!($($msg)*)) + }; +} + +/// Get the global event handler for the application. +/// +/// This is stored separately from AppState, since AppState needs to be accessible while the handler +/// is executing. +fn get_handler(mtm: MainThreadMarker) -> &'static EventHandler { + // SAFETY: Creating `StaticMainThreadBound` in a `const` context, where there is no concept + // of the main thread. + static GLOBAL: MainThreadBound> = + MainThreadBound::new(OnceCell::new(), unsafe { MainThreadMarker::new_unchecked() }); + + GLOBAL.get(mtm).get_or_init(EventHandler::new) +} + +#[derive(Debug)] +pub(crate) enum EventWrapper { + Window { window_id: WindowId, event: WindowEvent }, + ScaleFactorChanged(ScaleFactorChanged), +} + +#[derive(Debug)] +pub struct ScaleFactorChanged { + pub(super) window: Retained, + pub(super) suggested_size: PhysicalSize, + pub(super) scale_factor: f64, +} + +impl EventWrapper { + fn is_redraw(&self) -> bool { + matches!(self, Self::Window { event: WindowEvent::RedrawRequested, .. }) + } +} + +// this is the state machine for the app lifecycle +#[derive(Clone, Copy, Debug)] +#[must_use = "dropping `AppStateImpl` without inspecting it is probably a bug"] +enum AppStateImpl { + Initial, + ProcessingEvents { active_control_flow: ControlFlow }, + ProcessingRedraws { active_control_flow: ControlFlow }, + Waiting { start: Instant }, + PollFinished, + Terminated, +} + +pub(crate) struct AppState { + state: Cell, + control_flow: Cell, + waker: EventLoopWaker, + event_loop_proxy: Arc, + queued_events: Cell>, + queued_gpu_redraws: Cell>>, + awaiting_scene: Cell, +} + +impl fmt::Debug for AppState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("AppState") + .field("control_flow", &self.control_flow) + .field("waker", &self.waker) + .field("event_loop_proxy", &self.event_loop_proxy) + .field("queued_events", &"Cell<...>") + .field("queued_gpu_redraws", &"Cell<...>") + .finish_non_exhaustive() + } +} + +// SAFETY: Creating `MainThreadBound` in a `const` context, +// where there is no concept of the main thread. +static GLOBAL: MainThreadBound> = + MainThreadBound::new(OnceCell::new(), unsafe { MainThreadMarker::new_unchecked() }); + +impl AppState { + pub(crate) fn setup_global(mtm: MainThreadMarker) -> bool { + let event_loop_proxy = Arc::new(EventLoopProxy::new(mtm, move || { + get_handler(mtm).handle(|app| app.proxy_wake_up(&ActiveEventLoop { mtm })); + })); + GLOBAL + .get(mtm) + .set(Self { + state: Cell::new(AppStateImpl::Initial), + control_flow: Cell::new(ControlFlow::default()), + waker: EventLoopWaker::new(CFRunLoop::main().unwrap()), + event_loop_proxy, + queued_events: Cell::new(Vec::new()), + queued_gpu_redraws: Cell::new(HashSet::new()), + awaiting_scene: Cell::new(false), + }) + .is_ok() + } + + pub(crate) fn get(mtm: MainThreadMarker) -> &'static Self { + GLOBAL.get(mtm).get().expect("tried to get application state before it was registered") + } + + fn has_launched(&self) -> bool { + !matches!(self.state.get(), AppStateImpl::Initial) + } + + fn has_terminated(&self) -> bool { + matches!(self.state.get(), AppStateImpl::Terminated) + } + + fn did_finish_launching_transition(&self) { + match self.state.get() { + AppStateImpl::Initial => {}, + s => bug!("unexpected state {:?}", s), + } + self.state + .set(AppStateImpl::ProcessingEvents { active_control_flow: self.control_flow.get() }); + } + + fn wakeup_transition(&self) -> Option { + // before `AppState::did_finish_launching` is called, pretend there is no running + // event loop. + if !self.has_launched() || self.has_terminated() { + return None; + } + + let start_cause = match (self.control_flow.get(), self.state.get()) { + (ControlFlow::Poll, AppStateImpl::PollFinished) => StartCause::Poll, + (ControlFlow::Wait, AppStateImpl::Waiting { start }) => { + StartCause::WaitCancelled { start, requested_resume: None } + }, + (ControlFlow::WaitUntil(requested_resume), AppStateImpl::Waiting { start }) => { + if Instant::now() >= requested_resume { + StartCause::ResumeTimeReached { start, requested_resume } + } else { + StartCause::WaitCancelled { start, requested_resume: Some(requested_resume) } + } + }, + s => bug!("`EventHandler` unexpectedly woke up {:?}", s), + }; + + self.state + .set(AppStateImpl::ProcessingEvents { active_control_flow: self.control_flow.get() }); + Some(start_cause) + } + + fn main_events_cleared_transition(&self) { + let active_control_flow = match self.state.get() { + AppStateImpl::ProcessingEvents { active_control_flow } => active_control_flow, + s => bug!("unexpected state {:?}", s), + }; + self.state.set(AppStateImpl::ProcessingRedraws { active_control_flow }); + } + + fn events_cleared_transition(&self) { + if !self.has_launched() || self.has_terminated() { + return; + } + let old = match self.state.get() { + AppStateImpl::ProcessingRedraws { active_control_flow } => active_control_flow, + s => bug!("unexpected state {:?}", s), + }; + + let new = self.control_flow.get(); + match (old, new) { + (ControlFlow::Wait, ControlFlow::Wait) => { + let start = Instant::now(); + self.state.set(AppStateImpl::Waiting { start }); + self.waker.stop() + }, + (ControlFlow::WaitUntil(old_instant), ControlFlow::WaitUntil(new_instant)) + if old_instant == new_instant => + { + let start = Instant::now(); + self.state.set(AppStateImpl::Waiting { start }); + }, + (_, ControlFlow::Wait) => { + let start = Instant::now(); + self.state.set(AppStateImpl::Waiting { start }); + self.waker.stop() + }, + (_, ControlFlow::WaitUntil(new_instant)) => { + let start = Instant::now(); + self.state.set(AppStateImpl::Waiting { start }); + self.waker.start_at(new_instant) + }, + // Unlike on macOS, handle Poll to Poll transition here to call the waker + (_, ControlFlow::Poll) => { + self.state.set(AppStateImpl::PollFinished); + self.waker.start() + }, + } + } + + fn terminated_transition(&self) { + match self.state.replace(AppStateImpl::Terminated) { + AppStateImpl::ProcessingEvents { .. } => {}, + s => bug!("terminated while not processing events {:?}", s), + } + } + + pub fn event_loop_proxy(&self) -> &Arc { + &self.event_loop_proxy + } + + pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { + self.control_flow.set(control_flow); + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + self.control_flow.get() + } +} + +pub(crate) fn queue_gl_or_metal_redraw(mtm: MainThreadMarker, window: Retained) { + let this = AppState::get(mtm); + match this.state.get() { + AppStateImpl::Initial | AppStateImpl::ProcessingEvents { .. } => { + let mut queued_gpu_redraws = this.queued_gpu_redraws.take(); + let _ = queued_gpu_redraws.insert(window); + this.queued_gpu_redraws.set(queued_gpu_redraws); + }, + s @ AppStateImpl::ProcessingRedraws { .. } + | s @ AppStateImpl::Waiting { .. } + | s @ AppStateImpl::PollFinished => bug!("unexpected state {:?}", s), + AppStateImpl::Terminated => { + panic!("Attempt to create a `Window` after the app has terminated") + }, + } +} + +pub(crate) fn launch( + mtm: MainThreadMarker, + app: impl ApplicationHandler, + run: impl FnOnce() -> R, +) -> R { + get_handler(mtm).set(Box::new(app), run) +} + +pub fn did_finish_launching(mtm: MainThreadMarker) { + let this = AppState::get(mtm); + + this.waker.start(); + this.did_finish_launching_transition(); + + get_handler(mtm).handle(|app| app.new_events(&ActiveEventLoop { mtm }, StartCause::Init)); + // Apps that adopt the scene life cycle get their first scene after launching, and windows + // need one to be shown. + if available!(ios = 13.0, tvos = 13.0, visionos = 1.0) + && UIApplication::sharedApplication(mtm).connectedScenes().is_empty() + { + this.awaiting_scene.set(true); + } else { + get_handler(mtm).handle(|app| app.can_create_surfaces(&ActiveEventLoop { mtm })); + } + handle_nonuser_events(mtm, []); +} + +pub(crate) fn scene_will_connect(mtm: MainThreadMarker) { + if AppState::get(mtm).awaiting_scene.replace(false) { + get_handler(mtm).handle(|app| app.can_create_surfaces(&ActiveEventLoop { mtm })); + handle_nonuser_events(mtm, []); + } +} + +// AppState::did_finish_launching handles the special transition `Init` +pub fn handle_wakeup_transition(mtm: MainThreadMarker) { + let this = AppState::get(mtm); + let cause = match this.wakeup_transition() { + None => return, + Some(cause) => cause, + }; + + get_handler(mtm).handle(|app| app.new_events(&ActiveEventLoop { mtm }, cause)); + handle_nonuser_events(mtm, []); +} + +pub(crate) fn handle_nonuser_event(mtm: MainThreadMarker, event: EventWrapper) { + handle_nonuser_events(mtm, std::iter::once(event)) +} + +pub(crate) fn handle_nonuser_events>( + mtm: MainThreadMarker, + events: I, +) { + let this = AppState::get(mtm); + if this.has_terminated() { + return; + } + + if !get_handler(mtm).ready() { + // Prevent re-entrancy; queue the events up for once we're done handling the event instead. + let mut queued_events = this.queued_events.take(); + queued_events.extend(events); + this.queued_events.set(queued_events); + return; + } + + let processing_redraws = matches!(this.state.get(), AppStateImpl::ProcessingRedraws { .. }); + + for event in events { + if !processing_redraws && event.is_redraw() { + tracing::info!("processing `RedrawRequested` during the main event loop"); + } else if processing_redraws && !event.is_redraw() { + tracing::warn!( + "processing non `RedrawRequested` event after the main event loop: {:#?}", + event + ); + } + handle_wrapped_event(mtm, event) + } + + loop { + let queued_events = this.queued_events.take(); + if queued_events.is_empty() { + break; + } + + for event in queued_events { + if !processing_redraws && event.is_redraw() { + tracing::info!("processing `RedrawRequested` during the main event loop"); + } else if processing_redraws && !event.is_redraw() { + tracing::warn!( + "processing non-`RedrawRequested` event after the main event loop: {:#?}", + event + ); + } + handle_wrapped_event(mtm, event); + } + } +} + +fn handle_user_events(mtm: MainThreadMarker) { + let this = AppState::get(mtm); + if matches!(this.state.get(), AppStateImpl::ProcessingRedraws { .. }) { + bug!("user events attempted to be sent out while `ProcessingRedraws`"); + } + + loop { + let queued_events = this.queued_events.take(); + if queued_events.is_empty() { + break; + } + + for event in queued_events { + handle_wrapped_event(mtm, event); + } + } +} + +pub(crate) fn send_occluded_event_for_all_windows(application: &UIApplication, occluded: bool) { + let mtm = MainThreadMarker::from(application); + + let mut events = Vec::new(); + #[allow(deprecated)] + for window in application.windows().iter() { + if let Ok(window) = window.downcast::() { + events.push(EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::Occluded(occluded), + }); + } + } + handle_nonuser_events(mtm, events); +} + +pub fn handle_main_events_cleared(mtm: MainThreadMarker) { + let this = AppState::get(mtm); + if !this.has_launched() || this.has_terminated() { + return; + } + match this.state.get() { + AppStateImpl::ProcessingEvents { .. } => {}, + _ => bug!("`ProcessingRedraws` happened unexpectedly"), + }; + + handle_user_events(mtm); + + this.main_events_cleared_transition(); + let queued_gpu_redraws = this.queued_gpu_redraws.take(); + let redraw_events = queued_gpu_redraws.into_iter().map(|window| EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::RedrawRequested, + }); + + handle_nonuser_events(mtm, redraw_events); + get_handler(mtm).handle(|app| app.about_to_wait(&ActiveEventLoop { mtm })); + handle_nonuser_events(mtm, []); +} + +pub fn handle_events_cleared(mtm: MainThreadMarker) { + AppState::get(mtm).events_cleared_transition(); +} + +pub(crate) fn handle_resumed(mtm: MainThreadMarker) { + get_handler(mtm).handle(|app| app.resumed(&ActiveEventLoop { mtm })); + handle_nonuser_events(mtm, []); +} + +pub(crate) fn handle_suspended(mtm: MainThreadMarker) { + get_handler(mtm).handle(|app| app.suspended(&ActiveEventLoop { mtm })); + handle_nonuser_events(mtm, []); +} + +pub(crate) fn handle_memory_warning(mtm: MainThreadMarker) { + get_handler(mtm).handle(|app| app.memory_warning(&ActiveEventLoop { mtm })); + handle_nonuser_events(mtm, []); +} + +pub(crate) fn terminated(application: &UIApplication) { + let mtm = MainThreadMarker::from(application); + + let mut events = Vec::new(); + #[allow(deprecated)] + for window in application.windows().iter() { + if let Ok(window) = window.downcast::() { + events.push(EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::Destroyed, + }); + } + } + handle_nonuser_events(mtm, events); + + let this = AppState::get(mtm); + this.terminated_transition(); + // Prevent EventLoopProxy from firing again. + this.event_loop_proxy.invalidate(); + + get_handler(mtm).terminate(); +} + +fn handle_wrapped_event(mtm: MainThreadMarker, event: EventWrapper) { + match event { + EventWrapper::Window { window_id, event } => get_handler(mtm) + .handle(|app| app.window_event(&ActiveEventLoop { mtm }, window_id, event)), + EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(mtm, event), + } +} + +fn handle_hidpi_proxy(mtm: MainThreadMarker, event: ScaleFactorChanged) { + let ScaleFactorChanged { suggested_size, scale_factor, window } = event; + let new_surface_size = Arc::new(Mutex::new(suggested_size)); + get_handler(mtm).handle(|app| { + app.window_event(&ActiveEventLoop { mtm }, window.id(), WindowEvent::ScaleFactorChanged { + scale_factor, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)), + }); + }); + let (view, screen_frame) = get_view_and_screen_frame(&window); + let physical_size = *new_surface_size.lock().unwrap(); + drop(new_surface_size); + let logical_size = physical_size.to_logical(scale_factor); + let size = CGSize::new(logical_size.width, logical_size.height); + let new_frame: CGRect = CGRect::new(screen_frame.origin, size); + view.setFrame(new_frame); +} + +fn get_view_and_screen_frame(window: &WinitUIWindow) -> (Retained, CGRect) { + let view_controller = window.rootViewController().unwrap(); + let view = view_controller.view().unwrap(); + let bounds = window.bounds(); + let screen = window.screen(); + let screen_space = screen.coordinateSpace(); + let screen_frame = window.convertRect_toCoordinateSpace(bounds, &screen_space); + (view, screen_frame) +} + +#[derive(Debug)] +struct EventLoopWaker { + timer: CFRetained, +} + +impl Drop for EventLoopWaker { + fn drop(&mut self) { + self.timer.invalidate(); + } +} + +impl EventLoopWaker { + fn new(rl: CFRetained) -> EventLoopWaker { + extern "C-unwind" fn wakeup_main_loop(_timer: *mut CFRunLoopTimer, _info: *mut c_void) {} + unsafe { + // Create a timer with a 0.1µs interval (1ns does not work) to mimic polling. + // It is initially setup with a first fire time really far into the + // future, but that gets changed to fire immediately in did_finish_launching + let timer = CFRunLoopTimer::new( + None, + f64::MAX, + 0.000_000_1, + 0, + 0, + Some(wakeup_main_loop), + ptr::null_mut(), + ) + .unwrap(); + rl.add_timer(Some(&timer), kCFRunLoopCommonModes); + + EventLoopWaker { timer } + } + } + + fn stop(&self) { + self.timer.set_next_fire_date(f64::MAX); + } + + fn start(&self) { + self.timer.set_next_fire_date(f64::MIN); + } + + fn start_at(&self, instant: Instant) { + let now = Instant::now(); + if now >= instant { + self.start(); + } else { + let current = CFAbsoluteTimeGetCurrent(); + let duration = instant - now; + let fsecs = + duration.subsec_nanos() as f64 / 1_000_000_000.0 + duration.as_secs() as f64; + self.timer.set_next_fire_date(current + fsecs); + } + } +} diff --git a/patches/winit-uikit/src/event_loop.rs b/patches/winit-uikit/src/event_loop.rs new file mode 100644 index 0000000000..66c8ca0936 --- /dev/null +++ b/patches/winit-uikit/src/event_loop.rs @@ -0,0 +1,393 @@ +use std::ffi::{CStr, c_char, c_void}; +use std::ptr; +use std::sync::Arc; + +use objc2::rc::Retained; +use objc2::runtime::ProtocolObject; +use objc2::{ClassType, MainThreadMarker, available, msg_send}; +use objc2_core_foundation::{CFIndex, CFRunLoopActivity, kCFRunLoopDefaultMode}; +use objc2_foundation::{NSNotificationCenter, NSNotificationName, NSObjectProtocol}; +use objc2_ui_kit::{ + UIApplication, UIApplicationDidBecomeActiveNotification, + UIApplicationDidEnterBackgroundNotification, UIApplicationDidFinishLaunchingNotification, + UIApplicationDidReceiveMemoryWarningNotification, UIApplicationWillEnterForegroundNotification, + UIApplicationWillResignActiveNotification, UIApplicationWillTerminateNotification, UIScreen, +}; +use rwh_06::HasDisplayHandle; +use tracing::debug_span; +use winit_common::core_foundation::{MainRunLoop, MainRunLoopObserver, tracing_observers}; +use winit_common::foundation::create_observer; +use winit_core::application::ApplicationHandler; +use winit_core::cursor::{CustomCursor, CustomCursorSource}; +use winit_core::error::{EventLoopError, NotSupportedError, RequestError}; +use winit_core::event_loop::{ + ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents, EventLoopProvider, + EventLoopProxy as CoreEventLoopProxy, OwnedDisplayHandle as CoreOwnedDisplayHandle, +}; +use winit_core::monitor::MonitorHandle as CoreMonitorHandle; +use winit_core::window::{Theme, Window as CoreWindow}; + +use super::app_state::{AppState, send_occluded_event_for_all_windows}; +use crate::monitor::MonitorHandle; +use crate::window::Window; +use crate::{app_state, monitor}; + +#[derive(Debug)] +pub struct ActiveEventLoop { + pub(super) mtm: MainThreadMarker, +} + +impl RootActiveEventLoop for ActiveEventLoop { + fn create_proxy(&self) -> CoreEventLoopProxy { + CoreEventLoopProxy::new(AppState::get(self.mtm).event_loop_proxy().clone()) + } + + fn create_window( + &self, + window_attributes: winit_core::window::WindowAttributes, + ) -> Result, RequestError> { + Ok(Box::new(Window::new(self, window_attributes)?)) + } + + fn create_custom_cursor( + &self, + _source: CustomCursorSource, + ) -> Result { + Err(NotSupportedError::new("create_custom_cursor is not supported").into()) + } + + fn available_monitors(&self) -> Box> { + Box::new( + monitor::uiscreens(self.mtm) + .into_iter() + .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), + ) + } + + fn primary_monitor(&self) -> Option { + #[allow(deprecated)] + let monitor = MonitorHandle::new(UIScreen::mainScreen(self.mtm)); + Some(CoreMonitorHandle(Arc::new(monitor))) + } + + fn listen_device_events(&self, _allowed: DeviceEvents) {} + + fn set_control_flow(&self, control_flow: ControlFlow) { + AppState::get(self.mtm).set_control_flow(control_flow) + } + + fn system_theme(&self) -> Option { + None + } + + fn control_flow(&self) -> ControlFlow { + AppState::get(self.mtm).control_flow() + } + + fn exit(&self) { + // https://developer.apple.com/library/archive/qa/qa1561/_index.html + // it is not possible to quit an iOS app gracefully and programmatically + tracing::warn!("`ControlFlow::Exit` ignored on iOS"); + } + + fn exiting(&self) -> bool { + false + } + + fn owned_display_handle(&self) -> CoreOwnedDisplayHandle { + CoreOwnedDisplayHandle::new(Arc::new(OwnedDisplayHandle)) + } + + fn rwh_06_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } +} + +impl rwh_06::HasDisplayHandle for ActiveEventLoop { + fn display_handle(&self) -> Result, rwh_06::HandleError> { + let raw = rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new()); + unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) } + } +} + +#[derive(Clone, PartialEq, Eq)] +pub(crate) struct OwnedDisplayHandle; + +impl HasDisplayHandle for OwnedDisplayHandle { + fn display_handle(&self) -> Result, rwh_06::HandleError> { + let raw = rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new()); + unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) } + } +} + +#[derive(Debug)] +pub struct EventLoop { + mtm: MainThreadMarker, + window_target: ActiveEventLoop, + + // Since iOS 9.0, we no longer need to remove the observers before they are deallocated; the + // system instead cleans it up next time it would have posted a notification to it. + // + // Though we do still need to keep the observers around to prevent them from being deallocated. + _did_finish_launching_observer: Retained>, + _did_become_active_observer: Retained>, + _will_resign_active_observer: Retained>, + _will_enter_foreground_observer: Retained>, + _did_enter_background_observer: Retained>, + _will_terminate_observer: Retained>, + _did_receive_memory_warning_observer: Retained>, + _scene_will_connect_observer: Option>>, + + _tracing_observers: Option<(MainRunLoopObserver, MainRunLoopObserver)>, + _wakeup_observer: MainRunLoopObserver, + _main_events_cleared_observer: MainRunLoopObserver, + _events_cleared_observer: MainRunLoopObserver, +} + +#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct PlatformSpecificEventLoopAttributes {} + +impl EventLoop { + pub fn new(_: &PlatformSpecificEventLoopAttributes) -> Result { + let mtm = MainThreadMarker::new() + .expect("On iOS, `EventLoop` must be created on the main thread"); + + if !AppState::setup_global(mtm) { + // Required, AppState is global state, and event loop can only be run once. + return Err(EventLoopError::RecreationAttempt); + } + + let center = NSNotificationCenter::defaultCenter(); + + let _did_finish_launching_observer = create_observer( + ¢er, + // `application:didFinishLaunchingWithOptions:` + unsafe { UIApplicationDidFinishLaunchingNotification }, + move |_| { + let _entered = debug_span!("UIApplicationDidFinishLaunchingNotification").entered(); + app_state::did_finish_launching(mtm); + }, + ); + let _did_become_active_observer = create_observer( + ¢er, + // `applicationDidBecomeActive:` + unsafe { UIApplicationDidBecomeActiveNotification }, + move |_| { + let _entered = debug_span!("UIApplicationDidBecomeActiveNotification").entered(); + app_state::handle_resumed(mtm) + }, + ); + let _will_resign_active_observer = create_observer( + ¢er, + // `applicationWillResignActive:` + unsafe { UIApplicationWillResignActiveNotification }, + move |_| { + let _entered = debug_span!("UIApplicationWillResignActiveNotification").entered(); + app_state::handle_suspended(mtm) + }, + ); + let _will_enter_foreground_observer = create_observer( + ¢er, + // `applicationWillEnterForeground:` + unsafe { UIApplicationWillEnterForegroundNotification }, + move |notification| { + let _entered = + debug_span!("UIApplicationWillEnterForegroundNotification").entered(); + let app = notification.object().expect( + "UIApplicationWillEnterForegroundNotification to have application object", + ); + // The `object` in `UIApplicationWillEnterForegroundNotification` is documented to + // be `UIApplication`. + let app = app.downcast::().unwrap(); + send_occluded_event_for_all_windows(&app, false); + }, + ); + let _did_enter_background_observer = create_observer( + ¢er, + // `applicationDidEnterBackground:` + unsafe { UIApplicationDidEnterBackgroundNotification }, + move |notification| { + let _entered = debug_span!("UIApplicationDidEnterBackgroundNotification").entered(); + let app = notification.object().expect( + "UIApplicationDidEnterBackgroundNotification to have application object", + ); + // The `object` in `UIApplicationDidEnterBackgroundNotification` is documented to be + // `UIApplication`. + let app = app.downcast::().unwrap(); + send_occluded_event_for_all_windows(&app, true); + }, + ); + let _will_terminate_observer = create_observer( + ¢er, + // `applicationWillTerminate:` + unsafe { UIApplicationWillTerminateNotification }, + move |notification| { + let _entered = debug_span!("UIApplicationWillTerminateNotification").entered(); + let app = notification + .object() + .expect("UIApplicationWillTerminateNotification to have application object"); + // The `object` in `UIApplicationWillTerminateNotification` is (somewhat) documented + // to be `UIApplication`. + let app = app.downcast::().unwrap(); + app_state::terminated(&app); + }, + ); + let _did_receive_memory_warning_observer = create_observer( + ¢er, + // `applicationDidReceiveMemoryWarning:` + unsafe { UIApplicationDidReceiveMemoryWarningNotification }, + move |_| { + let _entered = + debug_span!("UIApplicationDidReceiveMemoryWarningNotification").entered(); + app_state::handle_memory_warning(mtm) + }, + ); + + let _scene_will_connect_observer = available!(ios = 13.0, tvos = 13.0, visionos = 1.0) + .then(|| { + create_observer( + ¢er, + // `scene:willConnectToSession:options:` + uikit_notification_name(c"UISceneWillConnectNotification"), + move |_| { + let _entered = debug_span!("UISceneWillConnectNotification").entered(); + app_state::scene_will_connect(mtm) + }, + ) + }); + + let main_loop = MainRunLoop::get(mtm); + let mode = unsafe { kCFRunLoopDefaultMode }.unwrap(); + + // Tracing observers have the lowest and highest orderings. + let _tracing_observers = tracing_observers(mtm).inspect(|(start, end)| { + main_loop.add_observer(start, mode); + main_loop.add_observer(end, mode); + }); + + let _wakeup_observer = MainRunLoopObserver::new( + mtm, + CFRunLoopActivity::AfterWaiting, + true, + // Queued with the second-highest priority (tracing observers use the highest) to + // ensure it is processed before other observers. + CFIndex::MIN + 1, + move |_| app_state::handle_wakeup_transition(mtm), + ); + main_loop.add_observer(&_wakeup_observer, mode); + + let _main_events_cleared_observer = MainRunLoopObserver::new( + mtm, + CFRunLoopActivity::BeforeWaiting, + true, + // Core Animation registers its `CFRunLoopObserver` that performs drawing operations in + // `CA::Transaction::ensure_implicit` with a priority of `2000000`. We set the + // main_end priority to be 0, in order to send `AboutToWait` before `RedrawRequested`. + // This value was chosen conservatively to guard against apple using different + // priorities for their redraw observers in different OS's or on different devices. If + // it so happens that it's too conservative, the main symptom would be non-redraw + // events coming in after `AboutToWait`. + // + // The value of `2000000` was determined by inspecting stack traces and the associated + // registers for every `CFRunLoopAddObserver` call on an iPad Air 2 running iOS 11.4. + // + // Also tested to be `2000000` on iPhone 8, iOS 13 beta 4. + 0, + move |_| app_state::handle_main_events_cleared(mtm), + ); + main_loop.add_observer(&_main_events_cleared_observer, mode); + + let _events_cleared_observer = MainRunLoopObserver::new( + mtm, + CFRunLoopActivity::BeforeWaiting, + true, + // Queued with the second-lowest priority (tracing observers use the lowest) to ensure + // it is processed after other observers. + CFIndex::MAX - 1, + move |_| app_state::handle_events_cleared(mtm), + ); + main_loop.add_observer(&_events_cleared_observer, mode); + + Ok(EventLoop { + mtm, + window_target: ActiveEventLoop { mtm }, + _did_finish_launching_observer, + _did_become_active_observer, + _will_resign_active_observer, + _will_enter_foreground_observer, + _did_enter_background_observer, + _will_terminate_observer, + _did_receive_memory_warning_observer, + _scene_will_connect_observer, + _tracing_observers, + _wakeup_observer, + _main_events_cleared_observer, + _events_cleared_observer, + }) + } + + // Require `'static` for correctness, we won't be able to `Drop` the user's state otherwise. + pub fn run_app_never_return(self, app: A) -> ! { + let application: Option> = + unsafe { msg_send![UIApplication::class(), sharedApplication] }; + assert!( + application.is_none(), + "\ + `EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\nNote: \ + `EventLoop::run_app` calls `UIApplicationMain` on iOS", + ); + + // We intentionally override neither the application nor the delegate, + // to allow the user to do so themselves! + // + // NOTE: `UIApplicationMain` is _the only way_ to start the event loop on iOS/UIKit, there + // are no other feasible options. See also: + // + app_state::launch(self.mtm, app, || UIApplication::main(None, None, self.mtm)) + } + + pub fn window_target(&self) -> &dyn RootActiveEventLoop { + &self.window_target + } +} + +/// Looks up a notification name at runtime. Linking to one that is newer than the app's oldest +/// supported iOS version would stop the app from launching there. +fn uikit_notification_name(symbol: &CStr) -> &'static NSNotificationName { + unsafe extern "C" { + fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; + } + const RTLD_DEFAULT: *mut c_void = ptr::without_provenance_mut(-2isize as usize); + let name: *const &'static NSNotificationName = + unsafe { dlsym(RTLD_DEFAULT, symbol.as_ptr()) }.cast(); + unsafe { name.as_ref() }.copied().unwrap_or_else(|| panic!("UIKit has no {symbol:?}")) +} + +impl EventLoopProvider for EventLoop { + fn run_app(self, app: A) -> Result<(), EventLoopError> { + self.run_app_never_return(app) + } + + fn create_proxy(&self) -> CoreEventLoopProxy { + self.window_target().create_proxy() + } + + fn owned_display_handle(&self) -> CoreOwnedDisplayHandle { + self.window_target().owned_display_handle() + } + + fn listen_device_events(&self, allowed: DeviceEvents) { + self.window_target().listen_device_events(allowed); + } + + fn set_control_flow(&self, control_flow: ControlFlow) { + self.window_target().set_control_flow(control_flow); + } + + fn create_custom_cursor( + &self, + custom_cursor: CustomCursorSource, + ) -> Result { + self.window_target().create_custom_cursor(custom_cursor) + } +} diff --git a/patches/winit-uikit/src/lib.rs b/patches/winit-uikit/src/lib.rs new file mode 100644 index 0000000000..26c8ed907d --- /dev/null +++ b/patches/winit-uikit/src/lib.rs @@ -0,0 +1,486 @@ +//! # Winit's UIKit (iOS/tvOS/visionOS) backend +//! +//! Winit has [the same iOS version requirements as `rustc`][rustc-ios-version], although it's +//! frequently only tested on newer iOS versions. +//! +//! [rustc-ios-version]: https://doc.rust-lang.org/rustc/platform-support/apple-ios.html#os-version +//! +//! ## Running on Mac Catalyst +//! +//! Mac Catalyst allows running applications using UIKit on macOS, which can be very useful for +//! testing. See [`rustc`'s documentation on Mac Catalyst][rustc-mac-catalyst] for details on how to +//! use these targets. To use these with Winit, you'll need to bundle your application before +//! running it, otherwise UIKit will exit with an error. +//! +//! To run e.g. the `window` example in the Winit repository, you can use [`cargo-bundle`] as +//! follows: +//! +//! ```console +//! $ cargo +nightly bundle --format=ios --target=aarch64-apple-ios-macabi --example=window +//! $ ./target/aarch64-apple-ios-macabi/debug/examples/bundle/ios/winit.app/window +//! ``` +//! +//! [rustc-mac-catalyst]: https://doc.rust-lang.org/rustc/platform-support/apple-ios-macabi.html +//! [`cargo-bundle`]: https://github.com/burtonageo/cargo-bundle +//! +//! ## Introduction to building an app +//! +//! Building and running your application in the iOS simulator, or on a real device, is a bit more +//! complicated than Mac Catalyst - fundamentally, you must use Xcode, since the binary needs to be +//! bundled, signed, notarized and uploaded to the device (there is [an open source work-in-progress +//! on re-implementing parts of this][apple-platform-rs], but the user-story around it is not yet +//! clear). +//! +//! This means that you're left with effectively two options: Use a tool that manages the Xcode +//! configuration for you, or use Xcode directly. [`cargo-dinghy`] and [`cargo-mobile2`] are notable +//! projects in the ecosystem that attempt the former, and [`cargo-xcode`] is an excellent project +//! that attempts the latter. We will also attempt to describe here how you would go about using +//! Xcode directly: +//! +//! First off, you'll need the correct Rust targets, see [`rustc`'s documentation on iOS][rustc-ios] +//! for details. Nowadays, the correct targets are usually `aarch64-apple-ios-sim` for the +//! simulator, and `aarch64-apple-ios` for the actual device. +//! +//! Next, create a new Xcode project using the "App" template. The exact configuration does not +//! really matter, as we're going to delete most of it, since it's tailored for Objective-C and/or +//! Swift, and Rust/Winit is neither. Specifically, we need to delete: +//! - Everything relating to storyboards (unless you want to use e.g. a launch screen). This +//! includes the relevant keys in `Info.plist`. +//! - All the generated C header, Objective-C and/or Swift files. +//! +//! Now that we have a fairly clean slate that we can build upon, you can add a "run script" build +//! phase to your Xcode target, which will get invoked instead of the "compile sources" and "link +//! binary" steps. The basic script should look something like: +//! +//! ```sh +//! # Build desired targets based on `ARCHS` environment variable +//! cargo build --target=aarch64-apple-ios --target=armv7s-apple-ios +//! # Merge these with `lipo`, and place the result in "$TARGET_BUILD_DIR/$EXECUTABLE_PATH", which +//! # is understood by Xcode +//! lipo "$TARGET_BUILD_DIR/$EXECUTABLE_PATH" target/aarch64-apple-ios/debug/my_app target/armv7s-apple-ios/debug/my_app +//! ``` +//! +//! Note that this is very much the overall idea; the script needs to be much more involved to +//! properly deal with different target architectures, invoking `lipo` when needed, incremental +//! rebuild change detection, and so on. `cargo-xcode` has a script [here][cargo-xcode-script] that +//! handles most of this complexity, you might be able to build upon that. +//! +//! Apologies that we're not able to provide you with more than this; work is in-progress on +//! improving the situation, but it's slow-going. +//! +//! [apple-platform-rs]: https://github.com/indygreg/apple-platform-rs +//! [`cargo-dinghy`]: https://github.com/sonos/dinghy +//! [`cargo-mobile2`]: https://github.com/tauri-apps/cargo-mobile2 +//! [`cargo-xcode`]: https://crates.io/crates/cargo-xcode +//! [rustc-ios]: https://doc.rust-lang.org/rustc/platform-support/apple-ios.html +//! [cargo-xcode-script]: https://gitlab.com/kornelski/cargo-xcode/-/blob/main/src/xcodebuild.sh +//! +//! ## App lifecycle and events +//! +//! iOS environment is very different from other platforms and you must be very +//! careful with it's events. Familiarize yourself with +//! [app lifecycle](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/). +//! +//! This is how those event are represented in winit: +//! +//! - applicationDidBecomeActive is Resumed +//! - applicationWillResignActive is Suspended +//! - applicationWillTerminate corresponds to `Drop`ping the application handler. +//! +//! Note that an app may not receive the `Drop` event if suspended; it might be SIGKILL'ed. +//! +//! ## Scenes +//! +//! Apps built with the iOS 27 SDK must adopt [the UIScene lifecycle][scenes] by declaring a scene +//! configuration in `Info.plist`. No scene delegate is needed: +//! +//! ```xml +//! UIApplicationSceneManifest +//! +//! UIApplicationSupportsMultipleScenes +//! +//! UISceneConfigurations +//! +//! UIWindowSceneSessionRoleApplication +//! +//! +//! UISceneConfigurationName +//! Default Configuration +//! +//! +//! +//! +//! ``` +//! +//! Winit shows its windows in the first scene that connects; multiple scenes are not supported. +//! +//! [scenes]: https://developer.apple.com/documentation/uikit/specifying-the-scenes-your-app-supports +//! +//! ## Custom `UIApplicationDelegate` +//! +//! Winit usually handles everything related to the lifecycle events of the application. Sometimes, +//! though, you might want to access some of the more niche stuff that [the application +//! delegate][app-delegate] provides. This functionality is not exposed directly in Winit, since it +//! would increase the API surface by quite a lot. Instead, Winit guarantees that it will not +//! register an application delegate, so you can set up a custom one in a nib file instead. +//! +//! [app-delegate]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate?language=objc +#![cfg(target_vendor = "apple")] // TODO: Remove once `objc2` allows compiling on all platforms +#![warn(clippy::exhaustive_enums)] + +mod app_state; +mod event_loop; +mod monitor; +mod view; +mod view_controller; +mod window; + +use std::os::raw::c_void; + +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; +use winit_core::monitor::{MonitorHandle, VideoMode}; +use winit_core::window::{PlatformWindowAttributes, Window}; + +pub use self::event_loop::{EventLoop, PlatformSpecificEventLoopAttributes}; +use self::monitor::MonitorHandle as UIKitMonitorHandle; +use self::window::Window as UIKitWindow; + +/// Additional methods on [`Window`] that are specific to iOS. +pub trait WindowExtIOS { + /// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`. + /// + /// The default value is device dependent, and it's recommended GLES or Metal applications set + /// this to [`MonitorHandleProvider::scale_factor()`]. + /// + /// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc + /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc + /// [`MonitorHandleProvider::scale_factor()`]: crate::monitor::MonitorHandleProvider::scale_factor() + fn set_scale_factor(&self, scale_factor: f64); + + /// Sets the valid orientations for the [`Window`]. + /// + /// The default value is [`ValidOrientations::LandscapeAndPortrait`]. + /// + /// This changes the value returned by + /// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc), + /// and then calls + /// [`-[UIViewController attemptRotationToDeviceOrientation]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621400-attemptrotationtodeviceorientati?language=objc). + fn set_valid_orientations(&self, valid_orientations: ValidOrientations); + + /// Sets whether the [`Window`] prefers the home indicator hidden. + /// + /// The default is to prefer showing the home indicator. + /// + /// This changes the value returned by + /// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc), + /// and then calls + /// [`-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc). + /// + /// This only has an effect on iOS 11.0+. + fn set_prefers_home_indicator_hidden(&self, hidden: bool); + + /// Sets the screen edges for which the system gestures will take a lower priority than the + /// application's touch handling. + /// + /// This changes the value returned by + /// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc), + /// and then calls + /// [`-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc). + /// + /// This only has an effect on iOS 11.0+. + fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge); + + /// Sets whether the [`Window`] prefers the status bar hidden. + /// + /// The default is to prefer showing the status bar. + /// + /// This sets the value of the + /// [`prefersStatusBarHidden`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc) + /// property. + /// + /// [`setNeedsStatusBarAppearanceUpdate()`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc) + /// is also called for you. + fn set_prefers_status_bar_hidden(&self, hidden: bool); + + /// Sets the preferred status bar style for the [`Window`]. + /// + /// The default is system-defined. + /// + /// This sets the value of the + /// [`preferredStatusBarStyle`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621416-preferredstatusbarstyle?language=objc) + /// property. + /// + /// [`setNeedsStatusBarAppearanceUpdate()`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc) + /// is also called for you. + fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle); + + /// Sets whether the [`Window`] should recognize pinch gestures. + /// + /// The default is to not recognize gestures. + fn recognize_pinch_gesture(&self, should_recognize: bool); + + /// Sets whether the [`Window`] should recognize pan gestures. + /// + /// The default is to not recognize gestures. + /// Installs [`UIPanGestureRecognizer`](https://developer.apple.com/documentation/uikit/uipangesturerecognizer) onto view + /// + /// Set the minimum number of touches required: [`minimumNumberOfTouches`](https://developer.apple.com/documentation/uikit/uipangesturerecognizer/1621208-minimumnumberoftouches) + /// + /// Set the maximum number of touches recognized: [`maximumNumberOfTouches`](https://developer.apple.com/documentation/uikit/uipangesturerecognizer/1621208-maximumnumberoftouches) + fn recognize_pan_gesture( + &self, + should_recognize: bool, + minimum_number_of_touches: u8, + maximum_number_of_touches: u8, + ); + + /// Sets whether the [`Window`] should recognize double tap gestures. + /// + /// The default is to not recognize gestures. + fn recognize_doubletap_gesture(&self, should_recognize: bool); + + /// Sets whether the [`Window`] should recognize rotation gestures. + /// + /// The default is to not recognize gestures. + fn recognize_rotation_gesture(&self, should_recognize: bool); +} + +impl WindowExtIOS for dyn Window + '_ { + #[inline] + fn set_scale_factor(&self, scale_factor: f64) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_scale_factor(scale_factor)); + } + + #[inline] + fn set_valid_orientations(&self, valid_orientations: ValidOrientations) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_valid_orientations(valid_orientations)); + } + + #[inline] + fn set_prefers_home_indicator_hidden(&self, hidden: bool) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_prefers_home_indicator_hidden(hidden)); + } + + #[inline] + fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| { + w.set_preferred_screen_edges_deferring_system_gestures(edges) + }); + } + + #[inline] + fn set_prefers_status_bar_hidden(&self, hidden: bool) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_prefers_status_bar_hidden(hidden)); + } + + #[inline] + fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_preferred_status_bar_style(status_bar_style)) + } + + #[inline] + fn recognize_pinch_gesture(&self, should_recognize: bool) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.recognize_pinch_gesture(should_recognize)); + } + + #[inline] + fn recognize_pan_gesture( + &self, + should_recognize: bool, + minimum_number_of_touches: u8, + maximum_number_of_touches: u8, + ) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| { + w.recognize_pan_gesture( + should_recognize, + minimum_number_of_touches, + maximum_number_of_touches, + ) + }); + } + + #[inline] + fn recognize_doubletap_gesture(&self, should_recognize: bool) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.recognize_doubletap_gesture(should_recognize)); + } + + #[inline] + fn recognize_rotation_gesture(&self, should_recognize: bool) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.recognize_rotation_gesture(should_recognize)); + } +} + +/// Ios specific window attributes. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct WindowAttributesIos { + pub(crate) scale_factor: Option, + pub(crate) valid_orientations: ValidOrientations, + pub(crate) prefers_home_indicator_hidden: bool, + pub(crate) prefers_status_bar_hidden: bool, + pub(crate) preferred_status_bar_style: StatusBarStyle, + pub(crate) preferred_screen_edges_deferring_system_gestures: ScreenEdge, +} + +impl WindowAttributesIos { + /// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`. + /// + /// The default value is device dependent, and it's recommended GLES or Metal applications set + /// this to [`MonitorHandleProvider::scale_factor()`]. + /// + /// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc + /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc + /// [`MonitorHandleProvider::scale_factor()`]: crate::monitor::MonitorHandleProvider::scale_factor() + pub fn with_scale_factor(mut self, scale_factor: f64) -> Self { + self.scale_factor = Some(scale_factor); + self + } + + /// Sets the valid orientations for the [`Window`]. + /// + /// The default value is [`ValidOrientations::LandscapeAndPortrait`]. + /// + /// This sets the initial value returned by + /// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc). + pub fn with_valid_orientations(mut self, valid_orientations: ValidOrientations) -> Self { + self.valid_orientations = valid_orientations; + self + } + + /// Sets whether the [`Window`] prefers the home indicator hidden. + /// + /// The default is to prefer showing the home indicator. + /// + /// This sets the initial value returned by + /// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc). + /// + /// This only has an effect on iOS 11.0+. + pub fn with_prefers_home_indicator_hidden(mut self, hidden: bool) -> Self { + self.prefers_home_indicator_hidden = hidden; + self + } + + /// Sets the screen edges for which the system gestures will take a lower priority than the + /// application's touch handling. + /// + /// This sets the initial value returned by + /// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc). + /// + /// This only has an effect on iOS 11.0+. + pub fn with_preferred_screen_edges_deferring_system_gestures( + mut self, + edges: ScreenEdge, + ) -> Self { + self.preferred_screen_edges_deferring_system_gestures = edges; + self + } + + /// Sets whether the [`Window`] prefers the status bar hidden. + /// + /// The default is to prefer showing the status bar. + /// + /// This sets the initial value returned by + /// [`-[UIViewController prefersStatusBarHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc). + pub fn with_prefers_status_bar_hidden(mut self, hidden: bool) -> Self { + self.prefers_status_bar_hidden = hidden; + self + } + + /// Sets the style of the [`Window`]'s status bar. + /// + /// The default is system-defined. + /// + /// This sets the initial value returned by + /// [`-[UIViewController preferredStatusBarStyle]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621416-preferredstatusbarstyle?language=objc), + pub fn with_preferred_status_bar_style(mut self, status_bar_style: StatusBarStyle) -> Self { + self.preferred_status_bar_style = status_bar_style; + self + } +} + +impl PlatformWindowAttributes for WindowAttributesIos { + fn box_clone(&self) -> Box { + Box::from(self.clone()) + } +} + +/// Additional methods on [`MonitorHandle`] that are specific to iOS. +pub trait MonitorHandleExtIOS { + /// Returns a pointer to the [`UIScreen`] that is used by this monitor. + /// + /// [`UIScreen`]: https://developer.apple.com/documentation/uikit/uiscreen?language=objc + fn ui_screen(&self) -> *mut c_void; + + /// Returns the preferred [`VideoMode`] for this monitor. + /// + /// This translates to a call to [`-[UIScreen preferredMode]`](https://developer.apple.com/documentation/uikit/uiscreen/1617823-preferredmode?language=objc). + fn preferred_video_mode(&self) -> VideoMode; +} + +impl MonitorHandleExtIOS for MonitorHandle { + #[inline] + fn ui_screen(&self) -> *mut c_void { + // SAFETY: The marker is only used to get the pointer of the screen + let mtm = unsafe { objc2::MainThreadMarker::new_unchecked() }; + let monitor = self.cast_ref::().unwrap(); + objc2::rc::Retained::as_ptr(monitor.ui_screen(mtm)) as *mut c_void + } + + #[inline] + fn preferred_video_mode(&self) -> VideoMode { + let monitor = self.cast_ref::().unwrap(); + monitor.preferred_video_mode() + } +} + +/// Valid orientations for a particular [`Window`]. +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[non_exhaustive] +pub enum ValidOrientations { + /// Excludes `PortraitUpsideDown` on iphone + #[default] + LandscapeAndPortrait, + + Landscape, + + /// Excludes `PortraitUpsideDown` on iphone + Portrait, +} + +bitflags::bitflags! { + /// The [edges] of a screen. + /// + /// [edges]: https://developer.apple.com/documentation/uikit/uirectedge?language=objc + #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] + pub struct ScreenEdge: u8 { + const NONE = 0; + const TOP = 1 << 0; + const LEFT = 1 << 1; + const BOTTOM = 1 << 2; + const RIGHT = 1 << 3; + const ALL = ScreenEdge::TOP.bits() | ScreenEdge::LEFT.bits() + | ScreenEdge::BOTTOM.bits() | ScreenEdge::RIGHT.bits(); + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[non_exhaustive] +pub enum StatusBarStyle { + #[default] + Default, + LightContent, + DarkContent, +} diff --git a/patches/winit-uikit/src/monitor.rs b/patches/winit-uikit/src/monitor.rs new file mode 100644 index 0000000000..c2d7935372 --- /dev/null +++ b/patches/winit-uikit/src/monitor.rs @@ -0,0 +1,278 @@ +#![allow(clippy::unnecessary_cast)] + +use std::collections::VecDeque; +use std::num::NonZeroU32; +use std::{fmt, hash, ptr}; + +use dispatch2::{MainThreadBound, run_on_main}; +use dpi::PhysicalPosition; +use objc2::rc::Retained; +use objc2::{MainThreadMarker, Message, available}; +use objc2_foundation::NSInteger; +use objc2_ui_kit::{UIScreen, UIScreenMode}; +use winit_core::monitor::{MonitorHandleProvider, VideoMode}; + +// Workaround for `MainThreadBound` implementing almost no traits +#[derive(Debug)] +struct MainThreadBoundDelegateImpls(MainThreadBound>); + +impl Clone for MainThreadBoundDelegateImpls { + fn clone(&self) -> Self { + Self(run_on_main(|mtm| MainThreadBound::new(Retained::clone(self.0.get(mtm)), mtm))) + } +} + +impl hash::Hash for MainThreadBoundDelegateImpls { + fn hash(&self, state: &mut H) { + // SAFETY: Marker only used to get the pointer + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + Retained::as_ptr(self.0.get(mtm)).hash(state); + } +} + +impl PartialEq for MainThreadBoundDelegateImpls { + fn eq(&self, other: &Self) -> bool { + // SAFETY: Marker only used to get the pointer + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + Retained::as_ptr(self.0.get(mtm)) == Retained::as_ptr(other.0.get(mtm)) + } +} + +impl Eq for MainThreadBoundDelegateImpls {} + +#[derive(Debug, PartialEq, Eq, Hash, Clone)] +pub struct VideoModeHandle { + pub(crate) mode: VideoMode, + screen_mode: MainThreadBoundDelegateImpls, +} + +impl VideoModeHandle { + fn new( + uiscreen: Retained, + screen_mode: Retained, + mtm: MainThreadMarker, + ) -> VideoModeHandle { + let refresh_rate_millihertz = refresh_rate_millihertz(&uiscreen); + let size = screen_mode.size(); + let mode = VideoMode::new( + (size.width as u32, size.height as u32).into(), + None, + refresh_rate_millihertz, + ); + + VideoModeHandle { + mode, + screen_mode: MainThreadBoundDelegateImpls(MainThreadBound::new(screen_mode, mtm)), + } + } + + pub(super) fn screen_mode(&self, mtm: MainThreadMarker) -> &Retained { + self.screen_mode.0.get(mtm) + } +} + +pub struct MonitorHandle { + ui_screen: MainThreadBound>, +} + +impl MonitorHandleProvider for MonitorHandle { + fn id(&self) -> u128 { + self.native_id() as _ + } + + fn native_id(&self) -> u64 { + // SAFETY: Only getting the pointer. + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + Retained::as_ptr(self.ui_screen.get(mtm)) as u64 + } + + fn name(&self) -> Option> { + run_on_main(|mtm| { + #[allow(deprecated)] + let main = UIScreen::mainScreen(mtm); + if *self.ui_screen(mtm) == main { + Some("Primary".into()) + } else if Some(self.ui_screen(mtm)) == main.mirroredScreen().as_ref() { + Some("Mirrored".into()) + } else { + #[allow(deprecated)] + UIScreen::screens(mtm) + .iter() + .position(|rhs| rhs == *self.ui_screen(mtm)) + .map(|idx| idx.to_string().into()) + } + }) + } + + fn position(&self) -> Option> { + let bounds = self.ui_screen.get_on_main(|ui_screen| ui_screen.nativeBounds()); + Some((bounds.origin.x as f64, bounds.origin.y as f64).into()) + } + + fn scale_factor(&self) -> f64 { + self.ui_screen.get_on_main(|ui_screen| ui_screen.nativeScale()) as f64 + } + + fn current_video_mode(&self) -> Option { + Some(run_on_main(|mtm| { + VideoModeHandle::new( + self.ui_screen(mtm).clone(), + self.ui_screen(mtm).currentMode().unwrap(), + mtm, + ) + .mode + })) + } + + fn video_modes(&self) -> Box> { + Box::new(self.video_modes()) + } +} + +impl Clone for MonitorHandle { + fn clone(&self) -> Self { + run_on_main(|mtm| Self { + ui_screen: MainThreadBound::new(self.ui_screen.get(mtm).clone(), mtm), + }) + } +} + +impl hash::Hash for MonitorHandle { + fn hash(&self, state: &mut H) { + // SAFETY: Only getting the pointer. + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + Retained::as_ptr(self.ui_screen.get(mtm)).hash(state); + } +} + +impl PartialEq for MonitorHandle { + fn eq(&self, other: &Self) -> bool { + // SAFETY: Only getting the pointer. + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + ptr::eq( + Retained::as_ptr(self.ui_screen.get(mtm)), + Retained::as_ptr(other.ui_screen.get(mtm)), + ) + } +} + +impl Eq for MonitorHandle {} + +impl PartialOrd for MonitorHandle { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for MonitorHandle { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + // SAFETY: Only getting the pointer. + // TODO: Make a better ordering + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + Retained::as_ptr(self.ui_screen.get(mtm)).cmp(&Retained::as_ptr(other.ui_screen.get(mtm))) + } +} + +impl fmt::Debug for MonitorHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MonitorHandle") + .field("name", &self.name()) + .field("position", &self.position()) + .field("scale_factor", &self.scale_factor()) + .finish_non_exhaustive() + } +} + +impl MonitorHandle { + pub(crate) fn new(ui_screen: Retained) -> Self { + // Holding `Retained` implies we're on the main thread. + let mtm = MainThreadMarker::new().unwrap(); + Self { ui_screen: MainThreadBound::new(ui_screen, mtm) } + } + + pub fn video_modes_handles(&self) -> impl Iterator + 'static { + run_on_main(|mtm| { + let ui_screen = self.ui_screen(mtm); + + ui_screen + .availableModes() + .into_iter() + .map(|mode| VideoModeHandle::new(ui_screen.clone(), mode, mtm)) + .collect::>() + .into_iter() + }) + } + + pub fn video_modes(&self) -> impl Iterator + 'static { + self.video_modes_handles().map(|handle| handle.mode) + } + + pub(crate) fn ui_screen(&self, mtm: MainThreadMarker) -> &Retained { + self.ui_screen.get(mtm) + } + + pub fn preferred_video_mode(&self) -> VideoMode { + run_on_main(|mtm| { + VideoModeHandle::new( + self.ui_screen(mtm).clone(), + self.ui_screen(mtm).preferredMode().unwrap(), + mtm, + ) + .mode + }) + } +} + +fn refresh_rate_millihertz(uiscreen: &UIScreen) -> Option { + let refresh_rate_millihertz: NSInteger = { + if available!(ios = 10.3, tvos = 10.2) { + uiscreen.maximumFramesPerSecond() + } else { + // https://developer.apple.com/library/archive/technotes/tn2460/_index.html + // https://en.wikipedia.org/wiki/IPad_Pro#Model_comparison + // + // All iOS devices support 60 fps, and on devices where `maximumFramesPerSecond` is not + // supported, they are all guaranteed to have 60hz refresh rates. This does not + // correctly handle external displays. ProMotion displays support 120fps, but they were + // introduced at the same time as the `maximumFramesPerSecond` API. + // + // FIXME: earlier OSs could calculate the refresh rate using + // `-[CADisplayLink duration]`. + tracing::warn!( + "`maximumFramesPerSecond` requires iOS 10.3+ or tvOS 10.2+. Defaulting to 60 fps" + ); + 60 + } + }; + + NonZeroU32::new(refresh_rate_millihertz as u32 * 1000) +} + +pub fn uiscreens(mtm: MainThreadMarker) -> VecDeque { + #[allow(deprecated)] + UIScreen::screens(mtm).into_iter().map(MonitorHandle::new).collect() +} + +#[cfg(test)] +mod tests { + use objc2_foundation::NSSet; + + use super::*; + + // Test that UIScreen pointer comparisons are correct. + #[test] + #[allow(deprecated)] + fn screen_comparisons() { + // Test code, doesn't matter that it's not thread safe + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + + assert!(ptr::eq(&*UIScreen::mainScreen(mtm), &*UIScreen::mainScreen(mtm))); + + let main = UIScreen::mainScreen(mtm); + assert!(UIScreen::screens(mtm).iter().any(|screen| ptr::eq(&*screen, &*main))); + + assert!( + NSSet::setWithArray(&UIScreen::screens(mtm)).containsObject(&UIScreen::mainScreen(mtm)) + ); + } +} diff --git a/patches/winit-uikit/src/view.rs b/patches/winit-uikit/src/view.rs new file mode 100644 index 0000000000..dd1e3d76c6 --- /dev/null +++ b/patches/winit-uikit/src/view.rs @@ -0,0 +1,749 @@ +#![allow(clippy::unnecessary_cast)] +use std::cell::{Cell, RefCell}; + +use dpi::PhysicalPosition; +use objc2::rc::Retained; +use objc2::runtime::{NSObjectProtocol, ProtocolObject}; +use objc2::{DefinedClass, MainThreadMarker, available, define_class, msg_send, sel}; +use objc2_core_foundation::{CGFloat, CGPoint, CGRect}; +use objc2_foundation::{NSObject, NSSet, NSString}; +use objc2_ui_kit::{ + UIEvent, UIForceTouchCapability, UIGestureRecognizer, UIGestureRecognizerDelegate, + UIGestureRecognizerState, UIKeyInput, UIPanGestureRecognizer, UIPinchGestureRecognizer, + UIResponder, UIRotationGestureRecognizer, UITapGestureRecognizer, UITextInputTraits, UITouch, + UITouchPhase, UITouchType, UITraitEnvironment, UIView, +}; +use tracing::{debug, debug_span, trace_span}; +use winit_core::event::{ + ButtonSource, ElementState, FingerId, Force, KeyEvent, PointerKind, PointerSource, + TabletToolAngle, TabletToolButton, TabletToolData, TabletToolKind, TouchPhase, WindowEvent, +}; +use winit_core::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKeyCode, PhysicalKey}; + +use super::app_state::{self, EventWrapper}; +use super::window::WinitUIWindow; + +pub struct WinitViewState { + pinch_gesture_recognizer: RefCell>>, + doubletap_gesture_recognizer: RefCell>>, + rotation_gesture_recognizer: RefCell>>, + pan_gesture_recognizer: RefCell>>, + + // for iOS delta references the start of the Gesture + rotation_last_delta: Cell, + pinch_last_delta: Cell, + pan_last_delta: Cell, + + primary_finger: Cell>, + fingers: Cell, +} + +define_class!( + #[unsafe(super(UIView, UIResponder, NSObject))] + #[name = "WinitUIView"] + #[ivars = WinitViewState] + pub(crate) struct WinitView; + + /// This documentation attribute makes rustfmt work for some reason? + impl WinitView { + #[unsafe(method(drawRect:))] + fn draw_rect(&self, rect: CGRect) { + let _entered = debug_span!("drawRect:").entered(); + let mtm = MainThreadMarker::new().unwrap(); + let window = self.window().unwrap(); + app_state::handle_nonuser_event(mtm, EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::RedrawRequested, + }); + let _: () = unsafe { msg_send![super(self), drawRect: rect] }; + } + + #[unsafe(method(layoutSubviews))] + fn layout_subviews(&self) { + let _entered = debug_span!("layoutSubviews").entered(); + let mtm = MainThreadMarker::new().unwrap(); + let _: () = unsafe { msg_send![super(self), layoutSubviews] }; + + let frame = self.frame(); + let scale_factor = self.contentScaleFactor() as f64; + let size = dpi::LogicalSize { + width: frame.size.width as f64, + height: frame.size.height as f64, + } + .to_physical(scale_factor); + + let window = self.window().unwrap(); + app_state::handle_nonuser_event(mtm, EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::SurfaceResized(size), + }); + } + + #[unsafe(method(setContentScaleFactor:))] + fn set_content_scale_factor(&self, untrusted_scale_factor: CGFloat) { + let _entered = debug_span!("setContentScaleFactor:").entered(); + let mtm = MainThreadMarker::new().unwrap(); + let _: () = + unsafe { msg_send![super(self), setContentScaleFactor: untrusted_scale_factor] }; + + // `window` is null when `setContentScaleFactor` is invoked prior to `[UIWindow + // makeKeyAndVisible]` at window creation time (either manually or internally by + // UIKit when the `UIView` is first created), in which case we send no events here + let window = match self.window() { + Some(window) => window, + None => return, + }; + // `setContentScaleFactor` may be called with a value of 0, which means "reset the + // content scale factor to a device-specific default value", so we can't use the + // parameter here. We can query the actual factor using the getter + let scale_factor = self.contentScaleFactor(); + assert!( + !scale_factor.is_nan() + && scale_factor.is_finite() + && scale_factor.is_sign_positive() + && scale_factor > 0.0, + "invalid scale_factor set on UIView", + ); + let scale_factor = scale_factor as f64; + let frame = self.frame(); + let size = dpi::LogicalSize { + width: frame.size.width as f64, + height: frame.size.height as f64, + }; + let window_id = window.id(); + app_state::handle_nonuser_events( + mtm, + std::iter::once(EventWrapper::ScaleFactorChanged(app_state::ScaleFactorChanged { + window, + scale_factor, + suggested_size: size.to_physical(scale_factor), + })) + .chain(std::iter::once(EventWrapper::Window { + window_id, + event: WindowEvent::SurfaceResized(size.to_physical(scale_factor)), + })), + ); + } + + #[unsafe(method(safeAreaInsetsDidChange))] + fn safe_area_changed(&self) { + let _entered = debug_span!("safeAreaInsetsDidChange").entered(); + debug!("safeAreaInsetsDidChange was called, requesting redraw"); + // When the safe area changes we want to make sure to emit a redraw event + self.setNeedsDisplay(); + } + + #[unsafe(method(touchesBegan:withEvent:))] + fn touches_began(&self, touches: &NSSet, _event: Option<&UIEvent>) { + let _entered = debug_span!("touchesBegan:withEvent:").entered(); + self.handle_touches(touches) + } + + #[unsafe(method(touchesMoved:withEvent:))] + fn touches_moved(&self, touches: &NSSet, _event: Option<&UIEvent>) { + let _entered = debug_span!("touchesMoved:withEvent:").entered(); + self.handle_touches(touches) + } + + #[unsafe(method(touchesEnded:withEvent:))] + fn touches_ended(&self, touches: &NSSet, _event: Option<&UIEvent>) { + let _entered = debug_span!("touchesEnded:withEvent:").entered(); + self.handle_touches(touches) + } + + #[unsafe(method(touchesCancelled:withEvent:))] + fn touches_cancelled(&self, touches: &NSSet, _event: Option<&UIEvent>) { + let _entered = debug_span!("touchesCancelled:withEvent:").entered(); + self.handle_touches(touches) + } + + #[unsafe(method(pinchGesture:))] + fn pinch_gesture(&self, recognizer: &UIPinchGestureRecognizer) { + let _entered = debug_span!("pinchGesture:").entered(); + let window = self.window().unwrap(); + + let (phase, delta) = match recognizer.state() { + UIGestureRecognizerState::Began => { + self.ivars().pinch_last_delta.set(recognizer.scale()); + (TouchPhase::Started, 0.0) + }, + UIGestureRecognizerState::Changed => { + let last_scale: f64 = self.ivars().pinch_last_delta.replace(recognizer.scale()); + (TouchPhase::Moved, recognizer.scale() - last_scale) + }, + UIGestureRecognizerState::Ended => { + let last_scale: f64 = self.ivars().pinch_last_delta.replace(0.0); + (TouchPhase::Moved, recognizer.scale() - last_scale) + }, + UIGestureRecognizerState::Cancelled | UIGestureRecognizerState::Failed => { + self.ivars().rotation_last_delta.set(0.0); + // Pass -delta so that action is reversed + (TouchPhase::Cancelled, -recognizer.scale()) + }, + state => panic!("unexpected recognizer state: {state:?}"), + }; + + let gesture_event = EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::PinchGesture { device_id: None, delta: delta as f64, phase }, + }; + + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event(mtm, gesture_event); + } + + #[unsafe(method(doubleTapGesture:))] + fn double_tap_gesture(&self, recognizer: &UITapGestureRecognizer) { + let _entered = debug_span!("doubleTapGesture:").entered(); + let window = self.window().unwrap(); + + if recognizer.state() == UIGestureRecognizerState::Ended { + let gesture_event = EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::DoubleTapGesture { device_id: None }, + }; + + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event(mtm, gesture_event); + } + } + + #[unsafe(method(rotationGesture:))] + fn rotation_gesture(&self, recognizer: &UIRotationGestureRecognizer) { + let _entered = debug_span!("rotationGesture:").entered(); + let window = self.window().unwrap(); + + let (phase, delta) = match recognizer.state() { + UIGestureRecognizerState::Began => { + self.ivars().rotation_last_delta.set(0.0); + + (TouchPhase::Started, 0.0) + }, + UIGestureRecognizerState::Changed => { + let last_rotation = + self.ivars().rotation_last_delta.replace(recognizer.rotation()); + + (TouchPhase::Moved, recognizer.rotation() - last_rotation) + }, + UIGestureRecognizerState::Ended => { + let last_rotation = self.ivars().rotation_last_delta.replace(0.0); + + (TouchPhase::Ended, recognizer.rotation() - last_rotation) + }, + UIGestureRecognizerState::Cancelled | UIGestureRecognizerState::Failed => { + self.ivars().rotation_last_delta.set(0.0); + + // Pass -delta so that action is reversed + (TouchPhase::Cancelled, -recognizer.rotation()) + }, + state => panic!("unexpected recognizer state: {state:?}"), + }; + + // Make delta negative to match macos, convert to degrees + let gesture_event = EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::RotationGesture { + device_id: None, + delta: -delta.to_degrees() as _, + phase, + }, + }; + + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event(mtm, gesture_event); + } + + #[unsafe(method(panGesture:))] + fn pan_gesture(&self, recognizer: &UIPanGestureRecognizer) { + let _entered = debug_span!("panGesture:").entered(); + let window = self.window().unwrap(); + + let translation = recognizer.translationInView(Some(self)); + + let (phase, dx, dy) = match recognizer.state() { + UIGestureRecognizerState::Began => { + self.ivars().pan_last_delta.set(translation); + + (TouchPhase::Started, 0.0, 0.0) + }, + UIGestureRecognizerState::Changed => { + let last_pan: CGPoint = self.ivars().pan_last_delta.replace(translation); + + let dx = translation.x - last_pan.x; + let dy = translation.y - last_pan.y; + + (TouchPhase::Moved, dx, dy) + }, + UIGestureRecognizerState::Ended => { + let last_pan: CGPoint = + self.ivars().pan_last_delta.replace(CGPoint { x: 0.0, y: 0.0 }); + + let dx = translation.x - last_pan.x; + let dy = translation.y - last_pan.y; + + (TouchPhase::Ended, dx, dy) + }, + UIGestureRecognizerState::Cancelled | UIGestureRecognizerState::Failed => { + let last_pan: CGPoint = + self.ivars().pan_last_delta.replace(CGPoint { x: 0.0, y: 0.0 }); + + // Pass -delta so that action is reversed + (TouchPhase::Cancelled, -last_pan.x, -last_pan.y) + }, + state => panic!("unexpected recognizer state: {state:?}"), + }; + + let gesture_event = EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::PanGesture { + device_id: None, + delta: PhysicalPosition::new(dx as _, dy as _), + phase, + }, + }; + + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event(mtm, gesture_event); + } + + #[unsafe(method(canBecomeFirstResponder))] + fn can_become_first_responder(&self) -> bool { + let _entered = trace_span!("canBecomeFirstResponder").entered(); + true + } + } + + unsafe impl NSObjectProtocol for WinitView {} + + unsafe impl UIGestureRecognizerDelegate for WinitView { + #[unsafe(method(gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:))] + fn should_recognize_simultaneously( + &self, + _gesture_recognizer: &UIGestureRecognizer, + _other_gesture_recognizer: &UIGestureRecognizer, + ) -> bool { + let _entered = trace_span!( + "gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:" + ) + .entered(); + true + } + } + + unsafe impl UITextInputTraits for WinitView {} + + unsafe impl UIKeyInput for WinitView { + #[unsafe(method(hasText))] + fn has_text(&self) -> bool { + let _entered = debug_span!("hasText").entered(); + true + } + + #[unsafe(method(insertText:))] + fn insert_text(&self, text: &NSString) { + let _entered = debug_span!("insertText:").entered(); + self.handle_insert_text(text) + } + + #[unsafe(method(deleteBackward))] + fn delete_backward(&self) { + let _entered = debug_span!("deleteBackward").entered(); + self.handle_delete_backward() + } + } +); + +impl WinitView { + pub(crate) fn new( + mtm: MainThreadMarker, + scale_factor: Option, + frame: CGRect, + ) -> Retained { + let this = mtm.alloc().set_ivars(WinitViewState { + pinch_gesture_recognizer: RefCell::new(None), + doubletap_gesture_recognizer: RefCell::new(None), + rotation_gesture_recognizer: RefCell::new(None), + pan_gesture_recognizer: RefCell::new(None), + + rotation_last_delta: Cell::new(0.0), + pinch_last_delta: Cell::new(0.0), + pan_last_delta: Cell::new(CGPoint { x: 0.0, y: 0.0 }), + + primary_finger: Cell::new(None), + fingers: Cell::new(0), + }); + let this: Retained = unsafe { msg_send![super(this), initWithFrame: frame] }; + + this.setMultipleTouchEnabled(true); + + if let Some(scale_factor) = scale_factor { + this.setContentScaleFactor(scale_factor as _); + } + + this + } + + fn window(&self) -> Option> { + // `WinitView`s should always be installed in a `WinitUIWindow` + (**self).window().map(|window| window.downcast().unwrap()) + } + + pub(crate) fn recognize_pinch_gesture(&self, should_recognize: bool) { + let mtm = MainThreadMarker::from(self); + if should_recognize { + if self.ivars().pinch_gesture_recognizer.borrow().is_none() { + let pinch = unsafe { + UIPinchGestureRecognizer::initWithTarget_action( + mtm.alloc(), + Some(self), + Some(sel!(pinchGesture:)), + ) + }; + pinch.setDelegate(Some(ProtocolObject::from_ref(self))); + self.addGestureRecognizer(&pinch); + self.ivars().pinch_gesture_recognizer.replace(Some(pinch)); + } + } else if let Some(recognizer) = self.ivars().pinch_gesture_recognizer.take() { + self.removeGestureRecognizer(&recognizer); + } + } + + pub(crate) fn recognize_pan_gesture( + &self, + should_recognize: bool, + minimum_number_of_touches: u8, + maximum_number_of_touches: u8, + ) { + let mtm = MainThreadMarker::from(self); + if should_recognize { + if self.ivars().pan_gesture_recognizer.borrow().is_none() { + let pan = unsafe { + UIPanGestureRecognizer::initWithTarget_action( + mtm.alloc(), + Some(self), + Some(sel!(panGesture:)), + ) + }; + pan.setDelegate(Some(ProtocolObject::from_ref(self))); + pan.setMinimumNumberOfTouches(minimum_number_of_touches as _); + pan.setMaximumNumberOfTouches(maximum_number_of_touches as _); + self.addGestureRecognizer(&pan); + self.ivars().pan_gesture_recognizer.replace(Some(pan)); + } + } else if let Some(recognizer) = self.ivars().pan_gesture_recognizer.take() { + self.removeGestureRecognizer(&recognizer); + } + } + + pub(crate) fn recognize_doubletap_gesture(&self, should_recognize: bool) { + let mtm = MainThreadMarker::from(self); + if should_recognize { + if self.ivars().doubletap_gesture_recognizer.borrow().is_none() { + let tap = unsafe { + UITapGestureRecognizer::initWithTarget_action( + mtm.alloc(), + Some(self), + Some(sel!(doubleTapGesture:)), + ) + }; + tap.setDelegate(Some(ProtocolObject::from_ref(self))); + tap.setNumberOfTapsRequired(2); + tap.setNumberOfTouchesRequired(1); + self.addGestureRecognizer(&tap); + self.ivars().doubletap_gesture_recognizer.replace(Some(tap)); + } + } else if let Some(recognizer) = self.ivars().doubletap_gesture_recognizer.take() { + self.removeGestureRecognizer(&recognizer); + } + } + + pub(crate) fn recognize_rotation_gesture(&self, should_recognize: bool) { + let mtm = MainThreadMarker::from(self); + if should_recognize { + if self.ivars().rotation_gesture_recognizer.borrow().is_none() { + let rotation = unsafe { + UIRotationGestureRecognizer::initWithTarget_action( + mtm.alloc(), + Some(self), + Some(sel!(rotationGesture:)), + ) + }; + rotation.setDelegate(Some(ProtocolObject::from_ref(self))); + self.addGestureRecognizer(&rotation); + self.ivars().rotation_gesture_recognizer.replace(Some(rotation)); + } + } else if let Some(recognizer) = self.ivars().rotation_gesture_recognizer.take() { + self.removeGestureRecognizer(&recognizer); + } + } + + fn handle_touches(&self, touches: &NSSet) { + let window = self.window().unwrap(); + let mut touch_events = Vec::new(); + for touch in touches { + let logical_location = touch.locationInView(None); + let touch_type = touch.r#type(); + let force = if available!(ios = 9.0, tvos = 9.0, visionos = 1.0) { + let use_force = match touch_type { + UITouchType::Pencil => true, + _ => { + let trait_collection = self.traitCollection(); + trait_collection.forceTouchCapability() == UIForceTouchCapability::Available + }, + }; + + if use_force { + let force = touch.force(); + let max_possible_force = touch.maximumPossibleForce(); + Some(Force::Calibrated { + force: force as _, + max_possible_force: max_possible_force as _, + }) + } else { + None + } + } else { + None + }; + let touch_id = Retained::as_ptr(&touch) as usize; + let phase = touch.phase(); + let position = { + let scale_factor = self.contentScaleFactor(); + PhysicalPosition::from_logical::<(f64, f64), f64>( + (logical_location.x as _, logical_location.y as _), + scale_factor as f64, + ) + }; + let window_id = window.id(); + let finger_id = FingerId::from_raw(touch_id); + + let ivars = self.ivars(); + + match phase { + UITouchPhase::Began => { + let primary = if let UITouchType::Pencil = touch_type { + true + } else { + ivars.fingers.set(ivars.fingers.get() + 1); + // Keep the primary finger around until we clear all the fingers to + // recognize it when user briefly removes it. + match ivars.primary_finger.get() { + Some(primary_id) => primary_id == finger_id, + None => { + debug_assert_eq!( + ivars.fingers.get(), + 1, + "number of fingers were not counted correctly" + ); + ivars.primary_finger.set(Some(finger_id)); + true + }, + } + }; + + touch_events.push(EventWrapper::Window { + window_id, + event: WindowEvent::PointerEntered { + device_id: None, + primary, + position, + kind: if let UITouchType::Pencil = touch_type { + PointerKind::TabletTool(TabletToolKind::Pencil) + } else { + PointerKind::Touch(finger_id) + }, + }, + }); + touch_events.push(EventWrapper::Window { + window_id, + event: WindowEvent::PointerButton { + device_id: None, + primary, + state: ElementState::Pressed, + position, + button: if let UITouchType::Pencil = touch_type { + let tool_data = self.tablet_tool_data_for_pencil(&touch); + ButtonSource::TabletTool { + kind: TabletToolKind::Pencil, + button: TabletToolButton::Contact, + data: tool_data, + } + } else { + ButtonSource::Touch { finger_id, force } + }, + is_macos_activation_click: false, + }, + }); + }, + UITouchPhase::Moved => { + let (primary, source) = if let UITouchType::Pencil = touch_type { + let tool_data = self.tablet_tool_data_for_pencil(&touch); + (true, PointerSource::TabletTool { + kind: TabletToolKind::Pencil, + data: tool_data, + }) + } else { + (ivars.primary_finger.get().unwrap() == finger_id, PointerSource::Touch { + finger_id, + force, + }) + }; + + touch_events.push(EventWrapper::Window { + window_id, + event: WindowEvent::PointerMoved { + device_id: None, + primary, + position, + source, + }, + }); + }, + // 2 is UITouchPhase::Stationary and is not expected here + UITouchPhase::Ended | UITouchPhase::Cancelled => { + let primary = if let UITouchType::Pencil = touch_type { + true + } else { + ivars.fingers.set(ivars.fingers.get() - 1); + let primary = ivars.primary_finger.get().unwrap() == finger_id; + if ivars.fingers.get() == 0 { + ivars.primary_finger.set(None); + } + primary + }; + + if let UITouchPhase::Ended = phase { + touch_events.push(EventWrapper::Window { + window_id, + event: WindowEvent::PointerButton { + device_id: None, + primary, + state: ElementState::Released, + position, + button: if let UITouchType::Pencil = touch_type { + let tool_data = self.tablet_tool_data_for_pencil(&touch); + ButtonSource::TabletTool { + kind: TabletToolKind::Pencil, + button: TabletToolButton::Contact, + data: tool_data, + } + } else { + ButtonSource::Touch { finger_id, force } + }, + is_macos_activation_click: false, + }, + }); + } + + touch_events.push(EventWrapper::Window { + window_id, + event: WindowEvent::PointerLeft { + device_id: None, + primary, + position: Some(position), + kind: if let UITouchType::Pencil = touch_type { + PointerKind::TabletTool(TabletToolKind::Pencil) + } else { + PointerKind::Touch(finger_id) + }, + }, + }); + }, + _ => panic!("unexpected touch phase: {phase:?}"), + } + } + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_events(mtm, touch_events); + } + + fn tablet_tool_data_for_pencil(&self, touch: &UITouch) -> TabletToolData { + let force = if available!(ios = 9.0, tvos = 9.0, visionos = 1.0) { + let force_val = touch.force(); + let max_force = touch.maximumPossibleForce(); + Some(Force::Calibrated { force: force_val as _, max_possible_force: max_force as _ }) + } else { + None + }; + + let angle = if available!(ios = 9.1, tvos = 9.0, visionos = 1.0) { + let altitude = touch.altitudeAngle(); + let azimuth = touch.azimuthAngleInView(Some(self)); + Some(TabletToolAngle { altitude: altitude as _, azimuth: azimuth as _ }) + } else { + None + }; + + TabletToolData { + force, + tangential_force: None, // iOS doesn't provide barrel pressure + twist: None, // iOS doesn't provide rotation/twist + tilt: None, // Will be calculated from angle if needed + angle, + } + } + + fn handle_insert_text(&self, text: &NSString) { + let window = self.window().unwrap(); + let window_id = window.id(); + let mtm = MainThreadMarker::new().unwrap(); + // send individual events for each character + app_state::handle_nonuser_events( + mtm, + text.to_string().chars().flat_map(|c| { + let text = smol_str::SmolStr::from_iter([c]); + // Emit both press and release events + [ElementState::Pressed, ElementState::Released].map(|state| EventWrapper::Window { + window_id, + event: WindowEvent::KeyboardInput { + device_id: None, + event: KeyEvent { + text: if state == ElementState::Pressed { + Some(text.clone()) + } else { + None + }, + state, + location: KeyLocation::Standard, + repeat: false, + logical_key: Key::Character(text.clone()), + physical_key: PhysicalKey::Unidentified(NativeKeyCode::Unidentified), + text_with_all_modifiers: if state == ElementState::Pressed { + Some(text.clone()) + } else { + None + }, + key_without_modifiers: Key::Character(text.clone()), + }, + is_synthetic: false, + }, + }) + }), + ); + } + + fn handle_delete_backward(&self) { + let window = self.window().unwrap(); + let window_id = window.id(); + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_events( + mtm, + [ElementState::Pressed, ElementState::Released].map(|state| EventWrapper::Window { + window_id, + event: WindowEvent::KeyboardInput { + device_id: None, + event: KeyEvent { + state, + logical_key: Key::Named(NamedKey::Backspace), + physical_key: PhysicalKey::Code(KeyCode::Backspace), + repeat: false, + location: KeyLocation::Standard, + text: None, + text_with_all_modifiers: None, + key_without_modifiers: Key::Named(NamedKey::Backspace), + }, + is_synthetic: false, + }, + }), + ); + } +} diff --git a/patches/winit-uikit/src/view_controller.rs b/patches/winit-uikit/src/view_controller.rs new file mode 100644 index 0000000000..f921de6dcd --- /dev/null +++ b/patches/winit-uikit/src/view_controller.rs @@ -0,0 +1,167 @@ +use std::cell::Cell; + +use objc2::rc::Retained; +use objc2::{DefinedClass, MainThreadMarker, available, define_class, msg_send}; +use objc2_foundation::NSObject; +use objc2_ui_kit::{ + UIDevice, UIInterfaceOrientationMask, UIRectEdge, UIResponder, UIStatusBarStyle, + UIUserInterfaceIdiom, UIView, UIViewController, +}; +use tracing::trace_span; + +use crate::{ScreenEdge, StatusBarStyle, ValidOrientations, WindowAttributesIos}; + +pub struct ViewControllerState { + prefers_status_bar_hidden: Cell, + preferred_status_bar_style: Cell, + prefers_home_indicator_auto_hidden: Cell, + supported_orientations: Cell, + preferred_screen_edges_deferring_system_gestures: Cell, +} + +define_class!( + #[unsafe(super(UIViewController, UIResponder, NSObject))] + #[name = "WinitUIViewController"] + #[ivars = ViewControllerState] + pub(crate) struct WinitViewController; + + /// This documentation attribute makes rustfmt work for some reason? + impl WinitViewController { + #[unsafe(method(shouldAutorotate))] + fn should_autorotate(&self) -> bool { + let _entered = trace_span!("shouldAutorotate").entered(); + true + } + + #[unsafe(method(prefersStatusBarHidden))] + fn prefers_status_bar_hidden(&self) -> bool { + let _entered = trace_span!("prefersStatusBarHidden").entered(); + self.ivars().prefers_status_bar_hidden.get() + } + + #[unsafe(method(preferredStatusBarStyle))] + fn preferred_status_bar_style(&self) -> UIStatusBarStyle { + let _entered = trace_span!("preferredStatusBarStyle").entered(); + self.ivars().preferred_status_bar_style.get() + } + + #[unsafe(method(prefersHomeIndicatorAutoHidden))] + fn prefers_home_indicator_auto_hidden(&self) -> bool { + let _entered = trace_span!("prefersHomeIndicatorAutoHidden").entered(); + self.ivars().prefers_home_indicator_auto_hidden.get() + } + + #[unsafe(method(supportedInterfaceOrientations))] + fn supported_orientations(&self) -> UIInterfaceOrientationMask { + let _entered = trace_span!("supportedInterfaceOrientations").entered(); + self.ivars().supported_orientations.get() + } + + #[unsafe(method(preferredScreenEdgesDeferringSystemGestures))] + fn preferred_screen_edges_deferring_system_gestures(&self) -> UIRectEdge { + let _entered = trace_span!("preferredScreenEdgesDeferringSystemGestures").entered(); + self.ivars().preferred_screen_edges_deferring_system_gestures.get() + } + } +); + +impl WinitViewController { + pub(crate) fn set_prefers_status_bar_hidden(&self, val: bool) { + self.ivars().prefers_status_bar_hidden.set(val); + self.setNeedsStatusBarAppearanceUpdate(); + } + + pub(crate) fn set_preferred_status_bar_style(&self, val: StatusBarStyle) { + let val = match val { + StatusBarStyle::Default => UIStatusBarStyle::Default, + StatusBarStyle::LightContent => UIStatusBarStyle::LightContent, + StatusBarStyle::DarkContent => UIStatusBarStyle::DarkContent, + }; + self.ivars().preferred_status_bar_style.set(val); + self.setNeedsStatusBarAppearanceUpdate(); + } + + pub(crate) fn set_prefers_home_indicator_auto_hidden(&self, val: bool) { + self.ivars().prefers_home_indicator_auto_hidden.set(val); + if available!(ios = 11.0, visionos = 1.0) { + self.setNeedsUpdateOfHomeIndicatorAutoHidden(); + } else { + tracing::warn!( + "`setNeedsUpdateOfHomeIndicatorAutoHidden` requires iOS 11.0+ or visionOS. \ + Ignoring" + ); + } + } + + pub(crate) fn set_preferred_screen_edges_deferring_system_gestures(&self, val: ScreenEdge) { + let val = { + assert_eq!(val.bits() & !ScreenEdge::ALL.bits(), 0, "invalid `ScreenEdge`"); + UIRectEdge(val.bits().into()) + }; + self.ivars().preferred_screen_edges_deferring_system_gestures.set(val); + if available!(ios = 11.0, visionos = 1.0) { + self.setNeedsUpdateOfScreenEdgesDeferringSystemGestures(); + } else { + tracing::warn!( + "`setNeedsUpdateOfScreenEdgesDeferringSystemGestures` requires iOS 11.0+ or \ + visionOS. Ignoring" + ); + } + } + + pub(crate) fn set_supported_interface_orientations( + &self, + mtm: MainThreadMarker, + valid_orientations: ValidOrientations, + ) { + let mask = match (valid_orientations, UIDevice::currentDevice(mtm).userInterfaceIdiom()) { + (ValidOrientations::LandscapeAndPortrait, UIUserInterfaceIdiom::Phone) => { + UIInterfaceOrientationMask::AllButUpsideDown + }, + (ValidOrientations::LandscapeAndPortrait, _) => UIInterfaceOrientationMask::All, + (ValidOrientations::Landscape, _) => UIInterfaceOrientationMask::Landscape, + (ValidOrientations::Portrait, UIUserInterfaceIdiom::Phone) => { + UIInterfaceOrientationMask::Portrait + }, + (ValidOrientations::Portrait, _) => { + UIInterfaceOrientationMask::Portrait + | UIInterfaceOrientationMask::PortraitUpsideDown + }, + }; + self.ivars().supported_orientations.set(mask); + #[allow(deprecated)] + UIViewController::attemptRotationToDeviceOrientation(mtm); + } + + pub(crate) fn new( + mtm: MainThreadMarker, + ios_attributes: &WindowAttributesIos, + view: &UIView, + ) -> Retained { + // These are set properly below, we just to set them to something in the meantime. + let this = mtm.alloc().set_ivars(ViewControllerState { + prefers_status_bar_hidden: Cell::new(false), + preferred_status_bar_style: Cell::new(UIStatusBarStyle::Default), + prefers_home_indicator_auto_hidden: Cell::new(false), + supported_orientations: Cell::new(UIInterfaceOrientationMask::All), + preferred_screen_edges_deferring_system_gestures: Cell::new(UIRectEdge::empty()), + }); + let this: Retained = unsafe { msg_send![super(this), init] }; + + this.set_prefers_status_bar_hidden(ios_attributes.prefers_status_bar_hidden); + + this.set_preferred_status_bar_style(ios_attributes.preferred_status_bar_style); + + this.set_supported_interface_orientations(mtm, ios_attributes.valid_orientations); + + this.set_prefers_home_indicator_auto_hidden(ios_attributes.prefers_home_indicator_hidden); + + this.set_preferred_screen_edges_deferring_system_gestures( + ios_attributes.preferred_screen_edges_deferring_system_gestures, + ); + + this.setView(Some(view)); + + this + } +} diff --git a/patches/winit-uikit/src/window.rs b/patches/winit-uikit/src/window.rs new file mode 100644 index 0000000000..5e9ecb40fc --- /dev/null +++ b/patches/winit-uikit/src/window.rs @@ -0,0 +1,931 @@ +#![allow(clippy::unnecessary_cast)] + +use std::collections::VecDeque; +use std::sync::{Arc, Mutex}; + +use dispatch2::MainThreadBound; +use dpi::{ + LogicalInsets, LogicalPosition, LogicalSize, PhysicalInsets, PhysicalPosition, PhysicalSize, + Position, Size, +}; +use objc2::rc::Retained; +use objc2::{MainThreadMarker, available, class, define_class, msg_send}; +use objc2_core_foundation::{CGFloat, CGPoint, CGRect, CGSize}; +use objc2_foundation::{NSObject, NSObjectProtocol}; +use objc2_ui_kit::{ + UIApplication, UICoordinateSpace, UIEdgeInsets, UIResponder, UIScreen, + UIScreenOverscanCompensation, UIViewController, UIWindow, UIWindowScene, +}; +use tracing::{debug, debug_span, warn}; +use winit_core::cursor::Cursor; +use winit_core::error::{NotSupportedError, RequestError}; +use winit_core::event::WindowEvent; +use winit_core::icon::Icon; +use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; +use winit_core::window::{ + CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, + UserAttentionType, Window as CoreWindow, WindowAttributes, WindowButtons, WindowId, + WindowLevel, WindowType, +}; + +use super::app_state::EventWrapper; +use super::view::WinitView; +use super::view_controller::WinitViewController; +use super::{app_state, monitor}; +use crate::event_loop::ActiveEventLoop; +use crate::monitor::MonitorHandle; +use crate::{ScreenEdge, StatusBarStyle, ValidOrientations, WindowAttributesIos}; + +define_class!( + #[unsafe(super(UIWindow, UIResponder, NSObject))] + #[name = "WinitUIWindow"] + #[derive(Debug, PartialEq, Eq, Hash)] + pub(crate) struct WinitUIWindow; + + /// This documentation attribute makes rustfmt work for some reason? + impl WinitUIWindow { + #[unsafe(method(becomeKeyWindow))] + fn become_key_window(&self) { + let _entered = debug_span!("becomeKeyWindow").entered(); + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event(mtm, EventWrapper::Window { + window_id: self.id(), + event: WindowEvent::Focused(true), + }); + let _: () = unsafe { msg_send![super(self), becomeKeyWindow] }; + } + + #[unsafe(method(resignKeyWindow))] + fn resign_key_window(&self) { + let _entered = debug_span!("resignKeyWindow").entered(); + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event(mtm, EventWrapper::Window { + window_id: self.id(), + event: WindowEvent::Focused(false), + }); + let _: () = unsafe { msg_send![super(self), resignKeyWindow] }; + } + } +); + +impl WinitUIWindow { + pub(crate) fn new( + mtm: MainThreadMarker, + window_attributes: &WindowAttributes, + frame: CGRect, + view_controller: &UIViewController, + ) -> Retained { + // NOTE: This should only be created after the application has started launching, + // (`application:willFinishLaunchingWithOptions:` at the earliest), otherwise you'll run + // into very confusing issues with the window not being properly activated. + // + // Winit ensures this by not allowing access to `ActiveEventLoop` before handling events. + let this: Retained = unsafe { msg_send![mtm.alloc(), initWithFrame: frame] }; + + this.setRootViewController(Some(view_controller)); + + // Windows in apps that adopt the scene life cycle are only shown once attached to a scene. + if available!(ios = 13.0, tvos = 13.0, visionos = 1.0) && this.windowScene().is_none() { + let scene = UIApplication::sharedApplication(mtm) + .connectedScenes() + .into_iter() + .find_map(|scene| scene.downcast::().ok()); + this.setWindowScene(scene.as_deref()); + } + + match window_attributes.fullscreen.clone() { + Some(Fullscreen::Exclusive(monitor, ref video_mode)) => { + let monitor = monitor.cast_ref::().unwrap(); + let screen = monitor.ui_screen(mtm); + if let Some(video_mode) = + monitor.video_modes_handles().find(|mode| &mode.mode == video_mode) + { + screen.setCurrentMode(Some(video_mode.screen_mode(mtm))); + } + this.setScreen(screen); + }, + Some(Fullscreen::Borderless(Some(ref monitor))) => { + let monitor = monitor.cast_ref::().unwrap(); + let screen = monitor.ui_screen(mtm); + this.setScreen(screen); + }, + _ => (), + } + + this + } + + pub(crate) fn id(&self) -> WindowId { + WindowId::from_raw(self as *const Self as usize) + } +} + +pub struct Inner { + window: Retained, + view_controller: Retained, + view: Retained, + gl_or_metal_backed: bool, + ime_capabilities: Mutex>, +} + +impl Inner { + pub fn set_title(&self, _title: &str) { + debug!("`Window::set_title` is ignored on iOS") + } + + pub fn set_transparent(&self, _transparent: bool) { + debug!("`Window::set_transparent` is ignored on iOS") + } + + pub fn set_blur(&self, _blur: bool) { + debug!("`Window::set_blur` is ignored on iOS") + } + + pub fn set_visible(&self, visible: bool) { + self.window.setHidden(!visible) + } + + pub fn is_visible(&self) -> Option { + warn!("`Window::is_visible` is ignored on iOS"); + None + } + + pub fn request_redraw(&self) { + if self.gl_or_metal_backed { + let mtm = MainThreadMarker::new().unwrap(); + // `setNeedsDisplay` does nothing on UIViews which are directly backed by CAEAGLLayer or + // CAMetalLayer. Ordinarily the OS sets up a bunch of UIKit state before + // calling drawRect: on a UIView, but when using raw or gl/metal for drawing + // this work is completely avoided. + // + // The docs for `setNeedsDisplay` don't mention `CAMetalLayer`; however, this has been + // confirmed via testing. + // + // https://developer.apple.com/documentation/uikit/uiview/1622437-setneedsdisplay?language=objc + app_state::queue_gl_or_metal_redraw(mtm, self.window.clone()); + } else { + self.view.setNeedsDisplay(); + } + } + + pub fn pre_present_notify(&self) {} + + pub fn surface_position(&self) -> PhysicalPosition { + let view_position = self.view.frame().origin; + let position = self.window.convertPoint_fromView(view_position, Some(&self.view)); + let position = LogicalPosition::new(position.x, position.y); + position.to_physical(self.scale_factor()) + } + + pub fn outer_position(&self) -> Result, RequestError> { + let screen_frame = self.screen_frame(); + let position = + LogicalPosition { x: screen_frame.origin.x as f64, y: screen_frame.origin.y as f64 }; + Ok(position.to_physical(self.scale_factor())) + } + + pub fn set_outer_position(&self, physical_position: Position) { + let scale_factor = self.scale_factor(); + let position = physical_position.to_logical::(scale_factor); + let screen_frame = self.screen_frame(); + let new_screen_frame = CGRect { + origin: CGPoint { x: position.x as _, y: position.y as _ }, + size: screen_frame.size, + }; + let bounds = self.rect_from_screen_space(new_screen_frame); + self.window.setBounds(bounds); + } + + pub fn surface_size(&self) -> PhysicalSize { + let frame = self.view.frame(); + let size = LogicalSize::new(frame.size.width, frame.size.height); + size.to_physical(self.scale_factor()) + } + + pub fn outer_size(&self) -> PhysicalSize { + let frame = self.window.frame(); + let size = LogicalSize::new(frame.size.width, frame.size.height); + size.to_physical(self.scale_factor()) + } + + pub fn request_surface_size(&self, _size: Size) -> Option> { + Some(self.surface_size()) + } + + pub fn safe_area(&self) -> PhysicalInsets { + let insets = if available!(ios = 11.0, tvos = 11.0, visionos = 1.0) { + self.view.safeAreaInsets() + } else { + // Assume the status bar frame is the only thing that obscures the view + let app = UIApplication::sharedApplication(MainThreadMarker::new().unwrap()); + #[allow(deprecated)] + let status_bar_frame = app.statusBarFrame(); + UIEdgeInsets { top: status_bar_frame.size.height, left: 0.0, bottom: 0.0, right: 0.0 } + }; + let insets = LogicalInsets::new(insets.top, insets.left, insets.bottom, insets.right); + insets.to_physical(self.scale_factor()) + } + + pub fn set_min_surface_size(&self, _dimensions: Option) { + warn!("`Window::set_min_surface_size` is ignored on iOS") + } + + pub fn set_max_surface_size(&self, _dimensions: Option) { + warn!("`Window::set_max_surface_size` is ignored on iOS") + } + + pub fn surface_resize_increments(&self) -> Option> { + None + } + + #[inline] + pub fn set_surface_resize_increments(&self, _increments: Option) { + warn!("`Window::set_surface_resize_increments` is ignored on iOS") + } + + pub fn set_resizable(&self, _resizable: bool) { + warn!("`Window::set_resizable` is ignored on iOS") + } + + pub fn is_resizable(&self) -> bool { + warn!("`Window::is_resizable` is ignored on iOS"); + false + } + + #[inline] + pub fn set_enabled_buttons(&self, _buttons: WindowButtons) { + warn!("`Window::set_enabled_buttons` is ignored on iOS"); + } + + #[inline] + pub fn enabled_buttons(&self) -> WindowButtons { + warn!("`Window::enabled_buttons` is ignored on iOS"); + WindowButtons::all() + } + + pub fn scale_factor(&self) -> f64 { + self.view.contentScaleFactor() as _ + } + + pub fn set_cursor(&self, _cursor: Cursor) { + debug!("`Window::set_cursor` ignored on iOS") + } + + pub fn set_cursor_position(&self, _position: Position) -> Result<(), NotSupportedError> { + Err(NotSupportedError::new("set_cursor_position is not supported")) + } + + pub fn set_cursor_grab(&self, _: CursorGrabMode) -> Result<(), NotSupportedError> { + Err(NotSupportedError::new("set_cursor_grab is not supported")) + } + + pub fn set_cursor_visible(&self, _visible: bool) { + debug!("`Window::set_cursor_visible` is ignored on iOS") + } + + pub fn drag_window(&self) -> Result<(), NotSupportedError> { + Err(NotSupportedError::new("drag_window is not supported")) + } + + pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), NotSupportedError> { + Err(NotSupportedError::new("drag_resize_window is not supported")) + } + + #[inline] + pub fn show_window_menu(&self, _position: Position) {} + + pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), NotSupportedError> { + Err(NotSupportedError::new("set_cursor_hittest is not supported")) + } + + pub fn set_minimized(&self, _minimized: bool) { + warn!("`Window::set_minimized` is ignored on iOS") + } + + pub fn is_minimized(&self) -> Option { + warn!("`Window::is_minimized` is ignored on iOS"); + None + } + + pub fn set_maximized(&self, _maximized: bool) { + warn!("`Window::set_maximized` is ignored on iOS") + } + + pub fn is_maximized(&self) -> bool { + warn!("`Window::is_maximized` is ignored on iOS"); + false + } + + pub(crate) fn set_fullscreen(&self, monitor: Option) { + let mtm = MainThreadMarker::new().unwrap(); + let uiscreen = match &monitor { + Some(Fullscreen::Exclusive(monitor, video_mode)) => { + let monitor = monitor.cast_ref::().unwrap(); + let uiscreen = monitor.ui_screen(mtm); + if let Some(video_mode) = + monitor.video_modes_handles().find(|mode| &mode.mode == video_mode) + { + uiscreen.setCurrentMode(Some(video_mode.screen_mode(mtm))); + } + uiscreen.clone() + }, + Some(Fullscreen::Borderless(Some(monitor))) => { + monitor.cast_ref::().unwrap().ui_screen(mtm).clone() + }, + Some(_) => self.current_monitor_inner().ui_screen(mtm).clone(), + None => { + warn!("`Window::set_fullscreen(None)` ignored on iOS"); + return; + }, + }; + + // this is pretty slow on iOS, so avoid doing it if we can + let current = self.window.screen(); + if uiscreen != current { + self.window.setScreen(&uiscreen); + } + + let bounds = uiscreen.bounds(); + self.window.setFrame(bounds); + + // For external displays, we must disable overscan compensation or + // the displayed image will have giant black bars surrounding it on + // each side + uiscreen.setOverscanCompensation(UIScreenOverscanCompensation::None); + } + + pub(crate) fn fullscreen(&self) -> Option { + let mtm = MainThreadMarker::new().unwrap(); + let monitor = self.current_monitor_inner(); + let uiscreen = monitor.ui_screen(mtm); + let screen_space_bounds = self.screen_frame(); + let screen_bounds = uiscreen.bounds(); + + // TODO: track fullscreen instead of relying on brittle float comparisons + if screen_space_bounds.origin.x == screen_bounds.origin.x + && screen_space_bounds.origin.y == screen_bounds.origin.y + && screen_space_bounds.size.width == screen_bounds.size.width + && screen_space_bounds.size.height == screen_bounds.size.height + { + Some(Fullscreen::Borderless(Some(CoreMonitorHandle(Arc::new(monitor))))) + } else { + None + } + } + + pub fn set_decorations(&self, _decorations: bool) {} + + pub fn is_decorated(&self) -> bool { + true + } + + pub fn set_window_level(&self, _level: WindowLevel) { + warn!("`Window::set_window_level` is ignored on iOS") + } + + pub fn set_window_icon(&self, _icon: Option) { + warn!("`Window::set_window_icon` is ignored on iOS") + } + + /// Show / hide the keyboard. To show the keyboard, we call `becomeFirstResponder`, + /// requesting focus for the [WinitView]. Since [WinitView] implements + /// [objc2_ui_kit::UIKeyInput], the keyboard will be shown. + /// + fn request_ime_update(&self, request: ImeRequest) -> Result<(), ImeRequestError> { + let mut current_caps = self.ime_capabilities.lock().unwrap(); + match request { + ImeRequest::Enable(enable) => { + let (capabilities, _) = enable.into_raw(); + if current_caps.is_some() { + return Err(ImeRequestError::AlreadyEnabled); + } + *current_caps = Some(capabilities); + + self.view.becomeFirstResponder(); + }, + ImeRequest::Update(_) => { + if current_caps.is_none() { + return Err(ImeRequestError::NotEnabled); + } + }, + ImeRequest::Disable => { + *current_caps = None; + self.view.resignFirstResponder(); + }, + _ => return Err(ImeRequestError::NotSupported), + } + + Ok(()) + } + + fn ime_capabilities(&self) -> Option { + *self.ime_capabilities.lock().unwrap() + } + + pub fn focus_window(&self) { + warn!("`Window::set_focus` is ignored on iOS") + } + + pub fn request_user_attention(&self, _request_type: Option) { + warn!("`Window::request_user_attention` is ignored on iOS") + } + + // Allow directly accessing the current monitor internally without unwrapping. + fn current_monitor_inner(&self) -> MonitorHandle { + MonitorHandle::new(self.window.screen()) + } + + pub fn current_monitor(&self) -> Option { + Some(self.current_monitor_inner()) + } + + pub fn available_monitors(&self) -> VecDeque { + monitor::uiscreens(MainThreadMarker::new().unwrap()) + } + + pub fn primary_monitor(&self) -> Option { + #[allow(deprecated)] + Some(MonitorHandle::new(UIScreen::mainScreen(MainThreadMarker::new().unwrap()))) + } + + pub fn id(&self) -> WindowId { + self.window.id() + } + + pub fn raw_window_handle_rwh_06(&self) -> rwh_06::RawWindowHandle { + let mut window_handle = rwh_06::UiKitWindowHandle::new({ + let ui_view = Retained::as_ptr(&self.view) as _; + std::ptr::NonNull::new(ui_view).expect("Retained should never be null") + }); + window_handle.ui_view_controller = + std::ptr::NonNull::new(Retained::as_ptr(&self.view_controller) as _); + rwh_06::RawWindowHandle::UiKit(window_handle) + } + + pub fn theme(&self) -> Option { + warn!("`Window::theme` is ignored on iOS"); + None + } + + pub fn set_content_protected(&self, _protected: bool) {} + + pub fn has_focus(&self) -> bool { + self.window.isKeyWindow() + } + + #[inline] + pub fn set_theme(&self, _theme: Option) { + warn!("`Window::set_theme` is ignored on iOS"); + } + + pub fn title(&self) -> String { + warn!("`Window::title` is ignored on iOS"); + String::new() + } + + pub fn reset_dead_keys(&self) { + // Noop + } +} + +#[derive(Debug)] +pub struct Window { + inner: MainThreadBound, +} + +impl Window { + pub(crate) fn new( + event_loop: &ActiveEventLoop, + mut window_attributes: WindowAttributes, + ) -> Result { + if window_attributes.window_type() == WindowType::Popup { + return Err(RequestError::NotSupported(NotSupportedError::new( + "Popups are not implemented for iOS", + ))); + } + + let mtm = event_loop.mtm; + + if window_attributes.min_surface_size.is_some() { + warn!("`WindowAttributes::min_surface_size` is ignored on iOS"); + } + if window_attributes.max_surface_size.is_some() { + warn!("`WindowAttributes::max_surface_size` is ignored on iOS"); + } + + let ios_attributes = window_attributes + .platform + .take() + .and_then(|attrs| attrs.cast::().ok()) + .unwrap_or_default(); + + // TODO: transparency, visible + + #[allow(deprecated)] + let main_screen = UIScreen::mainScreen(mtm); + let fullscreen = window_attributes.fullscreen.clone(); + let screen = match fullscreen { + Some(Fullscreen::Exclusive(ref monitor, _)) + | Some(Fullscreen::Borderless(Some(ref monitor))) => { + let monitor = monitor.cast_ref::().unwrap(); + monitor.ui_screen(mtm) + }, + _ => &main_screen, + }; + + let screen_bounds = screen.bounds(); + + let frame = match window_attributes.surface_size { + Some(dim) => { + let scale_factor = screen.scale(); + let size = dim.to_logical::(scale_factor as f64); + CGRect { + origin: screen_bounds.origin, + size: CGSize { width: size.width as _, height: size.height as _ }, + } + }, + None => screen_bounds, + }; + + let view = WinitView::new(mtm, ios_attributes.scale_factor, frame); + + let gl_or_metal_backed = + view.isKindOfClass(class!(CAMetalLayer)) || view.isKindOfClass(class!(CAEAGLLayer)); + + let view_controller = WinitViewController::new(mtm, &ios_attributes, &view); + let window = WinitUIWindow::new(mtm, &window_attributes, frame, &view_controller); + window.makeKeyAndVisible(); + + let inner = Inner { + window, + view_controller, + view, + gl_or_metal_backed, + ime_capabilities: Default::default(), + }; + Ok(Window { inner: MainThreadBound::new(inner, mtm) }) + } + + pub(crate) fn maybe_wait_on_main(&self, f: impl FnOnce(&Inner) -> R + Send) -> R { + self.inner.get_on_main(|inner| f(inner)) + } + + #[inline] + pub(crate) fn raw_window_handle_rwh_06( + &self, + ) -> Result { + if let Some(mtm) = MainThreadMarker::new() { + Ok(self.inner.get(mtm).raw_window_handle_rwh_06()) + } else { + Err(rwh_06::HandleError::Unavailable) + } + } + + #[inline] + pub(crate) fn raw_display_handle_rwh_06( + &self, + ) -> Result { + Ok(rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new())) + } +} + +impl rwh_06::HasDisplayHandle for Window { + fn display_handle(&self) -> Result, rwh_06::HandleError> { + let raw = self.raw_display_handle_rwh_06()?; + unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) } + } +} + +impl rwh_06::HasWindowHandle for Window { + fn window_handle(&self) -> Result, rwh_06::HandleError> { + let raw = self.raw_window_handle_rwh_06()?; + unsafe { Ok(rwh_06::WindowHandle::borrow_raw(raw)) } + } +} + +impl CoreWindow for Window { + fn window_type(&self) -> WindowType { + WindowType::Window + } + + fn id(&self) -> winit_core::window::WindowId { + self.maybe_wait_on_main(|delegate| delegate.id()) + } + + fn scale_factor(&self) -> f64 { + self.maybe_wait_on_main(|delegate| delegate.scale_factor()) + } + + fn request_redraw(&self) { + self.maybe_wait_on_main(|delegate| delegate.request_redraw()); + } + + fn pre_present_notify(&self) { + self.maybe_wait_on_main(|delegate| delegate.pre_present_notify()); + } + + fn reset_dead_keys(&self) { + self.maybe_wait_on_main(|delegate| delegate.reset_dead_keys()); + } + + fn surface_position(&self) -> PhysicalPosition { + self.maybe_wait_on_main(|delegate| delegate.surface_position()) + } + + fn outer_position(&self) -> Result, RequestError> { + self.maybe_wait_on_main(|delegate| delegate.outer_position()) + } + + fn set_outer_position(&self, position: Position) { + self.maybe_wait_on_main(|delegate| delegate.set_outer_position(position)); + } + + fn surface_size(&self) -> PhysicalSize { + self.maybe_wait_on_main(|delegate| delegate.surface_size()) + } + + fn request_surface_size(&self, size: Size) -> Option> { + self.maybe_wait_on_main(|delegate| delegate.request_surface_size(size)) + } + + fn outer_size(&self) -> PhysicalSize { + self.maybe_wait_on_main(|delegate| delegate.outer_size()) + } + + fn safe_area(&self) -> PhysicalInsets { + self.maybe_wait_on_main(|delegate| delegate.safe_area()) + } + + fn set_min_surface_size(&self, min_size: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_min_surface_size(min_size)) + } + + fn set_max_surface_size(&self, max_size: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_max_surface_size(max_size)); + } + + fn surface_resize_increments(&self) -> Option> { + self.maybe_wait_on_main(|delegate| delegate.surface_resize_increments()) + } + + fn set_surface_resize_increments(&self, increments: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_surface_resize_increments(increments)); + } + + fn set_title(&self, title: &str) { + self.maybe_wait_on_main(|delegate| delegate.set_title(title)); + } + + fn set_transparent(&self, transparent: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_transparent(transparent)); + } + + fn set_blur(&self, blur: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_blur(blur)); + } + + fn set_visible(&self, visible: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_visible(visible)); + } + + fn is_visible(&self) -> Option { + self.maybe_wait_on_main(|delegate| delegate.is_visible()) + } + + fn set_resizable(&self, resizable: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_resizable(resizable)) + } + + fn is_resizable(&self) -> bool { + self.maybe_wait_on_main(|delegate| delegate.is_resizable()) + } + + fn set_enabled_buttons(&self, buttons: WindowButtons) { + self.maybe_wait_on_main(|delegate| delegate.set_enabled_buttons(buttons)) + } + + fn enabled_buttons(&self) -> WindowButtons { + self.maybe_wait_on_main(|delegate| delegate.enabled_buttons()) + } + + fn set_minimized(&self, minimized: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_minimized(minimized)); + } + + fn is_minimized(&self) -> Option { + self.maybe_wait_on_main(|delegate| delegate.is_minimized()) + } + + fn set_maximized(&self, maximized: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_maximized(maximized)); + } + + fn is_maximized(&self) -> bool { + self.maybe_wait_on_main(|delegate| delegate.is_maximized()) + } + + fn set_fullscreen(&self, fullscreen: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_fullscreen(fullscreen)) + } + + fn fullscreen(&self) -> Option { + self.maybe_wait_on_main(|delegate| delegate.fullscreen()) + } + + fn set_decorations(&self, decorations: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_decorations(decorations)); + } + + fn is_decorated(&self) -> bool { + self.maybe_wait_on_main(|delegate| delegate.is_decorated()) + } + + fn set_window_level(&self, level: WindowLevel) { + self.maybe_wait_on_main(|delegate| delegate.set_window_level(level)); + } + + fn set_window_icon(&self, window_icon: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_window_icon(window_icon)); + } + + fn request_ime_update(&self, request: ImeRequest) -> Result<(), ImeRequestError> { + self.maybe_wait_on_main(|delegate| delegate.request_ime_update(request)) + } + + fn ime_capabilities(&self) -> Option { + self.maybe_wait_on_main(|delegate| delegate.ime_capabilities()) + } + + fn focus_window(&self) { + self.maybe_wait_on_main(|delegate| delegate.focus_window()); + } + + fn has_focus(&self) -> bool { + self.maybe_wait_on_main(|delegate| delegate.has_focus()) + } + + fn request_user_attention(&self, request_type: Option) { + self.maybe_wait_on_main(|delegate| delegate.request_user_attention(request_type)); + } + + fn set_theme(&self, theme: Option) { + self.maybe_wait_on_main(|delegate| delegate.set_theme(theme)); + } + + fn theme(&self) -> Option { + self.maybe_wait_on_main(|delegate| delegate.theme()) + } + + fn set_content_protected(&self, protected: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_content_protected(protected)); + } + + fn title(&self) -> String { + self.maybe_wait_on_main(|delegate| delegate.title()) + } + + fn set_cursor(&self, cursor: Cursor) { + self.maybe_wait_on_main(|delegate| delegate.set_cursor(cursor)); + } + + fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { + Ok(self.maybe_wait_on_main(|delegate| delegate.set_cursor_position(position))?) + } + + fn set_cursor_grab( + &self, + mode: winit_core::window::CursorGrabMode, + ) -> Result<(), RequestError> { + Ok(self.maybe_wait_on_main(|delegate| delegate.set_cursor_grab(mode))?) + } + + fn set_cursor_visible(&self, visible: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_cursor_visible(visible)) + } + + fn drag_window(&self) -> Result<(), RequestError> { + Ok(self.maybe_wait_on_main(|delegate| delegate.drag_window())?) + } + + fn drag_resize_window( + &self, + direction: winit_core::window::ResizeDirection, + ) -> Result<(), RequestError> { + Ok(self.maybe_wait_on_main(|delegate| delegate.drag_resize_window(direction))?) + } + + fn show_window_menu(&self, position: Position) { + self.maybe_wait_on_main(|delegate| delegate.show_window_menu(position)) + } + + fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { + Ok(self.maybe_wait_on_main(|delegate| delegate.set_cursor_hittest(hittest))?) + } + + fn current_monitor(&self) -> Option { + self.maybe_wait_on_main(|delegate| { + delegate.current_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + }) + } + + fn available_monitors(&self) -> Box> { + self.maybe_wait_on_main(|delegate| { + Box::new( + delegate + .available_monitors() + .into_iter() + .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), + ) + }) + } + + fn primary_monitor(&self) -> Option { + self.maybe_wait_on_main(|delegate| { + delegate.primary_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + }) + } + + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } + + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { + self + } +} + +// WindowExtIOS +impl Inner { + pub fn set_scale_factor(&self, scale_factor: f64) { + assert!( + dpi::validate_scale_factor(scale_factor), + "`WindowExtIOS::set_scale_factor` received an invalid hidpi factor" + ); + let scale_factor = scale_factor as CGFloat; + self.view.setContentScaleFactor(scale_factor); + } + + pub fn set_valid_orientations(&self, valid_orientations: ValidOrientations) { + self.view_controller.set_supported_interface_orientations( + MainThreadMarker::new().unwrap(), + valid_orientations, + ); + } + + pub fn set_prefers_home_indicator_hidden(&self, hidden: bool) { + self.view_controller.set_prefers_home_indicator_auto_hidden(hidden); + } + + pub fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) { + self.view_controller.set_preferred_screen_edges_deferring_system_gestures(edges); + } + + pub fn set_prefers_status_bar_hidden(&self, hidden: bool) { + self.view_controller.set_prefers_status_bar_hidden(hidden); + } + + pub fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) { + self.view_controller.set_preferred_status_bar_style(status_bar_style); + } + + pub fn recognize_pinch_gesture(&self, should_recognize: bool) { + self.view.recognize_pinch_gesture(should_recognize); + } + + pub fn recognize_pan_gesture( + &self, + should_recognize: bool, + minimum_number_of_touches: u8, + maximum_number_of_touches: u8, + ) { + self.view.recognize_pan_gesture( + should_recognize, + minimum_number_of_touches, + maximum_number_of_touches, + ); + } + + pub fn recognize_doubletap_gesture(&self, should_recognize: bool) { + self.view.recognize_doubletap_gesture(should_recognize); + } + + pub fn recognize_rotation_gesture(&self, should_recognize: bool) { + self.view.recognize_rotation_gesture(should_recognize); + } +} + +impl Inner { + fn screen_frame(&self) -> CGRect { + self.rect_to_screen_space(self.window.frame()) + } + + fn rect_to_screen_space(&self, rect: CGRect) -> CGRect { + let screen_space = self.window.screen().coordinateSpace(); + self.window.convertRect_toCoordinateSpace(rect, &screen_space) + } + + fn rect_from_screen_space(&self, rect: CGRect) -> CGRect { + let screen_space = self.window.screen().coordinateSpace(); + self.window.convertRect_fromCoordinateSpace(rect, &screen_space) + } +}