Compare commits
61 Commits
notgull/sp
...
madsmtm/ch
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7b6f0c63d | ||
|
|
f40f87ff12 | ||
|
|
aa3127e460 | ||
|
|
295a789c42 | ||
|
|
a63b04385a | ||
|
|
06f4e28de9 | ||
|
|
249d5d8bff | ||
|
|
66df2c22ba | ||
|
|
359a38844b | ||
|
|
563b0bf5e3 | ||
|
|
b2f9fad654 | ||
|
|
4ade1a7518 | ||
|
|
e06ecf4d72 | ||
|
|
4a8050289d | ||
|
|
99e238065e | ||
|
|
d123cd2f8e | ||
|
|
fc8a008b25 | ||
|
|
f6f1c45a72 | ||
|
|
388c40b1e0 | ||
|
|
7a40aa43dc | ||
|
|
944347696a | ||
|
|
96172693fe | ||
|
|
32004405ee | ||
|
|
22e932b5ab | ||
|
|
3d4c53459a | ||
|
|
f0b4889227 | ||
|
|
c81448e0b8 | ||
|
|
f498ff0369 | ||
|
|
c4e6e94b80 | ||
|
|
a5dbd3ee52 | ||
|
|
a4480a0652 | ||
|
|
e41f0eabb1 | ||
|
|
7e28d7615e | ||
|
|
010787a430 | ||
|
|
352e70b8ac | ||
|
|
990bbf178f | ||
|
|
97cfdd4b09 | ||
|
|
a127bd6f66 | ||
|
|
4a8648be57 | ||
|
|
a8c7109e89 | ||
|
|
7abd427216 | ||
|
|
3fb93b4f83 | ||
|
|
19190a95a0 | ||
|
|
c4310af83c | ||
|
|
542d1938ce | ||
|
|
31f8b816bd | ||
|
|
e61a7320a2 | ||
|
|
db41938deb | ||
|
|
2bc1943188 | ||
|
|
385c4b3c88 | ||
|
|
ea70f773d3 | ||
|
|
83012f4c1c | ||
|
|
6825fed073 | ||
|
|
273984a385 | ||
|
|
dbe0f852da | ||
|
|
d1902aa15a | ||
|
|
4112fccc12 | ||
|
|
bd6ce32860 | ||
|
|
8936fe1acd | ||
|
|
fedb86ea5a | ||
|
|
20687fef1c |
24
.github/workflows/check-commit-msg.yml
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
name: Check Commit Messages
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
|
||||
jobs:
|
||||
length:
|
||||
name: Check that length of commit messages are <72 characters
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Fetch branch data from origin
|
||||
run: git fetch origin
|
||||
- run: |
|
||||
COMMIT_MESSAGES=$(git log --combined --format=%s origin/$GITHUB_BASE_REF..HEAD)
|
||||
echo $COMMIT_MESSAGES
|
||||
for MESSAGE in $COMMIT_MESSAGES; do
|
||||
LENGTH=$(echo $MESSAGE | wc -c)
|
||||
if [ $LENGTH -gt 72 ]; then
|
||||
echo "Commit message \"$MESSAGE\" is too long ($LENGTH characters). Please keep commit messages under 72 characters."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
35
.github/workflows/ci.yml
vendored
@@ -17,6 +17,24 @@ jobs:
|
||||
- name: Check Formatting
|
||||
run: cargo fmt -- --check
|
||||
|
||||
typos:
|
||||
name: Check for typos
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: typos-cli
|
||||
- name: run typos
|
||||
run: typos
|
||||
- name: Typos info
|
||||
if: failure()
|
||||
run: |
|
||||
echo 'To fix typos, please run `typos -w`'
|
||||
echo 'To check for a diff, run `typos`'
|
||||
echo 'You can find typos here: https://crates.io/crates/typos'
|
||||
|
||||
tests:
|
||||
name: Test ${{ matrix.toolchain }} ${{ matrix.platform.name }}
|
||||
runs-on: ${{ matrix.platform.os }}
|
||||
@@ -35,7 +53,7 @@ jobs:
|
||||
- { name: 'Linux 64bit', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, }
|
||||
- { name: 'X11', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=x11' }
|
||||
- { name: 'Wayland', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=wayland,wayland-dlopen' }
|
||||
- { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--features=android-native-activity', cmd: 'apk --' }
|
||||
- { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||
- { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest, }
|
||||
- { name: 'macOS', target: x86_64-apple-darwin, os: macos-latest, }
|
||||
- { name: 'iOS x86_64', target: x86_64-apple-ios, os: macos-latest, }
|
||||
@@ -89,7 +107,7 @@ jobs:
|
||||
|
||||
- name: Generate lockfile
|
||||
# Also updates the crates.io index
|
||||
run: cargo generate-lockfile
|
||||
run: cargo generate-lockfile && cargo update -p ahash --precise 0.8.7 && cargo update -p bumpalo --precise 3.14.0
|
||||
|
||||
- name: Install GCC Multilib
|
||||
if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
|
||||
@@ -125,13 +143,20 @@ jobs:
|
||||
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }}'
|
||||
|
||||
- name: Build crate
|
||||
run: cargo $CMD build -p winit $OPTIONS
|
||||
run: cargo $CMD build $OPTIONS
|
||||
|
||||
# Test only on Linux x86_64, so we avoid spending unnecessary CI hours.
|
||||
- name: Test dpi crate
|
||||
if: >
|
||||
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||
matrix.toolchain != '1.70.0'
|
||||
run: cargo test -p dpi
|
||||
|
||||
- name: Build tests
|
||||
if: >
|
||||
!contains(matrix.platform.target, 'redox') &&
|
||||
matrix.toolchain != '1.70.0'
|
||||
run: cargo $CMD test -p winit --no-run $OPTIONS
|
||||
run: cargo $CMD test --no-run $OPTIONS
|
||||
|
||||
- name: Run tests
|
||||
if: >
|
||||
@@ -150,7 +175,7 @@ jobs:
|
||||
if: >
|
||||
!contains(matrix.platform.target, 'redox') &&
|
||||
matrix.toolchain != '1.70.0'
|
||||
run: cargo $CMD test --no-run $OPTIONS -p winit --features serde
|
||||
run: cargo $CMD test --no-run $OPTIONS --features serde
|
||||
|
||||
- name: Run tests with serde enabled
|
||||
if: >
|
||||
|
||||
91
CHANGELOG.md
@@ -11,15 +11,24 @@ Unreleased` header.
|
||||
|
||||
# Unreleased
|
||||
|
||||
- On X11, fix swapped instance and general class names.
|
||||
- Deprecate `EventLoop::run` in favor of `EventLoop::run_app`.
|
||||
- Deprecate `EventLoopExtRunOnDemand::run_on_demand` in favor of `EventLoop::run_app_on_demand`.
|
||||
- Deprecate `EventLoopExtPumpEvents::pump_events` in favor of `EventLoopExtPumpEvents::pump_app_events`.
|
||||
- Add `ApplicationHandler<T>` trait which mimics `Event<T>`.
|
||||
- Move `dpi` types to its own crate, and re-export it from the root crate.
|
||||
- Implement `Sync` for `EventLoopProxy<T: Send>`.
|
||||
- **Breaking:** Move `Window::new` to `ActiveEventLoop::create_window` and `EventLoop::create_window` (with the latter being deprecated).
|
||||
- **Breaking:** Rename `EventLoopWindowTarget` to `ActiveEventLoop`.
|
||||
- **Breaking:** Remove `Deref` implementation for `EventLoop` that gave `EventLoopWindowTarget`.
|
||||
- **Breaking**: Remove `WindowBuilder` in favor of `WindowAttributes`.
|
||||
- **Breaking:** Removed unnecessary generic parameter `T` from `EventLoopWindowTarget`.
|
||||
- On Windows, macOS, X11, Wayland and Web, implement setting images as cursors. See the `custom_cursors.rs` example.
|
||||
- **Breaking:** Remove `Window::set_cursor_icon`
|
||||
- Add `WindowBuilder::with_cursor` and `Window::set_cursor` which takes a `CursorIcon` or `CustomCursor`
|
||||
- Add `CustomCursor`
|
||||
- Add `CustomCursor::from_rgba` to allow creating cursor images from RGBA data.
|
||||
- Add `CustomCursorExtWebSys::from_url` to allow loading cursor images from URLs.
|
||||
- Add `CustomCursorExtWebSys::from_animation` to allow creating animated cursors from other `CustomCursor`s.
|
||||
- Add `{Active,}EventLoop::create_custom_cursor` to load custom cursor image sources.
|
||||
- On macOS, add services menu.
|
||||
- **Breaking:** On Web, remove queuing fullscreen request in absence of transient activation.
|
||||
- On Web, fix setting cursor icon overriding cursor visibility.
|
||||
@@ -36,27 +45,67 @@ Unreleased` header.
|
||||
- on iOS, add detection support for `PinchGesture`, `DoubleTapGesture` and `RotationGesture`.
|
||||
- on Windows: add `with_system_backdrop`, `with_border_color`, `with_title_background_color`, `with_title_text_color` and `with_corner_preference`
|
||||
- On Windows, Remove `WS_CAPTION`, `WS_BORDER` and `WS_EX_WINDOWEDGE` styles for child windows without decorations.
|
||||
- On Windows, fixed a race condition when sending an event through the loop proxy.
|
||||
- **Breaking:** Removed `EventLoopError::AlreadyRunning`, which can't happen as it is already prevented by the type system.
|
||||
- On Wayland, disable `Occluded` event handling.
|
||||
- Added `EventLoop::builder`, which is intended to replace the (now deprecated) `EventLoopBuilder::new`.
|
||||
- **Breaking:** Changed the signature of `EventLoop::with_user_event` to return a builder.
|
||||
- **Breaking:** Removed `EventLoopBuilder::with_user_event`, the functionality is now available in `EventLoop::with_user_event`.
|
||||
- Add `Window::builder`, which is intended to replace the (now deprecated) `WindowBuilder::new`.
|
||||
- Add `Window::default_attributes` to get default `WindowAttributes`.
|
||||
- `log` has been replaced with `tracing`. The old behavior can be emulated by setting the `log` feature on the `tracing` crate.
|
||||
|
||||
# 0.29.15
|
||||
|
||||
- On X11, fix crash due to xsettings query on systems with incomplete xsettings.
|
||||
|
||||
# 0.29.14
|
||||
|
||||
- On X11/Wayland, fix `text` and `text_with_all_modifiers` not being `None` during compose.
|
||||
- On Wayland, don't reapply cursor grab when unchanged.
|
||||
- On X11, fix a bug where some mouse events would be unexpectedly filtered out.
|
||||
|
||||
# 0.29.13
|
||||
|
||||
- On Web, fix possible crash with `ControlFlow::Wait` and `ControlFlow::WaitUntil`.
|
||||
|
||||
# 0.29.12
|
||||
|
||||
- On X11, fix use after free during xinput2 handling.
|
||||
- On X11, filter close to zero values in mouse device events
|
||||
|
||||
# 0.29.11
|
||||
|
||||
- Fix compatibility with 32-bit platforms without 64-bit atomics.
|
||||
- On macOS, fix incorrect IME cursor rect origin.
|
||||
- On Windows, fixed a race condition when sending an event through the loop proxy.
|
||||
- On X11, fix swapped instance and general class names.
|
||||
- On X11, don't require XIM to run.
|
||||
- On X11, fix xkb state not being updated correctly sometimes leading to wrong input.
|
||||
- On X11, reload dpi on `_XSETTINGS_SETTINGS` update.
|
||||
- On X11, fix deadlock when adjusting DPI and resizing at the same time.
|
||||
- On Wayland, disable `Occluded` event handling.
|
||||
- On Wayland, fix DeviceEvent::Motion not being sent
|
||||
- On Wayland, fix `Focused(false)` being send when other seats still have window focused.
|
||||
- On Wayland, fix `Window::set_{min,max}_inner_size` not always applied.
|
||||
- On Wayland, fix title in CSD not updated from `AboutToWait`.
|
||||
- On Windows, fix inconsistent resizing behavior with multi-monitor setups when repositioning outside the event loop.
|
||||
- On Wayland, fix `WAYLAND_SOCKET` not used when detecting platform.
|
||||
- **Breaking:** Move some types to the `winit-core` crate. Most types are
|
||||
re-exported verbatim; however:
|
||||
- `Event`, `WindowEvent` and `KeyEvent` now take a generic that `winit`
|
||||
implements.
|
||||
- `ActivationToken` and `InnerSizeWriter` expose new methods to make them
|
||||
useful.
|
||||
- `InnerSizeWriter::request_inner_size` returns an `InnerSizeIgnored` error
|
||||
instead of an `ExternalError`.
|
||||
- On Orbital, fix `logical_key` and `text` not reported in `KeyEvent`.
|
||||
- On Orbital, implement `KeyEventExtModifierSupplement`.
|
||||
- On Orbital, map keys to `NamedKey` when possible.
|
||||
- On Orbital, implement `set_cursor_grab`.
|
||||
- On Orbital, implement `set_cursor_visible`.
|
||||
- On Orbital, implement `drag_window`.
|
||||
- On Orbital, implement `drag_resize_window`.
|
||||
- On Orbital, implement `set_transparent`.
|
||||
- On Orbital, implement `set_visible`.
|
||||
- On Orbital, implement `is_visible`.
|
||||
- On Orbital, implement `set_resizable`.
|
||||
- On Orbital, implement `is_resizable`.
|
||||
- On Orbital, implement `set_maximized`.
|
||||
- On Orbital, implement `is_maximized`.
|
||||
- On Orbital, implement `set_decorations`.
|
||||
- On Orbital, implement `is_decorated`.
|
||||
- On Orbital, implement `set_window_level`.
|
||||
- On Orbital, emit `DeviceEvent::MouseMotion`.
|
||||
|
||||
# 0.29.10
|
||||
|
||||
@@ -118,7 +167,7 @@ Unreleased` header.
|
||||
# 0.29.3
|
||||
|
||||
- On Wayland, apply correct scale to `PhysicalSize` passed in `WindowBuilder::with_inner_size` when possible.
|
||||
- On Wayland, fix `RedrawRequsted` being always sent without decorations and `sctk-adwaita` feature.
|
||||
- On Wayland, fix `RedrawRequested` being always sent without decorations and `sctk-adwaita` feature.
|
||||
- On Wayland, ignore resize requests when the window is fully tiled.
|
||||
- On Wayland, use `configure_bounds` to constrain `with_inner_size` when compositor wants users to pick size.
|
||||
- On Windows, fix deadlock when accessing the state during `Cursor{Enter,Leave}`.
|
||||
@@ -370,7 +419,7 @@ Unreleased` header.
|
||||
- **Breaking:**: Removed deprecated method `platform::unix::WindowExtUnix::is_ready`.
|
||||
- Removed `parking_lot` dependency.
|
||||
- **Breaking:** On macOS, add support for two-finger touchpad magnification and rotation gestures with new events `WindowEvent::TouchpadMagnify` and `WindowEvent::TouchpadRotate`. Also add support for touchpad smart-magnification gesture with a new event `WindowEvent::SmartMagnify`.
|
||||
- **Breaking:** On web, the `WindowBuilderExtWebSys::with_prevent_default` setting (enabled by default), now additionally prevents scrolling of the webpage in mobile browsers, previously it only disabled scrolling on desktop.
|
||||
- **Breaking:** On Web, the `WindowBuilderExtWebSys::with_prevent_default` setting (enabled by default), now additionally prevents scrolling of the webpage in mobile browsers, previously it only disabled scrolling on desktop.
|
||||
- On Wayland, `wayland-csd-adwaita` now uses `ab_glyph` instead of `crossfont` to render the title for decorations.
|
||||
- On Wayland, a new `wayland-csd-adwaita-crossfont` feature was added to use `crossfont` instead of `ab_glyph` for decorations.
|
||||
- On Wayland, if not otherwise specified use upstream automatic CSD theme selection.
|
||||
@@ -390,7 +439,7 @@ Unreleased` header.
|
||||
- Added `Window::set_transparent` to provide a hint about transparency of the window on Wayland and macOS.
|
||||
- On macOS, fix the mouse buttons other than left/right/middle being reported as middle.
|
||||
- On Wayland, support fractional scaling via the wp-fractional-scale protocol.
|
||||
- On web, fix removal of mouse event listeners from the global object upon window distruction.
|
||||
- On Web, fix removal of mouse event listeners from the global object upon window destruction.
|
||||
- Add WindowAttributes getter to WindowBuilder to allow introspection of default values.
|
||||
- Added `Window::set_ime_purpose` for setting the IME purpose, currently implemented on Wayland only.
|
||||
|
||||
@@ -496,7 +545,7 @@ Unreleased` header.
|
||||
- On Web, add `with_prevent_default` and `with_focusable` to `WindowBuilderExtWebSys` to control whether events should be propagated.
|
||||
- On Windows, fix focus events being sent to inactive windows.
|
||||
- **Breaking**, update `raw-window-handle` to `v0.5` and implement `HasRawDisplayHandle` for `Window` and `EventLoopWindowTarget`.
|
||||
- On X11, add function `register_xlib_error_hook` into `winit::platform::unix` to subscribe for errors comming from Xlib.
|
||||
- On X11, add function `register_xlib_error_hook` into `winit::platform::unix` to subscribe for errors coming from Xlib.
|
||||
- On Android, upgrade `ndk` and `ndk-glue` dependencies to the recently released `0.7.0`.
|
||||
- All platforms can now be relied on to emit a `Resumed` event. Applications are recommended to lazily initialize graphics state and windows on first resume for portability.
|
||||
- **Breaking:**: Reverse horizontal scrolling sign in `MouseScrollDelta` to match the direction of vertical scrolling. A positive X value now means moving the content to the right. The meaning of vertical scrolling stays the same: a positive Y value means moving the content down.
|
||||
@@ -795,7 +844,7 @@ Unreleased` header.
|
||||
- On Windows, fix handling of surrogate pairs when dispatching `ReceivedCharacter`.
|
||||
- On macOS 10.15, fix freeze upon exiting exclusive fullscreen mode.
|
||||
- On iOS, fix panic upon closing the app.
|
||||
- On X11, allow setting mulitple `XWindowType`s.
|
||||
- On X11, allow setting multiple `XWindowType`s.
|
||||
- On iOS, fix null window on initial `HiDpiFactorChanged` event.
|
||||
- On Windows, fix fullscreen window shrinking upon getting restored to a normal window.
|
||||
- On macOS, fix events not being emitted during modal loops, such as when windows are being resized
|
||||
@@ -948,7 +997,7 @@ and `WindowEvent::HoveredFile`.
|
||||
- On Windows, hiding the cursor no longer hides the cursor for all Winit windows - just the one `hide_cursor` was called on.
|
||||
- On Windows, cursor grabs used to get perpetually canceled when the grabbing window lost focus. Now, cursor grabs automatically get re-initialized when the window regains focus and the mouse moves over the client area.
|
||||
- On Windows, only vertical mouse wheel events were handled. Now, horizontal mouse wheel events are also handled.
|
||||
- On Windows, ignore the AltGr key when populating the `ModifersState` type.
|
||||
- On Windows, ignore the AltGr key when populating the `ModifiersState` type.
|
||||
|
||||
# Version 0.18.1 (2018-12-30)
|
||||
|
||||
@@ -1228,7 +1277,7 @@ _Yanked_
|
||||
|
||||
# Version 0.8.2 (2017-09-28)
|
||||
|
||||
- Uniformize keyboard scancode values accross Wayland and X11 (#297).
|
||||
- Uniformize keyboard scancode values across Wayland and X11 (#297).
|
||||
- Internal rework of the wayland event loop
|
||||
- Added method `os::linux::WindowExt::is_ready`
|
||||
|
||||
@@ -1242,7 +1291,7 @@ _Yanked_
|
||||
- Added `Window::set_maximized`, `WindowAttributes::maximized` and `WindowBuilder::with_maximized`.
|
||||
- Added `Window::set_fullscreen`.
|
||||
- Changed `with_fullscreen` to take a `Option<MonitorId>` instead of a `MonitorId`.
|
||||
- Removed `MonitorId::get_native_identifer()` in favor of platform-specific traits in the `os`
|
||||
- Removed `MonitorId::get_native_identifier()` in favor of platform-specific traits in the `os`
|
||||
module.
|
||||
- Changed `get_available_monitors()` and `get_primary_monitor()` to be methods of `EventsLoop`
|
||||
instead of stand-alone methods.
|
||||
|
||||
6
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,6 @@
|
||||
# Code of Conduct
|
||||
|
||||
The `rust-windowing` project adheres to the [Rust Code of Conduct]. This
|
||||
describes the minimum behavior expected from all contributors.
|
||||
|
||||
[Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct
|
||||
@@ -42,11 +42,9 @@ Once your PR is deemed ready, the merging maintainer will take care of resolving
|
||||
`CHANGELOG.md` (but you must resolve other conflicts yourself). Doing this requires that you check the
|
||||
"give contributors write access to the branch" checkbox when creating the PR.
|
||||
|
||||
## Maintainers & Testers
|
||||
## Maintainers
|
||||
|
||||
The current maintainers are listed in the [CODEOWNERS](.github/CODEOWNERS) file.
|
||||
|
||||
If you are interested in being pinged when testing is needed for a specific platform, please add yourself to the [Testers and Contributors](https://github.com/rust-windowing/winit/wiki/Testers-and-Contributors) table!
|
||||
The current maintainers for each platform are listed in the [CODEOWNERS](.github/CODEOWNERS) file.
|
||||
|
||||
## Release process
|
||||
|
||||
|
||||
284
Cargo.toml
@@ -1,16 +1,278 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"run-wasm",
|
||||
"winit",
|
||||
"winit-core"
|
||||
[package]
|
||||
name = "winit"
|
||||
version = "0.29.15"
|
||||
authors = ["The winit contributors", "Pierre Krieger <pierre.krieger1708@gmail.com>"]
|
||||
description = "Cross-platform window creation library."
|
||||
keywords = ["windowing"]
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/winit"
|
||||
categories = ["gui"]
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = [
|
||||
"rwh_04",
|
||||
"rwh_05",
|
||||
"rwh_06",
|
||||
"serde",
|
||||
"mint",
|
||||
# Enabled to get docs to compile
|
||||
"android-native-activity",
|
||||
]
|
||||
# These are all tested in CI
|
||||
targets = [
|
||||
# Windows
|
||||
"i686-pc-windows-msvc",
|
||||
"x86_64-pc-windows-msvc",
|
||||
# macOS
|
||||
"x86_64-apple-darwin",
|
||||
# Unix (X11 & Wayland)
|
||||
"i686-unknown-linux-gnu",
|
||||
"x86_64-unknown-linux-gnu",
|
||||
# iOS
|
||||
"x86_64-apple-ios",
|
||||
# Android
|
||||
"aarch64-linux-android",
|
||||
# Web
|
||||
"wasm32-unknown-unknown",
|
||||
]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
# Features are documented in either `lib.rs` or under `winit::platform`.
|
||||
[features]
|
||||
default = ["rwh_06", "x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"]
|
||||
x11 = ["x11-dl", "bytemuck", "percent-encoding", "xkbcommon-dl/x11", "x11rb"]
|
||||
wayland = ["wayland-client", "wayland-backend", "wayland-protocols", "wayland-protocols-plasma", "sctk", "ahash", "memmap2"]
|
||||
wayland-dlopen = ["wayland-backend/dlopen"]
|
||||
wayland-csd-adwaita = ["sctk-adwaita", "sctk-adwaita/ab_glyph"]
|
||||
wayland-csd-adwaita-crossfont = ["sctk-adwaita", "sctk-adwaita/crossfont"]
|
||||
wayland-csd-adwaita-notitle = ["sctk-adwaita"]
|
||||
android-native-activity = ["android-activity/native-activity"]
|
||||
android-game-activity = ["android-activity/game-activity"]
|
||||
serde = ["dep:serde", "cursor-icon/serde", "smol_str/serde", "dpi/serde"]
|
||||
mint = ["dpi/mint"]
|
||||
rwh_04 = ["dep:rwh_04", "ndk/rwh_04"]
|
||||
rwh_05 = ["dep:rwh_05", "ndk/rwh_05"]
|
||||
rwh_06 = ["dep:rwh_06", "ndk/rwh_06"]
|
||||
|
||||
[build-dependencies]
|
||||
cfg_aliases = "0.2.0"
|
||||
|
||||
[dependencies]
|
||||
bitflags = "2"
|
||||
cursor-icon = "1.1.0"
|
||||
rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true }
|
||||
rwh_05 = { package = "raw-window-handle", version = "0.5.2", features = ["std"], optional = true }
|
||||
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"], optional = true }
|
||||
serde = { workspace = true, optional = true }
|
||||
smol_str = "0.2.0"
|
||||
dpi = { path = "dpi" }
|
||||
tracing = { version = "0.1.40", default_features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
image = { version = "0.24.0", default-features = false, features = ["png"] }
|
||||
tracing = { version = "0.1.40", default_features = false, features = ["log"] }
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
|
||||
winit = { path = ".", features = ["rwh_05"] }
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies]
|
||||
softbuffer = { version = "0.3.0", default-features = false, features = ["x11", "x11-dlopen", "wayland", "wayland-dlopen"] }
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
android-activity = "0.5.0"
|
||||
ndk = { version = "0.8.0", default-features = false }
|
||||
ndk-sys = "0.5.0"
|
||||
|
||||
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
||||
core-foundation = "0.9.3"
|
||||
objc2 = "0.5.0"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
core-graphics = "0.23.1"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies.icrate]
|
||||
version = "0.1.0"
|
||||
features = [
|
||||
"dispatch",
|
||||
"Foundation",
|
||||
"Foundation_NSArray",
|
||||
"Foundation_NSAttributedString",
|
||||
"Foundation_NSMutableAttributedString",
|
||||
"Foundation_NSData",
|
||||
"Foundation_NSDictionary",
|
||||
"Foundation_NSString",
|
||||
"Foundation_NSProcessInfo",
|
||||
"Foundation_NSThread",
|
||||
"Foundation_NSNumber",
|
||||
"AppKit",
|
||||
"AppKit_NSAppearance",
|
||||
"AppKit_NSApplication",
|
||||
"AppKit_NSBitmapImageRep",
|
||||
"AppKit_NSButton",
|
||||
"AppKit_NSColor",
|
||||
"AppKit_NSControl",
|
||||
"AppKit_NSCursor",
|
||||
"AppKit_NSEvent",
|
||||
"AppKit_NSGraphicsContext",
|
||||
"AppKit_NSImage",
|
||||
"AppKit_NSImageRep",
|
||||
"AppKit_NSMenu",
|
||||
"AppKit_NSMenuItem",
|
||||
"AppKit_NSPasteboard",
|
||||
"AppKit_NSResponder",
|
||||
"AppKit_NSScreen",
|
||||
"AppKit_NSTextInputContext",
|
||||
"AppKit_NSView",
|
||||
"AppKit_NSWindow",
|
||||
"AppKit_NSWindowTabGroup",
|
||||
]
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies.icrate]
|
||||
version = "0.1.0"
|
||||
features = [
|
||||
"dispatch",
|
||||
"Foundation",
|
||||
"Foundation_NSArray",
|
||||
"Foundation_NSString",
|
||||
"Foundation_NSProcessInfo",
|
||||
"Foundation_NSThread",
|
||||
"Foundation_NSSet",
|
||||
]
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
unicode-segmentation = "1.7.1"
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies.windows-sys]
|
||||
version = "0.48"
|
||||
features = [
|
||||
"Win32_Devices_HumanInterfaceDevice",
|
||||
"Win32_Foundation",
|
||||
"Win32_Globalization",
|
||||
"Win32_Graphics_Dwm",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_Media",
|
||||
"Win32_System_Com_StructuredStorage",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_SystemInformation",
|
||||
"Win32_System_SystemServices",
|
||||
"Win32_System_Threading",
|
||||
"Win32_System_WindowsProgramming",
|
||||
"Win32_UI_Accessibility",
|
||||
"Win32_UI_Controls",
|
||||
"Win32_UI_HiDpi",
|
||||
"Win32_UI_Input_Ime",
|
||||
"Win32_UI_Input_KeyboardAndMouse",
|
||||
"Win32_UI_Input_Pointer",
|
||||
"Win32_UI_Input_Touch",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_TextServices",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
|
||||
[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies]
|
||||
ahash = { version = "0.8.7", features = ["no-rng"], optional = true }
|
||||
bytemuck = { version = "1.13.1", default-features = false, optional = true }
|
||||
calloop = "0.12.3"
|
||||
libc = "0.2.64"
|
||||
memmap2 = { version = "0.9.0", optional = true }
|
||||
percent-encoding = { version = "2.0", optional = true }
|
||||
rustix = { version = "0.38.4", default-features = false, features = ["std", "system", "thread", "process"] }
|
||||
sctk = { package = "smithay-client-toolkit", version = "0.18.0", default-features = false, features = ["calloop"], optional = true }
|
||||
sctk-adwaita = { version = "0.8.0", default_features = false, optional = true }
|
||||
wayland-backend = { version = "0.3.0", default_features = false, features = ["client_system"], optional = true }
|
||||
wayland-client = { version = "0.31.1", optional = true }
|
||||
wayland-protocols = { version = "0.31.0", features = [ "staging"], optional = true }
|
||||
wayland-protocols-plasma = { version = "0.2.0", features = [ "client" ], optional = true }
|
||||
x11-dl = { version = "2.19.1", optional = true }
|
||||
x11rb = { version = "0.13.0", default-features = false, features = ["allow-unsafe-code", "dl-libxcb", "randr", "resource_manager", "xinput", "xkb"], optional = true }
|
||||
xkbcommon-dl = "0.4.2"
|
||||
|
||||
[target.'cfg(target_os = "redox")'.dependencies]
|
||||
orbclient = { version = "0.3.47", default-features = false }
|
||||
redox_syscall = "0.4.1"
|
||||
|
||||
[target.'cfg(target_family = "wasm")'.dependencies.web_sys]
|
||||
package = "web-sys"
|
||||
version = "0.3.64"
|
||||
features = [
|
||||
'AbortController',
|
||||
'AbortSignal',
|
||||
'Blob',
|
||||
'console',
|
||||
'CssStyleDeclaration',
|
||||
'Document',
|
||||
'DomException',
|
||||
'DomRect',
|
||||
'DomRectReadOnly',
|
||||
'Element',
|
||||
'Event',
|
||||
'EventTarget',
|
||||
'FocusEvent',
|
||||
'HtmlCanvasElement',
|
||||
'HtmlElement',
|
||||
'HtmlImageElement',
|
||||
'ImageBitmap',
|
||||
'ImageBitmapOptions',
|
||||
'ImageBitmapRenderingContext',
|
||||
'ImageData',
|
||||
'IntersectionObserver',
|
||||
'IntersectionObserverEntry',
|
||||
'KeyboardEvent',
|
||||
'MediaQueryList',
|
||||
'MessageChannel',
|
||||
'MessagePort',
|
||||
'Node',
|
||||
'PageTransitionEvent',
|
||||
'PointerEvent',
|
||||
'PremultiplyAlpha',
|
||||
'ResizeObserver',
|
||||
'ResizeObserverBoxOptions',
|
||||
'ResizeObserverEntry',
|
||||
'ResizeObserverOptions',
|
||||
'ResizeObserverSize',
|
||||
'VisibilityState',
|
||||
'Window',
|
||||
'WheelEvent',
|
||||
'Url',
|
||||
]
|
||||
|
||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||
js-sys = "0.3.64"
|
||||
pin-project = "1"
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
web-time = "1"
|
||||
|
||||
[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies]
|
||||
atomic-waker = "1"
|
||||
concurrent-queue = { version = "2", default-features = false }
|
||||
|
||||
[target.'cfg(target_family = "wasm")'.dev-dependencies]
|
||||
console_log = "1"
|
||||
web-sys = { version = "0.3.22", features = ['CanvasRenderingContext2d'] }
|
||||
|
||||
[[example]]
|
||||
doc-scrape-examples = true
|
||||
name = "window"
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"dpi",
|
||||
"run-wasm",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.70.0"
|
||||
repository = "https://github.com/rust-windowing/winit"
|
||||
license = "Apache-2.0"
|
||||
edition = "2021"
|
||||
|
||||
[workspace.dependencies]
|
||||
bitflags = "2"
|
||||
cfg_aliases = "0.2.0"
|
||||
cursor-icon = "1.1.0"
|
||||
serde = { version = "1", features = ["serde_derive"] }
|
||||
smol_str = "0.2.0"
|
||||
web-time = "1"
|
||||
winit-core = { path = "./winit-core", default-features = false, features = ["std"] }
|
||||
mint = "0.5.6"
|
||||
|
||||
11
FEATURES.md
@@ -3,8 +3,8 @@
|
||||
Winit aims to expose an interface that abstracts over window creation and input handling and can
|
||||
be used to create both games and applications. It supports the following main graphical platforms:
|
||||
- Desktop
|
||||
- Windows 7+ (10+ is tested regularly)
|
||||
- macOS 10.7+ (10.14+ is tested regularly)
|
||||
- Windows
|
||||
- macOS
|
||||
- Unix
|
||||
- via X11
|
||||
- via Wayland
|
||||
@@ -13,9 +13,6 @@ be used to create both games and applications. It supports the following main gr
|
||||
- iOS
|
||||
- Android
|
||||
- Web
|
||||
- Chrome
|
||||
- Firefox
|
||||
- Safari 13.1+
|
||||
|
||||
Most platforms expose capabilities that cannot be meaningfully transposed onto others. Winit does not
|
||||
aim to support every single feature of every platform, but rather to abstract over the common features
|
||||
@@ -151,7 +148,6 @@ If your PR makes notable changes to Winit's features, please update this section
|
||||
* Setting the X11 parent window
|
||||
|
||||
### iOS
|
||||
* `winit` has a minimum OS requirement of iOS 8
|
||||
* Get the `UIScreen` object pointer
|
||||
* Setting the `UIView` hidpi factor
|
||||
* Valid orientations
|
||||
@@ -164,9 +160,6 @@ If your PR makes notable changes to Winit's features, please update this section
|
||||
### Web
|
||||
* Get if the systems preferred color scheme is "dark"
|
||||
|
||||
## Usability
|
||||
* `serde`: Enables serialization/deserialization of certain types with Serde. (Maintainer: @Osspial)
|
||||
|
||||
## Compatibility Matrix
|
||||
|
||||
Legend:
|
||||
|
||||
128
README.md
@@ -8,7 +8,7 @@
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
winit = "0.29.10"
|
||||
winit = "0.29.15"
|
||||
```
|
||||
|
||||
## [Documentation](https://docs.rs/winit)
|
||||
@@ -21,7 +21,7 @@ For features _outside_ the scope of winit, see [Are we GUI Yet?](https://arewegu
|
||||
|
||||
Join us in our [](https://matrix.to/#/#rust-windowing:matrix.org) room. If you don't get an answer there, try [](https://web.libera.chat/#winit).
|
||||
|
||||
The maintainers have a meeting every friday at UTC 14. The meeting notes can be found [here](https://hackmd.io/@winit-meetings).
|
||||
The maintainers have a meeting every friday at UTC 15. The meeting notes can be found [here](https://hackmd.io/@winit-meetings).
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -33,14 +33,6 @@ Winit is designed to be a low-level brick in a hierarchy of libraries. Consequen
|
||||
show something on the window you need to use the platform-specific getters provided by winit, or
|
||||
another library.
|
||||
|
||||
### Cargo Features
|
||||
|
||||
Winit provides the following features, which can be enabled in your `Cargo.toml` file:
|
||||
* `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde).
|
||||
* `x11` (enabled by default): On Unix platform, compiles with the X11 backend
|
||||
* `wayland` (enabled by default): On Unix platform, compiles with the Wayland backend
|
||||
* `mint`: Enables mint (math interoperability standard types) conversions.
|
||||
|
||||
## MSRV Policy
|
||||
|
||||
This crate's Minimum Supported Rust Version (MSRV) is **1.70**. Changes to
|
||||
@@ -71,118 +63,4 @@ same MSRV policy.
|
||||
|
||||
### Platform-specific usage
|
||||
|
||||
#### Wayland
|
||||
|
||||
Note that windows don't appear on Wayland until you draw/present to them.
|
||||
|
||||
#### Web
|
||||
|
||||
To run the web example: `cargo run-wasm --example web`
|
||||
|
||||
Winit supports compiling to the `wasm32-unknown-unknown` target with `web-sys`.
|
||||
|
||||
On the web platform, a Winit window is backed by a `<canvas>` element. You can
|
||||
either [provide Winit with a `<canvas>` element][web with_canvas], or [let Winit
|
||||
create a `<canvas>` element which you can then retrieve][web canvas getter] and
|
||||
insert it into the DOM yourself.
|
||||
|
||||
For the example code using Winit on Web, check out the [web example]. For
|
||||
information on using Rust on WebAssembly, check out the [Rust and WebAssembly
|
||||
book].
|
||||
|
||||
[web with_canvas]: https://docs.rs/winit/latest/wasm32-unknown-unknown/winit/platform/web/trait.WindowBuilderExtWebSys.html#tymethod.with_canvas
|
||||
[web canvas getter]: https://docs.rs/winit/latest/wasm32-unknown-unknown/winit/platform/web/trait.WindowExtWebSys.html#tymethod.canvas
|
||||
[web example]: ./examples/web.rs
|
||||
[Rust and WebAssembly book]: https://rustwasm.github.io/book/
|
||||
|
||||
#### Android
|
||||
|
||||
The Android backend builds on (and exposes types from) the [`ndk`](https://docs.rs/ndk/latest/ndk/) crate.
|
||||
|
||||
Native Android applications need some form of "glue" crate that is responsible
|
||||
for defining the main entry point for your Rust application as well as tracking
|
||||
various life-cycle events and synchronizing with the main JVM thread.
|
||||
|
||||
Winit uses the [android-activity](https://github.com/rib/android-activity) as a
|
||||
glue crate (prior to `0.28` it used
|
||||
[ndk-glue](https://github.com/rust-windowing/android-ndk-rs/tree/master/ndk-glue)).
|
||||
|
||||
The version of the glue crate that your application depends on _must_ match the
|
||||
version that Winit depends on because the glue crate is responsible for your
|
||||
application's main entry point. If Cargo resolves multiple versions, they will
|
||||
clash.
|
||||
|
||||
`winit` glue compatibility table:
|
||||
|
||||
| winit | ndk-glue |
|
||||
| :---: | :--------------------------: |
|
||||
| 0.29 | `android-activity = "0.5"` |
|
||||
| 0.28 | `android-activity = "0.4"` |
|
||||
| 0.27 | `ndk-glue = "0.7"` |
|
||||
| 0.26 | `ndk-glue = "0.5"` |
|
||||
| 0.25 | `ndk-glue = "0.3"` |
|
||||
| 0.24 | `ndk-glue = "0.2"` |
|
||||
|
||||
The recommended way to avoid a conflict with the glue version is to avoid explicitly
|
||||
depending on the `android-activity` crate, and instead consume the API that
|
||||
is re-exported by Winit under `winit::platform::android::activity::*`
|
||||
|
||||
Running on an Android device needs a dynamic system library. Add this to Cargo.toml:
|
||||
|
||||
```toml
|
||||
[lib]
|
||||
name = "main"
|
||||
crate-type = ["cdylib"]
|
||||
```
|
||||
|
||||
All Android applications are based on an `Activity` subclass, and the
|
||||
`android-activity` crate is designed to support different choices for this base
|
||||
class. Your application _must_ specify the base class it needs via a feature flag:
|
||||
|
||||
| Base Class | Feature Flag | Notes |
|
||||
| :--------------: | :---------------: | :-----: |
|
||||
| `NativeActivity` | `android-native-activity` | Built-in to Android - it is possible to use without compiling any Java or Kotlin code. Java or Kotlin code may be needed to subclass `NativeActivity` to access some platform features. It does not derive from the [`AndroidAppCompat`] base class.|
|
||||
| [`GameActivity`] | `android-game-activity` | Derives from [`AndroidAppCompat`], a defacto standard `Activity` base class that helps support a wider range of Android versions. Requires a build system that can compile Java or Kotlin and fetch Android dependencies from a [Maven repository][agdk_jetpack] (or link with an embedded [release][agdk_releases] of [`GameActivity`]) |
|
||||
|
||||
[`GameActivity`]: https://developer.android.com/games/agdk/game-activity
|
||||
[`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input
|
||||
[`AndroidAppCompat`]: https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity
|
||||
[agdk_jetpack]: https://developer.android.com/jetpack/androidx/releases/games
|
||||
[agdk_releases]: https://developer.android.com/games/agdk/download#agdk-libraries
|
||||
[Gradle]: https://developer.android.com/studio/build
|
||||
|
||||
For more details, refer to these `android-activity` [example applications](https://github.com/rust-mobile/android-activity/tree/main/examples).
|
||||
|
||||
##### Converting from `ndk-glue` to `android-activity`
|
||||
|
||||
If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building with `cargo apk`, then the minimal changes would be:
|
||||
1. Remove `ndk-glue` from your `Cargo.toml`
|
||||
2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.10", features = [ "android-native-activity" ] }`
|
||||
3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize logging as above).
|
||||
4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above).
|
||||
|
||||
#### MacOS
|
||||
|
||||
A lot of functionality expects the application to be ready before you start
|
||||
doing anything; this includes creating windows, fetching monitors, drawing,
|
||||
and so on, see issues [#2238], [#2051] and [#2087].
|
||||
|
||||
If you encounter problems, you should try doing your initialization inside
|
||||
`Event::Resumed`.
|
||||
|
||||
#### iOS
|
||||
|
||||
Similar to macOS, iOS's main `UIApplicationMain` does some init work that's required
|
||||
by all UI-related code (see issue [#1705]). It would be best to consider creating your windows
|
||||
inside `Event::Resumed`.
|
||||
|
||||
|
||||
[#2238]: https://github.com/rust-windowing/winit/issues/2238
|
||||
[#2051]: https://github.com/rust-windowing/winit/issues/2051
|
||||
[#2087]: https://github.com/rust-windowing/winit/issues/2087
|
||||
[#1705]: https://github.com/rust-windowing/winit/issues/1705
|
||||
|
||||
#### Redox OS
|
||||
|
||||
Redox OS has some functionality not yet present that will be implemented when
|
||||
its orbital display server provides it.
|
||||
Check out the [`winit::platform`](https://rust-windowing.github.io/winit/winit/platform/index.html) module for platform-specific usage.
|
||||
|
||||
@@ -35,9 +35,7 @@ skip = [
|
||||
{ name = "bitflags" }, # the ecosystem is in the process of migrating.
|
||||
{ name = "libloading" }, # x11rb uses a different version until the next update
|
||||
]
|
||||
skip-tree = [
|
||||
{ name = "run-wasm", version = "0.1.0" }
|
||||
]
|
||||
skip-tree = []
|
||||
|
||||
|
||||
[licenses]
|
||||
|
||||
16
dpi/CHANGELOG.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
Please keep one empty line before and after all headers. (This is required for
|
||||
`git` to produce a conflict when a release is made while a PR is open and the
|
||||
PR's changelog entry would go into the wrong section).
|
||||
|
||||
And please only add new entries to the top of this list, right below the `#
|
||||
Unreleased` header.
|
||||
|
||||
# Unreleased
|
||||
|
||||
# 0.1.0
|
||||
|
||||
- Add `LogicalUnit`, `PhysicalUnit` and `PixelUnit` types and related functions.
|
||||
39
dpi/Cargo.toml
Normal file
@@ -0,0 +1,39 @@
|
||||
[package]
|
||||
name = "dpi"
|
||||
version = "0.1.0"
|
||||
description = "Types for handling UI scaling"
|
||||
keywords = ["DPI", "HiDPI", "scale-factor"]
|
||||
categories = ["gui"]
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[features]
|
||||
serde = ["dep:serde"]
|
||||
mint = ["dep:mint"]
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true, optional = true }
|
||||
mint = { workspace = true, optional = true }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["serde", "mint"]
|
||||
# These are all tested in CI
|
||||
targets = [
|
||||
# Windows
|
||||
"i686-pc-windows-msvc",
|
||||
"x86_64-pc-windows-msvc",
|
||||
# macOS
|
||||
"x86_64-apple-darwin",
|
||||
# Unix (X11 & Wayland)
|
||||
"i686-unknown-linux-gnu",
|
||||
"x86_64-unknown-linux-gnu",
|
||||
# iOS
|
||||
"x86_64-apple-ios",
|
||||
# Android
|
||||
"aarch64-linux-android",
|
||||
# Web
|
||||
"wasm32-unknown-unknown",
|
||||
]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
1
dpi/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE
|
||||
@@ -1,4 +1,4 @@
|
||||
//! UI scaling is important, so read the docs for this module if you don't want to be confused.
|
||||
//! # DPI
|
||||
//!
|
||||
//! ## Why should I care about UI scaling?
|
||||
//!
|
||||
@@ -35,14 +35,11 @@
|
||||
//!
|
||||
//! ### Position and Size types
|
||||
//!
|
||||
//! Winit's [`PhysicalPosition`] / [`PhysicalSize`] types correspond with the actual pixels on the
|
||||
//! device, and the [`LogicalPosition`] / [`LogicalSize`] types correspond to the physical pixels
|
||||
//! The [`PhysicalPosition`] / [`PhysicalSize`] / [`PhysicalUnit`] types correspond with the actual pixels on the
|
||||
//! device, and the [`LogicalPosition`] / [`LogicalSize`] / [`LogicalUnit`] types correspond to the physical pixels
|
||||
//! divided by the scale factor.
|
||||
//! All of Winit's functions return physical types, but can take either logical or physical
|
||||
//! coordinates as input, allowing you to use the most convenient coordinate system for your
|
||||
//! particular application.
|
||||
//!
|
||||
//! Winit's position and size types are generic over their exact pixel type, `P`, to allow the
|
||||
//! The position and size types are generic over their exact pixel type, `P`, to allow the
|
||||
//! API to have integer precision where appropriate (e.g. most window manipulation functions) and
|
||||
//! floating precision when necessary (e.g. logical sizes for fractional scale factors and touch
|
||||
//! input). If `P` is a floating-point type, please do not cast the values with `as {int}`. Doing so
|
||||
@@ -51,58 +48,24 @@
|
||||
//! rounding properly. Note that precision loss will still occur when rounding from a float to an
|
||||
//! int, although rounding lessens the problem.
|
||||
//!
|
||||
//! ### Events
|
||||
//! ## Cargo Features
|
||||
//!
|
||||
//! Winit will dispatch a [`ScaleFactorChanged`] event whenever a window's scale factor has changed.
|
||||
//! This can happen if the user drags their window from a standard-resolution monitor to a high-DPI
|
||||
//! monitor or if the user changes their DPI settings. This allows you to rescale your application's
|
||||
//! UI elements and adjust how the platform changes the window's size to reflect the new scale
|
||||
//! factor. If a window hasn't received a [`ScaleFactorChanged`] event, its scale factor
|
||||
//! can be found by calling [`window.scale_factor()`].
|
||||
//! This crate provides the following Cargo features:
|
||||
//!
|
||||
//! ## How is the scale factor calculated?
|
||||
//!
|
||||
//! The scale factor is calculated differently on different platforms:
|
||||
//!
|
||||
//! - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from the
|
||||
//! display settings. While users are free to select any option they want, they're only given a
|
||||
//! selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7. The scale factor is
|
||||
//! global and changing it requires logging out. See [this article][windows_1] for technical
|
||||
//! details.
|
||||
//! - **macOS:** Recent macOS versions allow the user to change the scaling factor for specific
|
||||
//! displays. When available, the user may pick a per-monitor scaling factor from a set of
|
||||
//! pre-defined settings. All "retina displays" have a scaling factor above 1.0 by default,
|
||||
//! but the specific value varies across devices.
|
||||
//! - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. Winit
|
||||
//! currently uses a three-pronged approach:
|
||||
//! + Use the value in the `WINIT_X11_SCALE_FACTOR` environment variable if present.
|
||||
//! + If not present, use the value set in `Xft.dpi` in Xresources.
|
||||
//! + Otherwise, calculate the scale factor based on the millimeter monitor dimensions provided by XRandR.
|
||||
//!
|
||||
//! If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use the
|
||||
//! XRandR scaling method. Generally speaking, you should try to configure the standard system
|
||||
//! variables to do what you want before resorting to `WINIT_X11_SCALE_FACTOR`.
|
||||
//! - **Wayland:** The scale factor is suggested by the compositor for each window individually. The
|
||||
//! monitor scale factor may differ from the window scale factor.
|
||||
//! - **iOS:** Scale factors are set by Apple to the value that best suits the device, and range
|
||||
//! from `1.0` to `3.0`. See [this article][apple_1] and [this article][apple_2] for more
|
||||
//! information.
|
||||
//! - **Android:** Scale factors are set by the manufacturer to the value that best suits the
|
||||
//! device, and range from `1.0` to `4.0`. See [this article][android_1] for more information.
|
||||
//! - **Web:** The scale factor is the ratio between CSS pixels and the physical device pixels.
|
||||
//! In other words, it is the value of [`window.devicePixelRatio`][web_1]. It is affected by
|
||||
//! both the screen scaling and the browser zoom level and can go below `1.0`.
|
||||
//! * `serde`: Enables serialization/deserialization of certain types with
|
||||
//! [Serde](https://crates.io/crates/serde).
|
||||
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
||||
//!
|
||||
//!
|
||||
//! [points]: https://en.wikipedia.org/wiki/Point_(typography)
|
||||
//! [picas]: https://en.wikipedia.org/wiki/Pica_(typography)
|
||||
//! [`ScaleFactorChanged`]: crate::event::WindowEvent::ScaleFactorChanged
|
||||
//! [`window.scale_factor()`]: https://docs.rs/winit/latest/winit/window/struct.Window.html#method.scale_factor
|
||||
//! [windows_1]: https://docs.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows
|
||||
//! [apple_1]: https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
|
||||
//! [apple_2]: https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/image-size-and-resolution/
|
||||
//! [android_1]: https://developer.android.com/training/multiscreen/screendensities
|
||||
//! [web_1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
|
||||
|
||||
#![cfg_attr(
|
||||
docsrs,
|
||||
feature(doc_auto_cfg, doc_cfg_hide),
|
||||
doc(cfg_hide(doc, docsrs))
|
||||
)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -165,10 +128,242 @@ pub fn validate_scale_factor(scale_factor: f64) -> bool {
|
||||
scale_factor.is_sign_positive() && scale_factor.is_normal()
|
||||
}
|
||||
|
||||
/// A logical pixel unit.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct LogicalUnit<P>(pub P);
|
||||
|
||||
impl<P> LogicalUnit<P> {
|
||||
/// Represents a minimum logical unit of [`f64::MAX`].
|
||||
pub const MIN: LogicalUnit<f64> = LogicalUnit::new(f64::MIN);
|
||||
/// Represents a logical unit of `0_f64`.
|
||||
pub const ZERO: LogicalUnit<f64> = LogicalUnit::new(0.0);
|
||||
/// Represents a maximum logical unit that is equal to [`f64::MAX`].
|
||||
pub const MAX: LogicalUnit<f64> = LogicalUnit::new(f64::MAX);
|
||||
|
||||
#[inline]
|
||||
pub const fn new(v: P) -> Self {
|
||||
LogicalUnit(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> LogicalUnit<P> {
|
||||
#[inline]
|
||||
pub fn from_physical<T: Into<PhysicalUnit<X>>, X: Pixel>(
|
||||
physical: T,
|
||||
scale_factor: f64,
|
||||
) -> Self {
|
||||
physical.into().to_logical(scale_factor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_physical<X: Pixel>(&self, scale_factor: f64) -> PhysicalUnit<X> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
PhysicalUnit::new(self.0.into() * scale_factor).cast()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn cast<X: Pixel>(&self) -> LogicalUnit<X> {
|
||||
LogicalUnit(self.0.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<X> for LogicalUnit<P> {
|
||||
fn from(v: X) -> LogicalUnit<P> {
|
||||
LogicalUnit::new(v.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<LogicalUnit<P>> for u8 {
|
||||
fn from(v: LogicalUnit<P>) -> u8 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<LogicalUnit<P>> for u16 {
|
||||
fn from(v: LogicalUnit<P>) -> u16 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<LogicalUnit<P>> for u32 {
|
||||
fn from(v: LogicalUnit<P>) -> u32 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<LogicalUnit<P>> for i8 {
|
||||
fn from(v: LogicalUnit<P>) -> i8 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<LogicalUnit<P>> for i16 {
|
||||
fn from(v: LogicalUnit<P>) -> i16 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<LogicalUnit<P>> for i32 {
|
||||
fn from(v: LogicalUnit<P>) -> i32 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<LogicalUnit<P>> for f32 {
|
||||
fn from(v: LogicalUnit<P>) -> f32 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<LogicalUnit<P>> for f64 {
|
||||
fn from(v: LogicalUnit<P>) -> f64 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
/// A physical pixel unit.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct PhysicalUnit<P>(pub P);
|
||||
|
||||
impl<P> PhysicalUnit<P> {
|
||||
/// Represents a minimum physical unit of [`f64::MAX`].
|
||||
pub const MIN: LogicalUnit<f64> = LogicalUnit::new(f64::MIN);
|
||||
/// Represents a physical unit of `0_f64`.
|
||||
pub const ZERO: LogicalUnit<f64> = LogicalUnit::new(0.0);
|
||||
/// Represents a maximum physical unit that is equal to [`f64::MAX`].
|
||||
pub const MAX: LogicalUnit<f64> = LogicalUnit::new(f64::MAX);
|
||||
|
||||
#[inline]
|
||||
pub const fn new(v: P) -> Self {
|
||||
PhysicalUnit(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> PhysicalUnit<P> {
|
||||
#[inline]
|
||||
pub fn from_logical<T: Into<LogicalUnit<X>>, X: Pixel>(logical: T, scale_factor: f64) -> Self {
|
||||
logical.into().to_physical(scale_factor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_logical<X: Pixel>(&self, scale_factor: f64) -> LogicalUnit<X> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
LogicalUnit::new(self.0.into() / scale_factor).cast()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn cast<X: Pixel>(&self) -> PhysicalUnit<X> {
|
||||
PhysicalUnit(self.0.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<X> for PhysicalUnit<P> {
|
||||
fn from(v: X) -> PhysicalUnit<P> {
|
||||
PhysicalUnit::new(v.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<PhysicalUnit<P>> for u8 {
|
||||
fn from(v: PhysicalUnit<P>) -> u8 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<PhysicalUnit<P>> for u16 {
|
||||
fn from(v: PhysicalUnit<P>) -> u16 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<PhysicalUnit<P>> for u32 {
|
||||
fn from(v: PhysicalUnit<P>) -> u32 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<PhysicalUnit<P>> for i8 {
|
||||
fn from(v: PhysicalUnit<P>) -> i8 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<PhysicalUnit<P>> for i16 {
|
||||
fn from(v: PhysicalUnit<P>) -> i16 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<PhysicalUnit<P>> for i32 {
|
||||
fn from(v: PhysicalUnit<P>) -> i32 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<PhysicalUnit<P>> for f32 {
|
||||
fn from(v: PhysicalUnit<P>) -> f32 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<PhysicalUnit<P>> for f64 {
|
||||
fn from(v: PhysicalUnit<P>) -> f64 {
|
||||
v.0.cast()
|
||||
}
|
||||
}
|
||||
|
||||
/// A pixel unit that's either physical or logical.
|
||||
pub enum PixelUnit {
|
||||
Physical(PhysicalUnit<i32>),
|
||||
Logical(LogicalUnit<f64>),
|
||||
}
|
||||
|
||||
impl PixelUnit {
|
||||
/// Represents a minimum logical unit of [`f64::MAX`].
|
||||
pub const MIN: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MIN));
|
||||
/// Represents a logical unit of `0_f64`.
|
||||
pub const ZERO: PixelUnit = PixelUnit::Logical(LogicalUnit::new(0.0));
|
||||
/// Represents a maximum logical unit that is equal to [`f64::MAX`].
|
||||
pub const MAX: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MAX));
|
||||
|
||||
pub fn new<S: Into<PixelUnit>>(unit: S) -> PixelUnit {
|
||||
unit.into()
|
||||
}
|
||||
|
||||
pub fn to_logical<P: Pixel>(&self, scale_factor: f64) -> LogicalUnit<P> {
|
||||
match *self {
|
||||
PixelUnit::Physical(unit) => unit.to_logical(scale_factor),
|
||||
PixelUnit::Logical(unit) => unit.cast(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_physical<P: Pixel>(&self, scale_factor: f64) -> PhysicalUnit<P> {
|
||||
match *self {
|
||||
PixelUnit::Physical(unit) => unit.cast(),
|
||||
PixelUnit::Logical(unit) => unit.to_physical(scale_factor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<PhysicalUnit<P>> for PixelUnit {
|
||||
#[inline]
|
||||
fn from(unit: PhysicalUnit<P>) -> PixelUnit {
|
||||
PixelUnit::Physical(unit.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<LogicalUnit<P>> for PixelUnit {
|
||||
#[inline]
|
||||
fn from(unit: LogicalUnit<P>) -> PixelUnit {
|
||||
PixelUnit::Logical(unit.cast())
|
||||
}
|
||||
}
|
||||
|
||||
/// A position represented in logical pixels.
|
||||
///
|
||||
/// The position is stored as floats, so please be careful. Casting floats to integers truncates the
|
||||
/// fractional part, which can cause noticable issues. To help with that, an `Into<(i32, i32)>`
|
||||
/// fractional part, which can cause noticeable issues. To help with that, an `Into<(i32, i32)>`
|
||||
/// implementation is provided which does the rounding for you.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
@@ -587,15 +782,13 @@ impl<P: Pixel> From<LogicalPosition<P>> for Position {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::dpi;
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
macro_rules! test_pixel_int_impl {
|
||||
($($name:ident => $ty:ty),*) => {$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
use dpi::Pixel;
|
||||
|
||||
assert_eq!(
|
||||
<$ty as Pixel>::from_f64(37.0),
|
||||
37,
|
||||
@@ -664,8 +857,6 @@ mod tests {
|
||||
($($name:ident => $ty:ty),*) => {$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
use dpi::Pixel;
|
||||
|
||||
assert_approx_eq!(
|
||||
<$ty as Pixel>::from_f64(37.0),
|
||||
37.0,
|
||||
@@ -758,46 +949,77 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_validate_scale_factor() {
|
||||
assert!(dpi::validate_scale_factor(1.0));
|
||||
assert!(dpi::validate_scale_factor(2.0));
|
||||
assert!(dpi::validate_scale_factor(3.0));
|
||||
assert!(dpi::validate_scale_factor(1.5));
|
||||
assert!(dpi::validate_scale_factor(0.5));
|
||||
assert!(validate_scale_factor(1.0));
|
||||
assert!(validate_scale_factor(2.0));
|
||||
assert!(validate_scale_factor(3.0));
|
||||
assert!(validate_scale_factor(1.5));
|
||||
assert!(validate_scale_factor(0.5));
|
||||
|
||||
assert!(!dpi::validate_scale_factor(0.0));
|
||||
assert!(!dpi::validate_scale_factor(-1.0));
|
||||
assert!(!dpi::validate_scale_factor(f64::INFINITY));
|
||||
assert!(!dpi::validate_scale_factor(f64::NAN));
|
||||
assert!(!dpi::validate_scale_factor(f64::NEG_INFINITY));
|
||||
assert!(!validate_scale_factor(0.0));
|
||||
assert!(!validate_scale_factor(-1.0));
|
||||
assert!(!validate_scale_factor(f64::INFINITY));
|
||||
assert!(!validate_scale_factor(f64::NAN));
|
||||
assert!(!validate_scale_factor(f64::NEG_INFINITY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_logical_unity() {
|
||||
let log_unit = LogicalUnit::new(1.0);
|
||||
assert_eq!(log_unit.to_physical::<u32>(1.0), PhysicalUnit::new(1));
|
||||
assert_eq!(log_unit.to_physical::<u32>(2.0), PhysicalUnit::new(2));
|
||||
assert_eq!(log_unit.cast::<u32>(), LogicalUnit::new(1));
|
||||
assert_eq!(
|
||||
log_unit,
|
||||
LogicalUnit::from_physical(PhysicalUnit::new(1.0), 1.0)
|
||||
);
|
||||
assert_eq!(
|
||||
log_unit,
|
||||
LogicalUnit::from_physical(PhysicalUnit::new(2.0), 2.0)
|
||||
);
|
||||
assert_eq!(LogicalUnit::from(2.0), LogicalUnit::new(2.0));
|
||||
|
||||
let x: f64 = log_unit.into();
|
||||
assert_eq!(x, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_physical_unit() {
|
||||
assert_eq!(
|
||||
PhysicalUnit::from_logical(LogicalUnit::new(1.0), 1.0),
|
||||
PhysicalUnit::new(1)
|
||||
);
|
||||
assert_eq!(
|
||||
PhysicalUnit::from_logical(LogicalUnit::new(2.0), 0.5),
|
||||
PhysicalUnit::new(1)
|
||||
);
|
||||
assert_eq!(PhysicalUnit::from(2.0), PhysicalUnit::new(2.0,));
|
||||
assert_eq!(PhysicalUnit::from(2.0), PhysicalUnit::new(2.0));
|
||||
|
||||
let x: f64 = PhysicalUnit::new(1).into();
|
||||
assert_eq!(x, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_logical_position() {
|
||||
let log_pos = dpi::LogicalPosition::new(1.0, 2.0);
|
||||
assert_eq!(
|
||||
log_pos.to_physical::<u32>(1.0),
|
||||
dpi::PhysicalPosition::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
log_pos.to_physical::<u32>(2.0),
|
||||
dpi::PhysicalPosition::new(2, 4)
|
||||
);
|
||||
assert_eq!(log_pos.cast::<u32>(), dpi::LogicalPosition::new(1, 2));
|
||||
let log_pos = LogicalPosition::new(1.0, 2.0);
|
||||
assert_eq!(log_pos.to_physical::<u32>(1.0), PhysicalPosition::new(1, 2));
|
||||
assert_eq!(log_pos.to_physical::<u32>(2.0), PhysicalPosition::new(2, 4));
|
||||
assert_eq!(log_pos.cast::<u32>(), LogicalPosition::new(1, 2));
|
||||
assert_eq!(
|
||||
log_pos,
|
||||
dpi::LogicalPosition::from_physical(dpi::PhysicalPosition::new(1.0, 2.0), 1.0)
|
||||
LogicalPosition::from_physical(PhysicalPosition::new(1.0, 2.0), 1.0)
|
||||
);
|
||||
assert_eq!(
|
||||
log_pos,
|
||||
dpi::LogicalPosition::from_physical(dpi::PhysicalPosition::new(2.0, 4.0), 2.0)
|
||||
LogicalPosition::from_physical(PhysicalPosition::new(2.0, 4.0), 2.0)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::LogicalPosition::from((2.0, 2.0)),
|
||||
dpi::LogicalPosition::new(2.0, 2.0)
|
||||
LogicalPosition::from((2.0, 2.0)),
|
||||
LogicalPosition::new(2.0, 2.0)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::LogicalPosition::from([2.0, 3.0]),
|
||||
dpi::LogicalPosition::new(2.0, 3.0)
|
||||
LogicalPosition::from([2.0, 3.0]),
|
||||
LogicalPosition::new(2.0, 3.0)
|
||||
);
|
||||
|
||||
let x: (f64, f64) = log_pos.into();
|
||||
@@ -809,56 +1031,44 @@ mod tests {
|
||||
#[test]
|
||||
fn test_physical_position() {
|
||||
assert_eq!(
|
||||
dpi::PhysicalPosition::from_logical(dpi::LogicalPosition::new(1.0, 2.0), 1.0),
|
||||
dpi::PhysicalPosition::new(1, 2)
|
||||
PhysicalPosition::from_logical(LogicalPosition::new(1.0, 2.0), 1.0),
|
||||
PhysicalPosition::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::PhysicalPosition::from_logical(dpi::LogicalPosition::new(2.0, 4.0), 0.5),
|
||||
dpi::PhysicalPosition::new(1, 2)
|
||||
PhysicalPosition::from_logical(LogicalPosition::new(2.0, 4.0), 0.5),
|
||||
PhysicalPosition::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::PhysicalPosition::from((2.0, 2.0)),
|
||||
dpi::PhysicalPosition::new(2.0, 2.0)
|
||||
PhysicalPosition::from((2.0, 2.0)),
|
||||
PhysicalPosition::new(2.0, 2.0)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::PhysicalPosition::from([2.0, 3.0]),
|
||||
dpi::PhysicalPosition::new(2.0, 3.0)
|
||||
PhysicalPosition::from([2.0, 3.0]),
|
||||
PhysicalPosition::new(2.0, 3.0)
|
||||
);
|
||||
|
||||
let x: (f64, f64) = dpi::PhysicalPosition::new(1, 2).into();
|
||||
let x: (f64, f64) = PhysicalPosition::new(1, 2).into();
|
||||
assert_eq!(x, (1.0, 2.0));
|
||||
let x: [f64; 2] = dpi::PhysicalPosition::new(1, 2).into();
|
||||
let x: [f64; 2] = PhysicalPosition::new(1, 2).into();
|
||||
assert_eq!(x, [1.0, 2.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_logical_size() {
|
||||
let log_size = dpi::LogicalSize::new(1.0, 2.0);
|
||||
assert_eq!(
|
||||
log_size.to_physical::<u32>(1.0),
|
||||
dpi::PhysicalSize::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
log_size.to_physical::<u32>(2.0),
|
||||
dpi::PhysicalSize::new(2, 4)
|
||||
);
|
||||
assert_eq!(log_size.cast::<u32>(), dpi::LogicalSize::new(1, 2));
|
||||
let log_size = LogicalSize::new(1.0, 2.0);
|
||||
assert_eq!(log_size.to_physical::<u32>(1.0), PhysicalSize::new(1, 2));
|
||||
assert_eq!(log_size.to_physical::<u32>(2.0), PhysicalSize::new(2, 4));
|
||||
assert_eq!(log_size.cast::<u32>(), LogicalSize::new(1, 2));
|
||||
assert_eq!(
|
||||
log_size,
|
||||
dpi::LogicalSize::from_physical(dpi::PhysicalSize::new(1.0, 2.0), 1.0)
|
||||
LogicalSize::from_physical(PhysicalSize::new(1.0, 2.0), 1.0)
|
||||
);
|
||||
assert_eq!(
|
||||
log_size,
|
||||
dpi::LogicalSize::from_physical(dpi::PhysicalSize::new(2.0, 4.0), 2.0)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::LogicalSize::from((2.0, 2.0)),
|
||||
dpi::LogicalSize::new(2.0, 2.0)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::LogicalSize::from([2.0, 3.0]),
|
||||
dpi::LogicalSize::new(2.0, 3.0)
|
||||
LogicalSize::from_physical(PhysicalSize::new(2.0, 4.0), 2.0)
|
||||
);
|
||||
assert_eq!(LogicalSize::from((2.0, 2.0)), LogicalSize::new(2.0, 2.0));
|
||||
assert_eq!(LogicalSize::from([2.0, 3.0]), LogicalSize::new(2.0, 3.0));
|
||||
|
||||
let x: (f64, f64) = log_size.into();
|
||||
assert_eq!(x, (1.0, 2.0));
|
||||
@@ -869,136 +1079,130 @@ mod tests {
|
||||
#[test]
|
||||
fn test_physical_size() {
|
||||
assert_eq!(
|
||||
dpi::PhysicalSize::from_logical(dpi::LogicalSize::new(1.0, 2.0), 1.0),
|
||||
dpi::PhysicalSize::new(1, 2)
|
||||
PhysicalSize::from_logical(LogicalSize::new(1.0, 2.0), 1.0),
|
||||
PhysicalSize::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::PhysicalSize::from_logical(dpi::LogicalSize::new(2.0, 4.0), 0.5),
|
||||
dpi::PhysicalSize::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::PhysicalSize::from((2.0, 2.0)),
|
||||
dpi::PhysicalSize::new(2.0, 2.0)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::PhysicalSize::from([2.0, 3.0]),
|
||||
dpi::PhysicalSize::new(2.0, 3.0)
|
||||
PhysicalSize::from_logical(LogicalSize::new(2.0, 4.0), 0.5),
|
||||
PhysicalSize::new(1, 2)
|
||||
);
|
||||
assert_eq!(PhysicalSize::from((2.0, 2.0)), PhysicalSize::new(2.0, 2.0));
|
||||
assert_eq!(PhysicalSize::from([2.0, 3.0]), PhysicalSize::new(2.0, 3.0));
|
||||
|
||||
let x: (f64, f64) = dpi::PhysicalSize::new(1, 2).into();
|
||||
let x: (f64, f64) = PhysicalSize::new(1, 2).into();
|
||||
assert_eq!(x, (1.0, 2.0));
|
||||
let x: [f64; 2] = dpi::PhysicalSize::new(1, 2).into();
|
||||
let x: [f64; 2] = PhysicalSize::new(1, 2).into();
|
||||
assert_eq!(x, [1.0, 2.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_size() {
|
||||
assert_eq!(
|
||||
dpi::Size::new(dpi::PhysicalSize::new(1, 2)),
|
||||
dpi::Size::Physical(dpi::PhysicalSize::new(1, 2))
|
||||
Size::new(PhysicalSize::new(1, 2)),
|
||||
Size::Physical(PhysicalSize::new(1, 2))
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Size::new(dpi::LogicalSize::new(1.0, 2.0)),
|
||||
dpi::Size::Logical(dpi::LogicalSize::new(1.0, 2.0))
|
||||
Size::new(LogicalSize::new(1.0, 2.0)),
|
||||
Size::Logical(LogicalSize::new(1.0, 2.0))
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
dpi::Size::new(dpi::PhysicalSize::new(1, 2)).to_logical::<f64>(1.0),
|
||||
dpi::LogicalSize::new(1.0, 2.0)
|
||||
Size::new(PhysicalSize::new(1, 2)).to_logical::<f64>(1.0),
|
||||
LogicalSize::new(1.0, 2.0)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Size::new(dpi::PhysicalSize::new(1, 2)).to_logical::<f64>(2.0),
|
||||
dpi::LogicalSize::new(0.5, 1.0)
|
||||
Size::new(PhysicalSize::new(1, 2)).to_logical::<f64>(2.0),
|
||||
LogicalSize::new(0.5, 1.0)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Size::new(dpi::LogicalSize::new(1.0, 2.0)).to_logical::<f64>(1.0),
|
||||
dpi::LogicalSize::new(1.0, 2.0)
|
||||
Size::new(LogicalSize::new(1.0, 2.0)).to_logical::<f64>(1.0),
|
||||
LogicalSize::new(1.0, 2.0)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
dpi::Size::new(dpi::PhysicalSize::new(1, 2)).to_physical::<u32>(1.0),
|
||||
dpi::PhysicalSize::new(1, 2)
|
||||
Size::new(PhysicalSize::new(1, 2)).to_physical::<u32>(1.0),
|
||||
PhysicalSize::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Size::new(dpi::PhysicalSize::new(1, 2)).to_physical::<u32>(2.0),
|
||||
dpi::PhysicalSize::new(1, 2)
|
||||
Size::new(PhysicalSize::new(1, 2)).to_physical::<u32>(2.0),
|
||||
PhysicalSize::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Size::new(dpi::LogicalSize::new(1.0, 2.0)).to_physical::<u32>(1.0),
|
||||
dpi::PhysicalSize::new(1, 2)
|
||||
Size::new(LogicalSize::new(1.0, 2.0)).to_physical::<u32>(1.0),
|
||||
PhysicalSize::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Size::new(dpi::LogicalSize::new(1.0, 2.0)).to_physical::<u32>(2.0),
|
||||
dpi::PhysicalSize::new(2, 4)
|
||||
Size::new(LogicalSize::new(1.0, 2.0)).to_physical::<u32>(2.0),
|
||||
PhysicalSize::new(2, 4)
|
||||
);
|
||||
|
||||
let small = dpi::Size::Physical((1, 2).into());
|
||||
let medium = dpi::Size::Logical((3, 4).into());
|
||||
let medium_physical = dpi::Size::new(medium.to_physical::<u32>(1.0));
|
||||
let large = dpi::Size::Physical((5, 6).into());
|
||||
assert_eq!(dpi::Size::clamp(medium, small, large, 1.0), medium_physical);
|
||||
assert_eq!(dpi::Size::clamp(small, medium, large, 1.0), medium_physical);
|
||||
assert_eq!(dpi::Size::clamp(large, small, medium, 1.0), medium_physical);
|
||||
let small = Size::Physical((1, 2).into());
|
||||
let medium = Size::Logical((3, 4).into());
|
||||
let medium_physical = Size::new(medium.to_physical::<u32>(1.0));
|
||||
let large = Size::Physical((5, 6).into());
|
||||
assert_eq!(Size::clamp(medium, small, large, 1.0), medium_physical);
|
||||
assert_eq!(Size::clamp(small, medium, large, 1.0), medium_physical);
|
||||
assert_eq!(Size::clamp(large, small, medium, 1.0), medium_physical);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_position() {
|
||||
assert_eq!(
|
||||
dpi::Position::new(dpi::PhysicalPosition::new(1, 2)),
|
||||
dpi::Position::Physical(dpi::PhysicalPosition::new(1, 2))
|
||||
Position::new(PhysicalPosition::new(1, 2)),
|
||||
Position::Physical(PhysicalPosition::new(1, 2))
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Position::new(dpi::LogicalPosition::new(1.0, 2.0)),
|
||||
dpi::Position::Logical(dpi::LogicalPosition::new(1.0, 2.0))
|
||||
Position::new(LogicalPosition::new(1.0, 2.0)),
|
||||
Position::Logical(LogicalPosition::new(1.0, 2.0))
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
dpi::Position::new(dpi::PhysicalPosition::new(1, 2)).to_logical::<f64>(1.0),
|
||||
dpi::LogicalPosition::new(1.0, 2.0)
|
||||
Position::new(PhysicalPosition::new(1, 2)).to_logical::<f64>(1.0),
|
||||
LogicalPosition::new(1.0, 2.0)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Position::new(dpi::PhysicalPosition::new(1, 2)).to_logical::<f64>(2.0),
|
||||
dpi::LogicalPosition::new(0.5, 1.0)
|
||||
Position::new(PhysicalPosition::new(1, 2)).to_logical::<f64>(2.0),
|
||||
LogicalPosition::new(0.5, 1.0)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Position::new(dpi::LogicalPosition::new(1.0, 2.0)).to_logical::<f64>(1.0),
|
||||
dpi::LogicalPosition::new(1.0, 2.0)
|
||||
Position::new(LogicalPosition::new(1.0, 2.0)).to_logical::<f64>(1.0),
|
||||
LogicalPosition::new(1.0, 2.0)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
dpi::Position::new(dpi::PhysicalPosition::new(1, 2)).to_physical::<u32>(1.0),
|
||||
dpi::PhysicalPosition::new(1, 2)
|
||||
Position::new(PhysicalPosition::new(1, 2)).to_physical::<u32>(1.0),
|
||||
PhysicalPosition::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Position::new(dpi::PhysicalPosition::new(1, 2)).to_physical::<u32>(2.0),
|
||||
dpi::PhysicalPosition::new(1, 2)
|
||||
Position::new(PhysicalPosition::new(1, 2)).to_physical::<u32>(2.0),
|
||||
PhysicalPosition::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Position::new(dpi::LogicalPosition::new(1.0, 2.0)).to_physical::<u32>(1.0),
|
||||
dpi::PhysicalPosition::new(1, 2)
|
||||
Position::new(LogicalPosition::new(1.0, 2.0)).to_physical::<u32>(1.0),
|
||||
PhysicalPosition::new(1, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
dpi::Position::new(dpi::LogicalPosition::new(1.0, 2.0)).to_physical::<u32>(2.0),
|
||||
dpi::PhysicalPosition::new(2, 4)
|
||||
Position::new(LogicalPosition::new(1.0, 2.0)).to_physical::<u32>(2.0),
|
||||
PhysicalPosition::new(2, 4)
|
||||
);
|
||||
}
|
||||
|
||||
// Eat coverage for the Debug impls et al
|
||||
#[test]
|
||||
fn ensure_attrs_do_not_panic() {
|
||||
let _ = format!("{:?}", dpi::LogicalPosition::<u32>::default().clone());
|
||||
HashSet::new().insert(dpi::LogicalPosition::<u32>::default());
|
||||
let _ = format!("{:?}", LogicalPosition::<u32>::default().clone());
|
||||
HashSet::new().insert(LogicalPosition::<u32>::default());
|
||||
|
||||
let _ = format!("{:?}", dpi::PhysicalPosition::<u32>::default().clone());
|
||||
HashSet::new().insert(dpi::PhysicalPosition::<u32>::default());
|
||||
let _ = format!("{:?}", PhysicalPosition::<u32>::default().clone());
|
||||
HashSet::new().insert(PhysicalPosition::<u32>::default());
|
||||
|
||||
let _ = format!("{:?}", dpi::LogicalSize::<u32>::default().clone());
|
||||
HashSet::new().insert(dpi::LogicalSize::<u32>::default());
|
||||
let _ = format!("{:?}", LogicalSize::<u32>::default().clone());
|
||||
HashSet::new().insert(LogicalSize::<u32>::default());
|
||||
|
||||
let _ = format!("{:?}", dpi::PhysicalSize::<u32>::default().clone());
|
||||
HashSet::new().insert(dpi::PhysicalSize::<u32>::default());
|
||||
let _ = format!("{:?}", PhysicalSize::<u32>::default().clone());
|
||||
HashSet::new().insert(PhysicalSize::<u32>::default());
|
||||
|
||||
let _ = format!("{:?}", dpi::Size::Physical((1, 2).into()).clone());
|
||||
let _ = format!("{:?}", dpi::Position::Physical((1, 2).into()).clone());
|
||||
let _ = format!("{:?}", Size::Physical((1, 2).into()).clone());
|
||||
let _ = format!("{:?}", Position::Physical((1, 2).into()).clone());
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,3 @@
|
||||
#[cfg(all(
|
||||
feature = "rwh_06",
|
||||
any(x11_platform, macos_platform, windows_platform)
|
||||
))]
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
#[cfg(all(
|
||||
feature = "rwh_06",
|
||||
any(x11_platform, macos_platform, windows_platform)
|
||||
@@ -13,58 +6,57 @@ mod fill;
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use winit::{
|
||||
dpi::{LogicalPosition, LogicalSize, Position},
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||
raw_window_handle::HasRawWindowHandle,
|
||||
window::{Window, WindowId},
|
||||
};
|
||||
use winit::dpi::{LogicalPosition, LogicalSize, Position};
|
||||
use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
|
||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||
use winit::raw_window_handle::HasRawWindowHandle;
|
||||
use winit::window::Window;
|
||||
|
||||
fn spawn_child_window(
|
||||
parent: &Window,
|
||||
event_loop: &EventLoopWindowTarget,
|
||||
windows: &mut HashMap<WindowId, Window>,
|
||||
) {
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
|
||||
let parent = parent.raw_window_handle().unwrap();
|
||||
let mut builder = Window::builder()
|
||||
let mut window_attributes = Window::default_attributes()
|
||||
.with_title("child window")
|
||||
.with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
|
||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||
.with_visible(true);
|
||||
// `with_parent_window` is unsafe. Parent window must be a valid window.
|
||||
builder = unsafe { builder.with_parent_window(Some(parent)) };
|
||||
let child_window = builder.build(event_loop).unwrap();
|
||||
window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
|
||||
|
||||
let id = child_window.id();
|
||||
windows.insert(id, child_window);
|
||||
println!("child window created with id: {id:?}");
|
||||
event_loop.create_window(window_attributes).unwrap()
|
||||
}
|
||||
|
||||
let mut windows = HashMap::new();
|
||||
|
||||
let event_loop: EventLoop<()> = EventLoop::new().unwrap();
|
||||
let parent_window = Window::builder()
|
||||
.with_title("parent window")
|
||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
let mut parent_window_id = None;
|
||||
|
||||
println!("parent window: {parent_window:?})");
|
||||
event_loop.run(move |event: Event<()>, event_loop| {
|
||||
match event {
|
||||
Event::Resumed => {
|
||||
let attributes = Window::default_attributes()
|
||||
.with_title("parent window")
|
||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32));
|
||||
let window = event_loop.create_window(attributes).unwrap();
|
||||
|
||||
event_loop.run(move |event: Event<()>, elwt| {
|
||||
if let Event::WindowEvent { event, window_id } = event {
|
||||
match event {
|
||||
parent_window_id = Some(window.id());
|
||||
|
||||
println!("Parent window id: {parent_window_id:?})");
|
||||
windows.insert(window.id(), window);
|
||||
}
|
||||
Event::WindowEvent { window_id, event } => match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
windows.clear();
|
||||
elwt.exit();
|
||||
event_loop.exit();
|
||||
}
|
||||
WindowEvent::CursorEntered { device_id: _ } => {
|
||||
// On x11, println when the cursor entered in a window even if the child window is created
|
||||
// by some key inputs.
|
||||
// the child windows are always placed at (0, 0) with size (200, 200) in the parent window,
|
||||
// so we also can see this log when we move the cursor arround (200, 200) in parent window.
|
||||
// so we also can see this log when we move the cursor around (200, 200) in parent window.
|
||||
println!("cursor entered in the window {window_id:?}");
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
@@ -75,7 +67,11 @@ fn main() -> Result<(), impl std::error::Error> {
|
||||
},
|
||||
..
|
||||
} => {
|
||||
spawn_child_window(&parent_window, elwt, &mut windows);
|
||||
let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
|
||||
let child_window = spawn_child_window(parent_window, event_loop);
|
||||
let child_id = child_window.id();
|
||||
println!("Child window created with id: {child_id:?}");
|
||||
windows.insert(child_id, child_window);
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
if let Some(window) = windows.get(&window_id) {
|
||||
@@ -83,15 +79,16 @@ fn main() -> Result<(), impl std::error::Error> {
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(all(
|
||||
#[cfg(all(
|
||||
feature = "rwh_06",
|
||||
any(x11_platform, macos_platform, windows_platform)
|
||||
)))]
|
||||
not(any(x11_platform, macos_platform, windows_platform))
|
||||
))]
|
||||
fn main() {
|
||||
panic!("This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature enabled.");
|
||||
}
|
||||
147
examples/control_flow.rs
Normal file
@@ -0,0 +1,147 @@
|
||||
#![allow(clippy::single_match)]
|
||||
|
||||
use std::thread;
|
||||
#[cfg(not(web_platform))]
|
||||
use std::time;
|
||||
|
||||
#[cfg(web_platform)]
|
||||
use web_time as time;
|
||||
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent};
|
||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
use winit::keyboard::{Key, NamedKey};
|
||||
use winit::window::{Window, WindowId};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
|
||||
const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
#[default]
|
||||
Wait,
|
||||
WaitUntil,
|
||||
Poll,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
println!("Press '1' to switch to Wait mode.");
|
||||
println!("Press '2' to switch to WaitUntil mode.");
|
||||
println!("Press '3' to switch to Poll mode.");
|
||||
println!("Press 'R' to toggle request_redraw() calls.");
|
||||
println!("Press 'Esc' to close the window.");
|
||||
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let mut app = ControlFlowDemo::default();
|
||||
event_loop.run_app(&mut app)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ControlFlowDemo {
|
||||
mode: Mode,
|
||||
request_redraw: bool,
|
||||
wait_cancelled: bool,
|
||||
close_requested: bool,
|
||||
window: Option<Window>,
|
||||
}
|
||||
|
||||
impl ApplicationHandler for ControlFlowDemo {
|
||||
fn new_events(&mut self, _event_loop: &ActiveEventLoop, cause: StartCause) {
|
||||
println!("new_events: {cause:?}");
|
||||
|
||||
self.wait_cancelled = match cause {
|
||||
StartCause::WaitCancelled { .. } => self.mode == Mode::WaitUntil,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let window_attributes = Window::default_attributes().with_title(
|
||||
"Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
|
||||
);
|
||||
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
_event_loop: &ActiveEventLoop,
|
||||
_window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
println!("{event:?}");
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
self.close_requested = true;
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: key,
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => match key.as_ref() {
|
||||
// WARNING: Consider using `key_without_modifiers()` if available on your platform.
|
||||
// See the `key_binding` example
|
||||
Key::Character("1") => {
|
||||
self.mode = Mode::Wait;
|
||||
println!("\nmode: {:?}\n", self.mode);
|
||||
}
|
||||
Key::Character("2") => {
|
||||
self.mode = Mode::WaitUntil;
|
||||
println!("\nmode: {:?}\n", self.mode);
|
||||
}
|
||||
Key::Character("3") => {
|
||||
self.mode = Mode::Poll;
|
||||
println!("\nmode: {:?}\n", self.mode);
|
||||
}
|
||||
Key::Character("r") => {
|
||||
self.request_redraw = !self.request_redraw;
|
||||
println!("\nrequest_redraw: {}\n", self.request_redraw);
|
||||
}
|
||||
Key::Named(NamedKey::Escape) => {
|
||||
self.close_requested = true;
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
let window = self.window.as_ref().unwrap();
|
||||
window.pre_present_notify();
|
||||
fill::fill_window(window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.request_redraw && !self.wait_cancelled && !self.close_requested {
|
||||
self.window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
|
||||
match self.mode {
|
||||
Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
|
||||
Mode::WaitUntil => {
|
||||
if !self.wait_cancelled {
|
||||
event_loop
|
||||
.set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
|
||||
}
|
||||
}
|
||||
Mode::Poll => {
|
||||
thread::sleep(POLL_SLEEP_TIME);
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
}
|
||||
};
|
||||
|
||||
if self.close_requested {
|
||||
event_loop.exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 159 B After Width: | Height: | Size: 159 B |
|
Before Width: | Height: | Size: 129 B After Width: | Height: | Size: 129 B |
|
Before Width: | Height: | Size: 229 B After Width: | Height: | Size: 229 B |
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 2.9 KiB |
84
examples/pump_events.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
#![allow(clippy::single_match)]
|
||||
|
||||
// Limit this example to only compatible platforms.
|
||||
#[cfg(any(
|
||||
windows_platform,
|
||||
macos_platform,
|
||||
x11_platform,
|
||||
wayland_platform,
|
||||
android_platform,
|
||||
))]
|
||||
fn main() -> std::process::ExitCode {
|
||||
use std::{process::ExitCode, thread::sleep, time::Duration};
|
||||
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||
use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
|
||||
use winit::window::{Window, WindowId};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
#[derive(Default)]
|
||||
struct PumpDemo {
|
||||
window: Option<Window>,
|
||||
}
|
||||
|
||||
impl ApplicationHandler for PumpDemo {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let window_attributes = Window::default_attributes().with_title("A fantastic window!");
|
||||
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
println!("{event:?}");
|
||||
|
||||
let window = match self.window.as_ref() {
|
||||
Some(window) => window,
|
||||
None => return,
|
||||
};
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(window);
|
||||
window.request_redraw();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut event_loop = EventLoop::new().unwrap();
|
||||
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let mut app = PumpDemo::default();
|
||||
|
||||
loop {
|
||||
let timeout = Some(Duration::ZERO);
|
||||
let status = event_loop.pump_app_events(timeout, &mut app);
|
||||
|
||||
if let PumpStatus::Exit(exit_code) = status {
|
||||
break ExitCode::from(exit_code as u8);
|
||||
}
|
||||
|
||||
// Sleep for 1/60 second to simulate application work
|
||||
//
|
||||
// Since `pump_events` doesn't block it will be important to
|
||||
// throttle the loop in the app somehow.
|
||||
println!("Update()");
|
||||
sleep(Duration::from_millis(16));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(ios_platform, web_platform, orbital_platform))]
|
||||
fn main() {
|
||||
println!("This platform doesn't support pump_events.");
|
||||
}
|
||||
98
examples/run_on_demand.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
#![allow(clippy::single_match)]
|
||||
|
||||
// Limit this example to only compatible platforms.
|
||||
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform,))]
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
use std::time::Duration;
|
||||
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||
use winit::platform::run_on_demand::EventLoopExtRunOnDemand;
|
||||
use winit::window::{Window, WindowId};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
#[derive(Default)]
|
||||
struct App {
|
||||
idx: usize,
|
||||
window_id: Option<WindowId>,
|
||||
window: Option<Window>,
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
if let Some(window) = self.window.as_ref() {
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let window_attributes = Window::default_attributes()
|
||||
.with_title("Fantastic window number one!")
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0));
|
||||
let window = event_loop.create_window(window_attributes).unwrap();
|
||||
self.window_id = Some(window.id());
|
||||
self.window = Some(window);
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
if event == WindowEvent::Destroyed && self.window_id == Some(window_id) {
|
||||
println!(
|
||||
"--------------------------------------------------------- Window {} Destroyed",
|
||||
self.idx
|
||||
);
|
||||
self.window_id = None;
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
|
||||
let window = match self.window.as_mut() {
|
||||
Some(window) => window,
|
||||
None => return,
|
||||
};
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
println!("--------------------------------------------------------- Window {} CloseRequested", self.idx);
|
||||
fill::cleanup_window(window);
|
||||
self.window = None;
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let mut event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let mut app = App {
|
||||
idx: 1,
|
||||
..Default::default()
|
||||
};
|
||||
event_loop.run_app_on_demand(&mut app)?;
|
||||
|
||||
println!("--------------------------------------------------------- Finished first loop");
|
||||
println!("--------------------------------------------------------- Waiting 5 seconds");
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
|
||||
app.idx += 1;
|
||||
event_loop.run_app_on_demand(&mut app)?;
|
||||
println!("--------------------------------------------------------- Finished second loop");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(any(windows_platform, macos_platform, x11_platform, wayland_platform,)))]
|
||||
fn main() {
|
||||
println!("This example is not supported on this platform");
|
||||
}
|
||||
@@ -28,7 +28,7 @@ mod platform {
|
||||
// ManuallyDrop to prevent destructors from running.
|
||||
//
|
||||
// A static, thread-local map of graphics contexts to open windows.
|
||||
static GC: ManuallyDrop<RefCell<Option<GraphicsContext>>> = ManuallyDrop::new(RefCell::new(None));
|
||||
static GC: ManuallyDrop<RefCell<Option<GraphicsContext>>> = const { ManuallyDrop::new(RefCell::new(None)) };
|
||||
}
|
||||
|
||||
/// The graphics context used to draw to a window.
|
||||
984
examples/window.rs
Normal file
@@ -0,0 +1,984 @@
|
||||
//! Simple winit application.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::fmt::Debug;
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
use std::num::NonZeroU32;
|
||||
use std::path::Path;
|
||||
|
||||
use cursor_icon::CursorIcon;
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
use rwh_05::HasRawDisplayHandle;
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
use softbuffer::{Context, Surface};
|
||||
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
|
||||
use winit::event::{DeviceEvent, DeviceId, Ime, WindowEvent};
|
||||
use winit::event::{MouseButton, MouseScrollDelta};
|
||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||
use winit::keyboard::{Key, ModifiersState};
|
||||
use winit::window::{
|
||||
Cursor, CursorGrabMode, CustomCursor, CustomCursorSource, Fullscreen, Icon, ResizeDirection,
|
||||
Theme,
|
||||
};
|
||||
use winit::window::{Window, WindowId};
|
||||
|
||||
#[cfg(macos_platform)]
|
||||
use winit::platform::macos::{OptionAsAlt, WindowAttributesExtMacOS, WindowExtMacOS};
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
use winit::platform::startup_notify::{
|
||||
self, EventLoopExtStartupNotify, WindowAttributesExtStartupNotify, WindowExtStartupNotify,
|
||||
};
|
||||
|
||||
/// The amount of points to around the window for drag resize direction calculations.
|
||||
const BORDER_SIZE: f64 = 20.;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let event_loop = EventLoop::<UserEvent>::with_user_event().build()?;
|
||||
let _event_loop_proxy = event_loop.create_proxy();
|
||||
|
||||
// Wire the user event from another thread.
|
||||
#[cfg(not(web_platform))]
|
||||
std::thread::spawn(move || {
|
||||
// Wake up the `event_loop` once every second and dispatch a custom event
|
||||
// from a different thread.
|
||||
println!("Starting to send user event every second");
|
||||
loop {
|
||||
let _ = _event_loop_proxy.send_event(UserEvent::WakeUp);
|
||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||
}
|
||||
});
|
||||
|
||||
let mut state = Application::new(&event_loop);
|
||||
|
||||
event_loop.run_app(&mut state).map_err(Into::into)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum UserEvent {
|
||||
WakeUp,
|
||||
}
|
||||
|
||||
/// Application state and event handling.
|
||||
struct Application {
|
||||
/// Custom cursors assets.
|
||||
custom_cursors: Vec<CustomCursor>,
|
||||
/// Application icon.
|
||||
icon: Icon,
|
||||
windows: HashMap<WindowId, WindowState>,
|
||||
/// Drawing context.
|
||||
///
|
||||
/// With OpenGL it could be EGLDisplay.
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
context: Option<Context>,
|
||||
}
|
||||
|
||||
impl Application {
|
||||
fn new<T>(event_loop: &EventLoop<T>) -> Self {
|
||||
// SAFETY: we drop the context right before the event loop is stopped, thus making it safe.
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
let context = Some(unsafe { Context::from_raw(event_loop.raw_display_handle()).unwrap() });
|
||||
|
||||
// You'll have to choose an icon size at your own discretion. On X11, the desired size varies
|
||||
// by WM, and on Windows, you still have to account for screen scaling. Here we use 32px,
|
||||
// since it seems to work well enough in most cases. Be careful about going too high, or
|
||||
// you'll be bitten by the low-quality downscaling built into the WM.
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/data/icon.png");
|
||||
|
||||
let icon = load_icon(Path::new(path));
|
||||
|
||||
println!("Loading cursor assets");
|
||||
let custom_cursors = vec![
|
||||
event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/cross.png"))),
|
||||
event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/cross2.png"))),
|
||||
event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/gradient.png"))),
|
||||
];
|
||||
|
||||
Self {
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
context,
|
||||
custom_cursors,
|
||||
icon,
|
||||
windows: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_window(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_tab_id: Option<String>,
|
||||
) -> Result<WindowId, Box<dyn Error>> {
|
||||
// TODO read-out activation token.
|
||||
|
||||
#[allow(unused_mut)]
|
||||
let mut window_attributes = Window::default_attributes()
|
||||
.with_title("Winit window")
|
||||
.with_transparent(true)
|
||||
.with_window_icon(Some(self.icon.clone()));
|
||||
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
if let Some(token) = event_loop.read_token_from_env() {
|
||||
startup_notify::reset_activation_token_env();
|
||||
println!("Using token {:?} to activate a window", token);
|
||||
window_attributes = window_attributes.with_activation_token(token);
|
||||
}
|
||||
|
||||
#[cfg(macos_platform)]
|
||||
if let Some(tab_id) = _tab_id {
|
||||
window_attributes = window_attributes.with_tabbing_identifier(&tab_id);
|
||||
}
|
||||
|
||||
let window = event_loop.create_window(window_attributes)?;
|
||||
|
||||
#[cfg(ios_platform)]
|
||||
{
|
||||
use winit::platform::ios::WindowExtIOS;
|
||||
window.recognize_doubletap_gesture(true);
|
||||
window.recognize_pinch_gesture(true);
|
||||
window.recognize_rotation_gesture(true);
|
||||
}
|
||||
|
||||
let window_state = WindowState::new(self, window)?;
|
||||
let window_id = window_state.window.id();
|
||||
println!("Created new window with id={window_id:?}");
|
||||
self.windows.insert(window_id, window_state);
|
||||
Ok(window_id)
|
||||
}
|
||||
|
||||
fn handle_action(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, action: Action) {
|
||||
// let cursor_position = self.cursor_position;
|
||||
let window = self.windows.get_mut(&window_id).unwrap();
|
||||
println!("Executing action: {action:?}");
|
||||
match action {
|
||||
Action::CloseWindow => {
|
||||
let _ = self.windows.remove(&window_id);
|
||||
}
|
||||
Action::CreateNewWindow => {
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
if let Err(err) = window.window.request_activation_token() {
|
||||
println!("Failed to get activation token: {err}");
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(err) = self.create_window(event_loop, None) {
|
||||
eprintln!("Error creating new window: {err}");
|
||||
}
|
||||
}
|
||||
Action::ToggleResizeIncrements => window.toggle_resize_increments(),
|
||||
Action::ToggleCursorVisibility => window.toggle_cursor_visibility(),
|
||||
Action::ToggleResizable => window.toggle_resizable(),
|
||||
Action::ToggleDecorations => window.toggle_decorations(),
|
||||
Action::ToggleFullscreen => window.toggle_fullscreen(),
|
||||
Action::ToggleMaximize => window.toggle_maximize(),
|
||||
Action::ToggleImeInput => window.toggle_ime(),
|
||||
Action::Minimize => window.minimize(),
|
||||
Action::NextCursor => window.next_cursor(),
|
||||
Action::NextCustomCursor => window.next_custom_cursor(&self.custom_cursors),
|
||||
Action::CycleCursorGrab => window.cycle_cursor_grab(),
|
||||
Action::DragWindow => window.drag_window(),
|
||||
Action::DragResizeWindow => window.drag_resize_window(),
|
||||
Action::ShowWindowMenu => window.show_menu(),
|
||||
Action::PrintHelp => self.print_help(),
|
||||
#[cfg(macos_platform)]
|
||||
Action::CycleOptionAsAlt => window.cycle_option_as_alt(),
|
||||
#[cfg(macos_platform)]
|
||||
Action::CreateNewTab => {
|
||||
let tab_id = window.window.tabbing_identifier();
|
||||
if let Err(err) = self.create_window(event_loop, Some(tab_id)) {
|
||||
eprintln!("Error creating new window: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dump_monitors(&self, event_loop: &ActiveEventLoop) {
|
||||
println!("Monitors information");
|
||||
let primary_monitor = event_loop.primary_monitor();
|
||||
for monitor in event_loop.available_monitors() {
|
||||
let intro = if primary_monitor.as_ref() == Some(&monitor) {
|
||||
"Primary monitor"
|
||||
} else {
|
||||
"Monitor"
|
||||
};
|
||||
|
||||
if let Some(name) = monitor.name() {
|
||||
println!("{intro}: {name}");
|
||||
} else {
|
||||
println!("{intro}: [no name]");
|
||||
}
|
||||
|
||||
let PhysicalSize { width, height } = monitor.size();
|
||||
print!(" Current mode: {width}x{height}");
|
||||
if let Some(m_hz) = monitor.refresh_rate_millihertz() {
|
||||
println!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
|
||||
} else {
|
||||
println!();
|
||||
}
|
||||
|
||||
let PhysicalPosition { x, y } = monitor.position();
|
||||
println!(" Position: {x},{y}");
|
||||
|
||||
println!(" Scale factor: {}", monitor.scale_factor());
|
||||
|
||||
println!(" Available modes (width x height x bit-depth):");
|
||||
for mode in monitor.video_modes() {
|
||||
let PhysicalSize { width, height } = mode.size();
|
||||
let bits = mode.bit_depth();
|
||||
let m_hz = mode.refresh_rate_millihertz();
|
||||
println!(
|
||||
" {width}x{height}x{bits} @ {}.{} Hz",
|
||||
m_hz / 1000,
|
||||
m_hz % 1000
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Process the key binding.
|
||||
fn process_key_binding(key: &str, mods: &ModifiersState) -> Option<Action> {
|
||||
KEY_BINDINGS.iter().find_map(|binding| {
|
||||
binding
|
||||
.is_triggered_by(&key, mods)
|
||||
.then_some(binding.action)
|
||||
})
|
||||
}
|
||||
|
||||
/// Process mouse binding.
|
||||
fn process_mouse_binding(button: MouseButton, mods: &ModifiersState) -> Option<Action> {
|
||||
MOUSE_BINDINGS.iter().find_map(|binding| {
|
||||
binding
|
||||
.is_triggered_by(&button, mods)
|
||||
.then_some(binding.action)
|
||||
})
|
||||
}
|
||||
|
||||
fn print_help(&self) {
|
||||
println!("Keyboard bindings:");
|
||||
for binding in KEY_BINDINGS {
|
||||
println!(
|
||||
"{}{:<10} - {} ({})",
|
||||
modifiers_to_string(binding.mods),
|
||||
binding.trigger,
|
||||
binding.action,
|
||||
binding.action.help(),
|
||||
);
|
||||
}
|
||||
println!("Mouse bindings:");
|
||||
for binding in MOUSE_BINDINGS {
|
||||
println!(
|
||||
"{}{:<10} - {} ({})",
|
||||
modifiers_to_string(binding.mods),
|
||||
mouse_button_to_string(binding.trigger),
|
||||
binding.action,
|
||||
binding.action.help(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler<UserEvent> for Application {
|
||||
fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: UserEvent) {
|
||||
println!("User event: {event:?}");
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
let window = match self.windows.get_mut(&window_id) {
|
||||
Some(window) => window,
|
||||
None => return,
|
||||
};
|
||||
|
||||
match event {
|
||||
WindowEvent::Resized(size) => {
|
||||
window.resize(size);
|
||||
}
|
||||
WindowEvent::Focused(focused) => {
|
||||
if focused {
|
||||
println!("Window={window_id:?} fosused");
|
||||
} else {
|
||||
println!("Window={window_id:?} unfosused");
|
||||
}
|
||||
}
|
||||
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||
println!("Window={window_id:?} changed scale to {scale_factor}");
|
||||
}
|
||||
WindowEvent::ThemeChanged(theme) => {
|
||||
println!("Theme changed to {theme:?}");
|
||||
window.set_theme(theme);
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
if let Err(err) = window.draw() {
|
||||
eprintln!("Error drawing window: {err}");
|
||||
}
|
||||
}
|
||||
WindowEvent::Occluded(occluded) => {
|
||||
window.set_occluded(occluded);
|
||||
}
|
||||
WindowEvent::CloseRequested => {
|
||||
println!("Closing Window={window_id:?}");
|
||||
self.windows.remove(&window_id);
|
||||
}
|
||||
WindowEvent::ModifiersChanged(modifiers) => {
|
||||
window.modifiers = modifiers.state();
|
||||
println!("Modifiers changed to {:?}", window.modifiers);
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => {
|
||||
println!("Mouse wheel Line Delta: ({x},{y})");
|
||||
}
|
||||
MouseScrollDelta::PixelDelta(px) => {
|
||||
println!("Mouse wheel Pixel Delta: ({},{})", px.x, px.y);
|
||||
}
|
||||
},
|
||||
WindowEvent::KeyboardInput {
|
||||
event,
|
||||
is_synthetic: false,
|
||||
..
|
||||
} => {
|
||||
let mods = window.modifiers;
|
||||
|
||||
// Dispatch actions only on press.
|
||||
if event.state.is_pressed() {
|
||||
let action = if let Key::Character(ch) = event.logical_key.as_ref() {
|
||||
Self::process_key_binding(&ch.to_uppercase(), &mods)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(action) = action {
|
||||
self.handle_action(event_loop, window_id, action);
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { button, state, .. } => {
|
||||
let mods = window.modifiers;
|
||||
if let Some(action) = state
|
||||
.is_pressed()
|
||||
.then(|| Self::process_mouse_binding(button, &mods))
|
||||
.flatten()
|
||||
{
|
||||
self.handle_action(event_loop, window_id, action);
|
||||
}
|
||||
}
|
||||
WindowEvent::CursorLeft { .. } => {
|
||||
println!("Cursor left Window={window_id:?}");
|
||||
window.cursor_left();
|
||||
}
|
||||
WindowEvent::CursorMoved { position, .. } => {
|
||||
println!("Moved cursor to {position:?}");
|
||||
window.cursor_moved(position);
|
||||
}
|
||||
WindowEvent::ActivationTokenDone { token: _token, .. } => {
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
{
|
||||
startup_notify::set_activation_token_env(_token);
|
||||
if let Err(err) = self.create_window(event_loop, None) {
|
||||
eprintln!("Error creating new window: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::Ime(event) => match event {
|
||||
Ime::Enabled => println!("IME enabled for Window={window_id:?}"),
|
||||
Ime::Preedit(text, caret_pos) => {
|
||||
println!("Preedit: {}, with caret at {:?}", text, caret_pos);
|
||||
}
|
||||
Ime::Commit(text) => {
|
||||
println!("Committed: {}", text);
|
||||
}
|
||||
Ime::Disabled => println!("IME disabled for Window={window_id:?}"),
|
||||
},
|
||||
WindowEvent::PinchGesture { delta, .. } => {
|
||||
window.zoom += delta;
|
||||
let zoom = window.zoom;
|
||||
if delta > 0.0 {
|
||||
println!("Zoomed in {delta:.5} (now: {zoom:.5})");
|
||||
} else {
|
||||
println!("Zoomed out {delta:.5} (now: {zoom:.5})");
|
||||
}
|
||||
}
|
||||
WindowEvent::RotationGesture { delta, .. } => {
|
||||
window.rotated += delta;
|
||||
let rotated = window.rotated;
|
||||
if delta > 0.0 {
|
||||
println!("Rotated counterclockwise {delta:.5} (now: {rotated:.5})");
|
||||
} else {
|
||||
println!("Rotated clockwise {delta:.5} (now: {rotated:.5})");
|
||||
}
|
||||
}
|
||||
WindowEvent::DoubleTapGesture { .. } => {
|
||||
println!("Smart zoom");
|
||||
}
|
||||
WindowEvent::TouchpadPressure { .. }
|
||||
| WindowEvent::HoveredFileCancelled
|
||||
| WindowEvent::KeyboardInput { .. }
|
||||
| WindowEvent::CursorEntered { .. }
|
||||
| WindowEvent::AxisMotion { .. }
|
||||
| WindowEvent::DroppedFile(_)
|
||||
| WindowEvent::HoveredFile(_)
|
||||
| WindowEvent::Destroyed
|
||||
| WindowEvent::Touch(_)
|
||||
| WindowEvent::Moved(_) => (),
|
||||
}
|
||||
}
|
||||
|
||||
fn device_event(
|
||||
&mut self,
|
||||
_event_loop: &ActiveEventLoop,
|
||||
device_id: DeviceId,
|
||||
event: DeviceEvent,
|
||||
) {
|
||||
println!("Device {device_id:?} event: {event:?}");
|
||||
}
|
||||
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
println!("Resumed the event loop");
|
||||
self.dump_monitors(event_loop);
|
||||
|
||||
// Create initial window.
|
||||
self.create_window(event_loop, None)
|
||||
.expect("failed to create initial window");
|
||||
|
||||
self.print_help();
|
||||
}
|
||||
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.windows.is_empty() {
|
||||
println!("No windows left, exiting...");
|
||||
event_loop.exit();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
// We must drop the context here.
|
||||
self.context = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// State of the window.
|
||||
struct WindowState {
|
||||
/// IME input.
|
||||
ime: bool,
|
||||
/// Render surface.
|
||||
///
|
||||
/// NOTE: This surface must be dropped before the `Window`.
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
surface: Surface,
|
||||
/// The actual winit Window.
|
||||
window: Window,
|
||||
/// The window theme we're drawing with.
|
||||
theme: Theme,
|
||||
/// Cursor position over the window.
|
||||
cursor_position: Option<PhysicalPosition<f64>>,
|
||||
/// Window modifiers state.
|
||||
modifiers: ModifiersState,
|
||||
/// Occlusion state of the window.
|
||||
occluded: bool,
|
||||
/// Current cursor grab mode.
|
||||
cursor_grab: CursorGrabMode,
|
||||
/// The amount of zoom into window.
|
||||
zoom: f64,
|
||||
/// The amount of rotation of the window.
|
||||
rotated: f32,
|
||||
|
||||
#[cfg(macos_platform)]
|
||||
option_as_alt: OptionAsAlt,
|
||||
|
||||
// Cursor states.
|
||||
named_idx: usize,
|
||||
custom_idx: usize,
|
||||
cursor_hidden: bool,
|
||||
}
|
||||
|
||||
impl WindowState {
|
||||
fn new(app: &Application, window: Window) -> Result<Self, Box<dyn Error>> {
|
||||
// SAFETY: the surface is dropped before the `window` which provided it with handle, thus
|
||||
// it doesn't outlive it.
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
let surface = unsafe { Surface::new(app.context.as_ref().unwrap(), &window)? };
|
||||
|
||||
let theme = window.theme().unwrap_or(Theme::Dark);
|
||||
println!("Theme: {theme:?}");
|
||||
let named_idx = 0;
|
||||
window.set_cursor(CURSORS[named_idx]);
|
||||
|
||||
// Allow IME out of the box.
|
||||
let ime = true;
|
||||
window.set_ime_allowed(ime);
|
||||
|
||||
let size = window.inner_size();
|
||||
let mut state = Self {
|
||||
#[cfg(macos_platform)]
|
||||
option_as_alt: window.option_as_alt(),
|
||||
custom_idx: app.custom_cursors.len() - 1,
|
||||
cursor_grab: CursorGrabMode::None,
|
||||
named_idx,
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
surface,
|
||||
window,
|
||||
theme,
|
||||
ime,
|
||||
cursor_position: Default::default(),
|
||||
cursor_hidden: Default::default(),
|
||||
modifiers: Default::default(),
|
||||
occluded: Default::default(),
|
||||
rotated: Default::default(),
|
||||
zoom: Default::default(),
|
||||
};
|
||||
|
||||
state.resize(size);
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
pub fn toggle_ime(&mut self) {
|
||||
self.ime = !self.ime;
|
||||
self.window.set_ime_allowed(self.ime);
|
||||
if let Some(position) = self.ime.then_some(self.cursor_position).flatten() {
|
||||
self.window
|
||||
.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn minimize(&mut self) {
|
||||
self.window.set_minimized(true);
|
||||
}
|
||||
|
||||
pub fn cursor_moved(&mut self, position: PhysicalPosition<f64>) {
|
||||
self.cursor_position = Some(position);
|
||||
if self.ime {
|
||||
self.window
|
||||
.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cursor_left(&mut self) {
|
||||
self.cursor_position = None;
|
||||
}
|
||||
|
||||
/// Toggle maximized.
|
||||
fn toggle_maximize(&self) {
|
||||
let maximized = self.window.is_maximized();
|
||||
self.window.set_maximized(!maximized);
|
||||
}
|
||||
|
||||
/// Toggle window decorations.
|
||||
fn toggle_decorations(&self) {
|
||||
let decorated = self.window.is_decorated();
|
||||
self.window.set_decorations(!decorated);
|
||||
}
|
||||
|
||||
/// Toggle window resizable state.
|
||||
fn toggle_resizable(&self) {
|
||||
let resizable = self.window.is_resizable();
|
||||
self.window.set_resizable(!resizable);
|
||||
}
|
||||
|
||||
/// Toggle cursor visibility
|
||||
fn toggle_cursor_visibility(&mut self) {
|
||||
self.cursor_hidden = !self.cursor_hidden;
|
||||
self.window.set_cursor_visible(!self.cursor_hidden);
|
||||
}
|
||||
|
||||
/// Toggle resize increments on a window.
|
||||
fn toggle_resize_increments(&mut self) {
|
||||
let new_increments = match self.window.resize_increments() {
|
||||
Some(_) => None,
|
||||
None => Some(LogicalSize::new(25.0, 25.0)),
|
||||
};
|
||||
println!("Had increments: {}", new_increments.is_none());
|
||||
self.window.set_resize_increments(new_increments);
|
||||
}
|
||||
|
||||
/// Toggle fullscreen.
|
||||
fn toggle_fullscreen(&self) {
|
||||
let fullscreen = if self.window.fullscreen().is_some() {
|
||||
None
|
||||
} else {
|
||||
Some(Fullscreen::Borderless(None))
|
||||
};
|
||||
|
||||
self.window.set_fullscreen(fullscreen);
|
||||
}
|
||||
|
||||
/// Cycle through the grab modes ignoring errors.
|
||||
fn cycle_cursor_grab(&mut self) {
|
||||
self.cursor_grab = match self.cursor_grab {
|
||||
CursorGrabMode::None => CursorGrabMode::Confined,
|
||||
CursorGrabMode::Confined => CursorGrabMode::Locked,
|
||||
CursorGrabMode::Locked => CursorGrabMode::None,
|
||||
};
|
||||
println!("Changing cursor grab mode to {:?}", self.cursor_grab);
|
||||
if let Err(err) = self.window.set_cursor_grab(self.cursor_grab) {
|
||||
eprintln!("Error setting cursor grab: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(macos_platform)]
|
||||
fn cycle_option_as_alt(&mut self) {
|
||||
self.option_as_alt = match self.option_as_alt {
|
||||
OptionAsAlt::None => OptionAsAlt::OnlyLeft,
|
||||
OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight,
|
||||
OptionAsAlt::OnlyRight => OptionAsAlt::Both,
|
||||
OptionAsAlt::Both => OptionAsAlt::None,
|
||||
};
|
||||
println!("Setting option as alt {:?}", self.option_as_alt);
|
||||
self.window.set_option_as_alt(self.option_as_alt);
|
||||
}
|
||||
|
||||
/// Pick the next cursor.
|
||||
fn next_cursor(&mut self) {
|
||||
self.named_idx = (self.named_idx + 1) % CURSORS.len();
|
||||
println!("Setting cursor to \"{:?}\"", CURSORS[self.named_idx]);
|
||||
self.window
|
||||
.set_cursor(Cursor::Icon(CURSORS[self.named_idx]));
|
||||
}
|
||||
|
||||
/// Pick the next custom cursor.
|
||||
fn next_custom_cursor(&mut self, custom_cursors: &[CustomCursor]) {
|
||||
self.custom_idx = (self.custom_idx + 1) % custom_cursors.len();
|
||||
let cursor = Cursor::Custom(custom_cursors[self.custom_idx].clone());
|
||||
self.window.set_cursor(cursor);
|
||||
}
|
||||
|
||||
/// Resize the window to the new size.
|
||||
fn resize(&mut self, _size: PhysicalSize<u32>) {
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
{
|
||||
let (width, height) =
|
||||
match (NonZeroU32::new(_size.width), NonZeroU32::new(_size.height)) {
|
||||
(Some(width), Some(height)) => (width, height),
|
||||
_ => return,
|
||||
};
|
||||
self.surface
|
||||
.resize(width, height)
|
||||
.expect("failed to resize inner buffer");
|
||||
}
|
||||
self.window.request_redraw();
|
||||
}
|
||||
|
||||
/// Change the theme.
|
||||
fn set_theme(&mut self, theme: Theme) {
|
||||
self.theme = theme;
|
||||
self.window.request_redraw();
|
||||
}
|
||||
|
||||
/// Show window menu.
|
||||
fn show_menu(&self) {
|
||||
if let Some(position) = self.cursor_position {
|
||||
self.window.show_window_menu(position);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drag the window.
|
||||
fn drag_window(&self) {
|
||||
if let Err(err) = self.window.drag_window() {
|
||||
println!("Error starting window drag: {err}");
|
||||
} else {
|
||||
println!("Dragging window Window={:?}", self.window.id());
|
||||
}
|
||||
}
|
||||
|
||||
/// Drag-resize the window.
|
||||
fn drag_resize_window(&self) {
|
||||
let position = match self.cursor_position {
|
||||
Some(position) => position,
|
||||
None => {
|
||||
println!("Drag-resize requires cursor to be inside the window");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let win_size = self.window.inner_size();
|
||||
let border_size = BORDER_SIZE * self.window.scale_factor();
|
||||
|
||||
let x_direction = if position.x < border_size {
|
||||
ResizeDirection::West
|
||||
} else if position.x > (win_size.width as f64 - border_size) {
|
||||
ResizeDirection::East
|
||||
} else {
|
||||
// Use arbitrary direction instead of None for simplicity.
|
||||
ResizeDirection::SouthEast
|
||||
};
|
||||
|
||||
let y_direction = if position.y < border_size {
|
||||
ResizeDirection::North
|
||||
} else if position.y > (win_size.height as f64 - border_size) {
|
||||
ResizeDirection::South
|
||||
} else {
|
||||
// Use arbitrary direction instead of None for simplicity.
|
||||
ResizeDirection::SouthEast
|
||||
};
|
||||
|
||||
let direction = match (x_direction, y_direction) {
|
||||
(ResizeDirection::West, ResizeDirection::North) => ResizeDirection::NorthWest,
|
||||
(ResizeDirection::West, ResizeDirection::South) => ResizeDirection::SouthWest,
|
||||
(ResizeDirection::West, _) => ResizeDirection::West,
|
||||
(ResizeDirection::East, ResizeDirection::North) => ResizeDirection::NorthEast,
|
||||
(ResizeDirection::East, ResizeDirection::South) => ResizeDirection::SouthEast,
|
||||
(ResizeDirection::East, _) => ResizeDirection::East,
|
||||
(_, ResizeDirection::South) => ResizeDirection::South,
|
||||
(_, ResizeDirection::North) => ResizeDirection::North,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
if let Err(err) = self.window.drag_resize_window(direction) {
|
||||
println!("Error starting window drag-resize: {err}");
|
||||
} else {
|
||||
println!("Drag-resizing window Window={:?}", self.window.id());
|
||||
}
|
||||
}
|
||||
|
||||
/// Change window occlusion state.
|
||||
fn set_occluded(&mut self, occluded: bool) {
|
||||
self.occluded = occluded;
|
||||
if !occluded {
|
||||
self.window.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the window contents.
|
||||
#[cfg(not(any(android_platform, ios_platform)))]
|
||||
fn draw(&mut self) -> Result<(), Box<dyn Error>> {
|
||||
if self.occluded {
|
||||
println!("Skipping drawing occluded window={:?}", self.window.id());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
const WHITE: u32 = 0xFFFFFFFF;
|
||||
const DARK_GRAY: u32 = 0xFF181818;
|
||||
|
||||
let color = match self.theme {
|
||||
Theme::Light => WHITE,
|
||||
Theme::Dark => DARK_GRAY,
|
||||
};
|
||||
|
||||
let mut buffer = self.surface.buffer_mut()?;
|
||||
buffer.fill(color);
|
||||
self.window.pre_present_notify();
|
||||
buffer.present()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(android_platform, ios_platform))]
|
||||
fn draw(&mut self) -> Result<(), Box<dyn Error>> {
|
||||
println!("Drawing but without rendering...");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Binding<T: Eq> {
|
||||
trigger: T,
|
||||
mods: ModifiersState,
|
||||
action: Action,
|
||||
}
|
||||
|
||||
impl<T: Eq> Binding<T> {
|
||||
const fn new(trigger: T, mods: ModifiersState, action: Action) -> Self {
|
||||
Self {
|
||||
trigger,
|
||||
mods,
|
||||
action,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_triggered_by(&self, trigger: &T, mods: &ModifiersState) -> bool {
|
||||
&self.trigger == trigger && &self.mods == mods
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Action {
|
||||
CloseWindow,
|
||||
ToggleCursorVisibility,
|
||||
CreateNewWindow,
|
||||
ToggleResizeIncrements,
|
||||
ToggleImeInput,
|
||||
ToggleDecorations,
|
||||
ToggleResizable,
|
||||
ToggleFullscreen,
|
||||
ToggleMaximize,
|
||||
Minimize,
|
||||
NextCursor,
|
||||
NextCustomCursor,
|
||||
CycleCursorGrab,
|
||||
PrintHelp,
|
||||
DragWindow,
|
||||
DragResizeWindow,
|
||||
ShowWindowMenu,
|
||||
#[cfg(macos_platform)]
|
||||
CycleOptionAsAlt,
|
||||
#[cfg(macos_platform)]
|
||||
CreateNewTab,
|
||||
}
|
||||
|
||||
impl Action {
|
||||
fn help(&self) -> &'static str {
|
||||
match self {
|
||||
Action::CloseWindow => "Close window",
|
||||
Action::ToggleCursorVisibility => "Hide cursor",
|
||||
Action::CreateNewWindow => "Create new window",
|
||||
Action::ToggleImeInput => "Toggle IME input",
|
||||
Action::ToggleDecorations => "Toggle decorations",
|
||||
Action::ToggleResizable => "Toggle window resizable state",
|
||||
Action::ToggleFullscreen => "Toggle fullscreen",
|
||||
Action::ToggleMaximize => "Maximize",
|
||||
Action::Minimize => "Minimize",
|
||||
Action::ToggleResizeIncrements => "Use resize increments when resizing window",
|
||||
Action::NextCursor => "Advance the cursor to the next value",
|
||||
Action::NextCustomCursor => "Advance custom cursor to the next value",
|
||||
Action::CycleCursorGrab => "Cycle through cursor grab mode",
|
||||
Action::PrintHelp => "Print help",
|
||||
Action::DragWindow => "Start window drag",
|
||||
Action::DragResizeWindow => "Start window drag-resize",
|
||||
Action::ShowWindowMenu => "Show window menu",
|
||||
#[cfg(macos_platform)]
|
||||
Action::CycleOptionAsAlt => "Cycle option as alt mode",
|
||||
#[cfg(macos_platform)]
|
||||
Action::CreateNewTab => "Create new tab",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Action {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
Debug::fmt(&self, f)
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_cursor(bytes: &[u8]) -> CustomCursorSource {
|
||||
let img = image::load_from_memory(bytes).unwrap().to_rgba8();
|
||||
let samples = img.into_flat_samples();
|
||||
let (_, w, h) = samples.extents();
|
||||
let (w, h) = (w as u16, h as u16);
|
||||
CustomCursor::from_rgba(samples.samples, w, h, w / 2, h / 2).unwrap()
|
||||
}
|
||||
|
||||
fn load_icon(path: &Path) -> Icon {
|
||||
let (icon_rgba, icon_width, icon_height) = {
|
||||
let image = image::open(path)
|
||||
.expect("Failed to open icon path")
|
||||
.into_rgba8();
|
||||
let (width, height) = image.dimensions();
|
||||
let rgba = image.into_raw();
|
||||
(rgba, width, height)
|
||||
};
|
||||
Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon")
|
||||
}
|
||||
|
||||
fn modifiers_to_string(mods: ModifiersState) -> String {
|
||||
let mut mods_line = String::new();
|
||||
// Always add + since it's printed as a part of the bindings.
|
||||
for (modifier, desc) in [
|
||||
(ModifiersState::SUPER, "Super+"),
|
||||
(ModifiersState::ALT, "Alt+"),
|
||||
(ModifiersState::CONTROL, "Ctrl+"),
|
||||
(ModifiersState::SHIFT, "Shift+"),
|
||||
] {
|
||||
if !mods.contains(modifier) {
|
||||
continue;
|
||||
}
|
||||
|
||||
mods_line.push_str(desc);
|
||||
}
|
||||
mods_line
|
||||
}
|
||||
|
||||
fn mouse_button_to_string(button: MouseButton) -> &'static str {
|
||||
match button {
|
||||
MouseButton::Left => "LMB",
|
||||
MouseButton::Right => "RMB",
|
||||
MouseButton::Middle => "MMB",
|
||||
MouseButton::Back => "Back",
|
||||
MouseButton::Forward => "Forward",
|
||||
MouseButton::Other(_) => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// Cursor list to cycle through.
|
||||
const CURSORS: &[CursorIcon] = &[
|
||||
CursorIcon::Default,
|
||||
CursorIcon::Crosshair,
|
||||
CursorIcon::Pointer,
|
||||
CursorIcon::Move,
|
||||
CursorIcon::Text,
|
||||
CursorIcon::Wait,
|
||||
CursorIcon::Help,
|
||||
CursorIcon::Progress,
|
||||
CursorIcon::NotAllowed,
|
||||
CursorIcon::ContextMenu,
|
||||
CursorIcon::Cell,
|
||||
CursorIcon::VerticalText,
|
||||
CursorIcon::Alias,
|
||||
CursorIcon::Copy,
|
||||
CursorIcon::NoDrop,
|
||||
CursorIcon::Grab,
|
||||
CursorIcon::Grabbing,
|
||||
CursorIcon::AllScroll,
|
||||
CursorIcon::ZoomIn,
|
||||
CursorIcon::ZoomOut,
|
||||
CursorIcon::EResize,
|
||||
CursorIcon::NResize,
|
||||
CursorIcon::NeResize,
|
||||
CursorIcon::NwResize,
|
||||
CursorIcon::SResize,
|
||||
CursorIcon::SeResize,
|
||||
CursorIcon::SwResize,
|
||||
CursorIcon::WResize,
|
||||
CursorIcon::EwResize,
|
||||
CursorIcon::NsResize,
|
||||
CursorIcon::NeswResize,
|
||||
CursorIcon::NwseResize,
|
||||
CursorIcon::ColResize,
|
||||
CursorIcon::RowResize,
|
||||
];
|
||||
|
||||
const KEY_BINDINGS: &[Binding<&'static str>] = &[
|
||||
Binding::new("Q", ModifiersState::CONTROL, Action::CloseWindow),
|
||||
Binding::new("H", ModifiersState::CONTROL, Action::PrintHelp),
|
||||
Binding::new("F", ModifiersState::CONTROL, Action::ToggleFullscreen),
|
||||
Binding::new("D", ModifiersState::CONTROL, Action::ToggleDecorations),
|
||||
Binding::new("I", ModifiersState::CONTROL, Action::ToggleImeInput),
|
||||
Binding::new("L", ModifiersState::CONTROL, Action::CycleCursorGrab),
|
||||
Binding::new("P", ModifiersState::CONTROL, Action::ToggleResizeIncrements),
|
||||
Binding::new("R", ModifiersState::CONTROL, Action::ToggleResizable),
|
||||
// M.
|
||||
Binding::new("M", ModifiersState::CONTROL, Action::ToggleMaximize),
|
||||
Binding::new("M", ModifiersState::ALT, Action::Minimize),
|
||||
// N.
|
||||
Binding::new("N", ModifiersState::CONTROL, Action::CreateNewWindow),
|
||||
// C.
|
||||
Binding::new("C", ModifiersState::CONTROL, Action::NextCursor),
|
||||
Binding::new("C", ModifiersState::ALT, Action::NextCustomCursor),
|
||||
Binding::new("Z", ModifiersState::CONTROL, Action::ToggleCursorVisibility),
|
||||
#[cfg(macos_platform)]
|
||||
Binding::new("T", ModifiersState::SUPER, Action::CreateNewTab),
|
||||
#[cfg(macos_platform)]
|
||||
Binding::new("O", ModifiersState::CONTROL, Action::CycleOptionAsAlt),
|
||||
];
|
||||
|
||||
const MOUSE_BINDINGS: &[Binding<MouseButton>] = &[
|
||||
Binding::new(
|
||||
MouseButton::Left,
|
||||
ModifiersState::ALT,
|
||||
Action::DragResizeWindow,
|
||||
),
|
||||
Binding::new(
|
||||
MouseButton::Left,
|
||||
ModifiersState::CONTROL,
|
||||
Action::DragWindow,
|
||||
),
|
||||
Binding::new(
|
||||
MouseButton::Right,
|
||||
ModifiersState::CONTROL,
|
||||
Action::ShowWindowMenu,
|
||||
),
|
||||
];
|
||||
72
examples/x11_embed.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
//! A demonstration of embedding a winit window in an existing X11 application.
|
||||
use std::error::Error;
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||
use winit::platform::x11::WindowAttributesExtX11;
|
||||
use winit::window::{Window, WindowId};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
pub struct XEmbedDemo {
|
||||
parent_window_id: u32,
|
||||
window: Option<Window>,
|
||||
}
|
||||
|
||||
impl ApplicationHandler for XEmbedDemo {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let window_attributes = Window::default_attributes()
|
||||
.with_title("An embedded window!")
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||
.with_embed_parent_window(self.parent_window_id);
|
||||
|
||||
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
let window = self.window.as_ref().unwrap();
|
||||
match event {
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::RedrawRequested => {
|
||||
window.pre_present_notify();
|
||||
fill::fill_window(window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
self.window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
// First argument should be a 32-bit X11 window ID.
|
||||
let parent_window_id = std::env::args()
|
||||
.nth(1)
|
||||
.ok_or("Expected a 32-bit X11 window ID as the first argument.")?
|
||||
.parse::<u32>()?;
|
||||
|
||||
tracing_subscriber::fmt::init();
|
||||
let event_loop = EventLoop::new()?;
|
||||
|
||||
let mut app = XEmbedDemo {
|
||||
parent_window_id,
|
||||
window: None,
|
||||
};
|
||||
event_loop.run_app(&mut app).map_err(Into::into)
|
||||
}
|
||||
|
||||
#[cfg(not(x11_platform))]
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
println!("This example is only supported on X11 platforms.");
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
[package]
|
||||
name = "run-wasm"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
|
||||
221
src/application.rs
Normal file
@@ -0,0 +1,221 @@
|
||||
//! End user application handling.
|
||||
|
||||
use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent};
|
||||
use crate::event_loop::ActiveEventLoop;
|
||||
use crate::window::WindowId;
|
||||
|
||||
/// The handler of the application events.
|
||||
pub trait ApplicationHandler<T: 'static = ()> {
|
||||
/// Emitted when new events arrive from the OS to be processed.
|
||||
///
|
||||
/// This is a useful place to put code that should be done before you start processing
|
||||
/// events, such as updating frame timing information for benchmarking or checking the
|
||||
/// [`StartCause`] to see if a timer set by
|
||||
/// [`ControlFlow::WaitUntil`](crate::event_loop::ControlFlow::WaitUntil) has elapsed.
|
||||
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
|
||||
let _ = (event_loop, cause);
|
||||
}
|
||||
|
||||
/// Emitted when the application has been resumed.
|
||||
///
|
||||
/// For consistency, all platforms emit a `Resumed` event even if they don't themselves have a
|
||||
/// formal suspend/resume lifecycle. For systems without a formal suspend/resume lifecycle
|
||||
/// the `Resumed` event is always emitted after the [`NewEvents(StartCause::Init)`][StartCause::Init]
|
||||
/// event.
|
||||
///
|
||||
/// # Portability
|
||||
///
|
||||
/// It's recommended that applications should only initialize their graphics context and create
|
||||
/// a window after they have received their first `Resumed` event. Some systems
|
||||
/// (specifically Android) won't allow applications to create a render surface until they are
|
||||
/// resumed.
|
||||
///
|
||||
/// Considering that the implementation of [`Suspended`] and `Resumed` events may be internally
|
||||
/// driven by multiple platform-specific events, and that there may be subtle differences across
|
||||
/// platforms with how these internal events are delivered, it's recommended that applications
|
||||
/// be able to gracefully handle redundant (i.e. back-to-back) [`Suspended`] or `Resumed` events.
|
||||
///
|
||||
/// Also see [`Suspended`] notes.
|
||||
///
|
||||
/// ## Android
|
||||
///
|
||||
/// On Android, the `Resumed` event is sent when a new [`SurfaceView`] has been created. This is
|
||||
/// expected to closely correlate with the [`onResume`] lifecycle event but there may technically
|
||||
/// be a discrepancy.
|
||||
///
|
||||
/// [`onResume`]: https://developer.android.com/reference/android/app/Activity#onResume()
|
||||
///
|
||||
/// Applications that need to run on Android must wait until they have been `Resumed`
|
||||
/// before they will be able to create a render surface (such as an `EGLSurface`,
|
||||
/// [`VkSurfaceKHR`] or [`wgpu::Surface`]) which depend on having a
|
||||
/// [`SurfaceView`]. Applications must also assume that if they are [`Suspended`], then their
|
||||
/// render surfaces are invalid and should be dropped.
|
||||
///
|
||||
/// Also see [`Suspended`] notes.
|
||||
///
|
||||
/// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView
|
||||
/// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle
|
||||
/// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html
|
||||
/// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html
|
||||
///
|
||||
/// ## iOS
|
||||
///
|
||||
/// On iOS, the `Resumed` event is emitted in response to an [`applicationDidBecomeActive`]
|
||||
/// callback which means the application is "active" (according to the
|
||||
/// [iOS application lifecycle]).
|
||||
///
|
||||
/// [`applicationDidBecomeActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive
|
||||
/// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
|
||||
///
|
||||
/// ## Web
|
||||
///
|
||||
/// On Web, the `Resumed` event is emitted in response to a [`pageshow`] event
|
||||
/// with the property [`persisted`] being true, which means that the page is being
|
||||
/// restored from the [`bfcache`] (back/forward cache) - an in-memory cache that
|
||||
/// stores a complete snapshot of a page (including the JavaScript heap) as the
|
||||
/// user is navigating away.
|
||||
///
|
||||
/// [`pageshow`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event
|
||||
/// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
|
||||
/// [`bfcache`]: https://web.dev/bfcache/
|
||||
/// [`Suspended`]: Self::suspended
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop);
|
||||
|
||||
/// Emitted when an event is sent from [`EventLoopProxy::send_event`].
|
||||
///
|
||||
/// [`EventLoopProxy::send_event`]: crate::event_loop::EventLoopProxy::send_event
|
||||
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) {
|
||||
let _ = (event_loop, event);
|
||||
}
|
||||
|
||||
/// Emitted when the OS sends an event to a winit window.
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
);
|
||||
|
||||
/// Emitted when the OS sends an event to a device.
|
||||
fn device_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
device_id: DeviceId,
|
||||
event: DeviceEvent,
|
||||
) {
|
||||
let _ = (event_loop, device_id, event);
|
||||
}
|
||||
|
||||
/// Emitted when the event loop is about to block and wait for new events.
|
||||
///
|
||||
/// Most applications shouldn't need to hook into this event since there is no real relationship
|
||||
/// between how often the event loop needs to wake up and the dispatching of any specific events.
|
||||
///
|
||||
/// High frequency event sources, such as input devices could potentially lead to lots of wake
|
||||
/// ups and also lots of corresponding `AboutToWait` events.
|
||||
///
|
||||
/// This is not an ideal event to drive application rendering from and instead applications
|
||||
/// should render in response to [`WindowEvent::RedrawRequested`] events.
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let _ = event_loop;
|
||||
}
|
||||
|
||||
/// Emitted when the application has been suspended.
|
||||
///
|
||||
/// # Portability
|
||||
///
|
||||
/// Not all platforms support the notion of suspending applications, and there may be no
|
||||
/// technical way to guarantee being able to emit a `Suspended` event if the OS has
|
||||
/// no formal application lifecycle (currently only Android, iOS, and Web do). For this reason,
|
||||
/// Winit does not currently try to emit pseudo `Suspended` events before the application
|
||||
/// quits on platforms without an application lifecycle.
|
||||
///
|
||||
/// Considering that the implementation of `Suspended` and [`Resumed`] events may be internally
|
||||
/// driven by multiple platform-specific events, and that there may be subtle differences across
|
||||
/// platforms with how these internal events are delivered, it's recommended that applications
|
||||
/// be able to gracefully handle redundant (i.e. back-to-back) `Suspended` or [`Resumed`] events.
|
||||
///
|
||||
/// Also see [`Resumed`] notes.
|
||||
///
|
||||
/// ## Android
|
||||
///
|
||||
/// On Android, the `Suspended` event is only sent when the application's associated
|
||||
/// [`SurfaceView`] is destroyed. This is expected to closely correlate with the [`onPause`]
|
||||
/// lifecycle event but there may technically be a discrepancy.
|
||||
///
|
||||
/// [`onPause`]: https://developer.android.com/reference/android/app/Activity#onPause()
|
||||
///
|
||||
/// Applications that need to run on Android should assume their [`SurfaceView`] has been
|
||||
/// destroyed, which indirectly invalidates any existing render surfaces that may have been
|
||||
/// created outside of Winit (such as an `EGLSurface`, [`VkSurfaceKHR`] or [`wgpu::Surface`]).
|
||||
///
|
||||
/// After being `Suspended` on Android applications must drop all render surfaces before
|
||||
/// the event callback completes, which may be re-created when the application is next [`Resumed`].
|
||||
///
|
||||
/// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView
|
||||
/// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle
|
||||
/// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html
|
||||
/// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html
|
||||
///
|
||||
/// ## iOS
|
||||
///
|
||||
/// On iOS, the `Suspended` event is currently emitted in response to an
|
||||
/// [`applicationWillResignActive`] callback which means that the application is
|
||||
/// about to transition from the active to inactive state (according to the
|
||||
/// [iOS application lifecycle]).
|
||||
///
|
||||
/// [`applicationWillResignActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622950-applicationwillresignactive
|
||||
/// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
|
||||
///
|
||||
/// ## Web
|
||||
///
|
||||
/// On Web, the `Suspended` event is emitted in response to a [`pagehide`] event
|
||||
/// with the property [`persisted`] being true, which means that the page is being
|
||||
/// put in the [`bfcache`] (back/forward cache) - an in-memory cache that stores a
|
||||
/// complete snapshot of a page (including the JavaScript heap) as the user is
|
||||
/// navigating away.
|
||||
///
|
||||
/// [`pagehide`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event
|
||||
/// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
|
||||
/// [`bfcache`]: https://web.dev/bfcache/
|
||||
/// [`Resumed`]: Self::resumed
|
||||
fn suspended(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let _ = event_loop;
|
||||
}
|
||||
|
||||
/// Emitted when the event loop is being shut down.
|
||||
///
|
||||
/// This is irreversible - if this method is called, it is guaranteed that the event loop
|
||||
/// will exist right after.
|
||||
fn exiting(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let _ = event_loop;
|
||||
}
|
||||
|
||||
/// Emitted when the application has received a memory warning.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// ### Android
|
||||
///
|
||||
/// On Android, the `MemoryWarning` event is sent when [`onLowMemory`] was called. The application
|
||||
/// must [release memory] or risk being killed.
|
||||
///
|
||||
/// [`onLowMemory`]: https://developer.android.com/reference/android/app/Application.html#onLowMemory()
|
||||
/// [release memory]: https://developer.android.com/topic/performance/memory#release
|
||||
///
|
||||
/// ### iOS
|
||||
///
|
||||
/// On iOS, the `MemoryWarning` event is emitted in response to an [`applicationDidReceiveMemoryWarning`]
|
||||
/// callback. The application must free as much memory as possible or risk being terminated, see
|
||||
/// [how to respond to memory warnings].
|
||||
///
|
||||
/// [`applicationDidReceiveMemoryWarning`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623063-applicationdidreceivememorywarni
|
||||
/// [how to respond to memory warnings]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle/responding_to_memory_warnings
|
||||
///
|
||||
/// ### Others
|
||||
///
|
||||
/// - **macOS / Orbital / Wayland / Web / Windows:** Unsupported.
|
||||
fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let _ = event_loop;
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,7 @@ use std::{error::Error, hash::Hash};
|
||||
|
||||
use cursor_icon::CursorIcon;
|
||||
|
||||
use crate::event_loop::EventLoopWindowTarget;
|
||||
use crate::platform_impl::{self, PlatformCustomCursor, PlatformCustomCursorBuilder};
|
||||
use crate::platform_impl::{PlatformCustomCursor, PlatformCustomCursorSource};
|
||||
|
||||
/// The maximum width and height for a cursor when using [`CustomCursor::from_rgba`].
|
||||
pub const MAX_CURSOR_SIZE: u16 = 2048;
|
||||
@@ -49,31 +48,28 @@ impl From<CustomCursor> for Cursor {
|
||||
/// # Example
|
||||
///
|
||||
/// ```no_run
|
||||
/// use winit::{
|
||||
/// event::{Event, WindowEvent},
|
||||
/// event_loop::{ControlFlow, EventLoop},
|
||||
/// window::{CustomCursor, Window},
|
||||
/// };
|
||||
///
|
||||
/// let mut event_loop = EventLoop::new().unwrap();
|
||||
/// # use winit::event_loop::ActiveEventLoop;
|
||||
/// # use winit::window::Window;
|
||||
/// # fn scope(event_loop: &ActiveEventLoop, window: &Window) {
|
||||
/// use winit::window::CustomCursor;
|
||||
///
|
||||
/// let w = 10;
|
||||
/// let h = 10;
|
||||
/// let rgba = vec![255; (w * h * 4) as usize];
|
||||
///
|
||||
/// #[cfg(not(target_family = "wasm"))]
|
||||
/// let builder = CustomCursor::from_rgba(rgba, w, h, w / 2, h / 2).unwrap();
|
||||
/// let source = CustomCursor::from_rgba(rgba, w, h, w / 2, h / 2).unwrap();
|
||||
///
|
||||
/// #[cfg(target_family = "wasm")]
|
||||
/// let builder = {
|
||||
/// let source = {
|
||||
/// use winit::platform::web::CustomCursorExtWebSys;
|
||||
/// CustomCursor::from_url(String::from("http://localhost:3000/cursor.png"), 0, 0)
|
||||
/// };
|
||||
///
|
||||
/// let custom_cursor = builder.build(&event_loop);
|
||||
/// let custom_cursor = event_loop.create_custom_cursor(source);
|
||||
///
|
||||
/// let window = Window::new(&event_loop).unwrap();
|
||||
/// window.set_cursor(custom_cursor.clone());
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
pub struct CustomCursor {
|
||||
@@ -91,9 +87,18 @@ impl CustomCursor {
|
||||
height: u16,
|
||||
hotspot_x: u16,
|
||||
hotspot_y: u16,
|
||||
) -> Result<CustomCursorBuilder, BadImage> {
|
||||
Ok(CustomCursorBuilder {
|
||||
inner: PlatformCustomCursorBuilder::from_rgba(
|
||||
) -> Result<CustomCursorSource, BadImage> {
|
||||
let _span = tracing::debug_span!(
|
||||
"winit::Cursor::from_rgba",
|
||||
width,
|
||||
height,
|
||||
hotspot_x,
|
||||
hotspot_y
|
||||
)
|
||||
.entered();
|
||||
|
||||
Ok(CustomCursorSource {
|
||||
inner: PlatformCustomCursorSource::from_rgba(
|
||||
rgba.into(),
|
||||
width,
|
||||
height,
|
||||
@@ -104,20 +109,12 @@ impl CustomCursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a [`CustomCursor`].
|
||||
/// Source for [`CustomCursor`].
|
||||
///
|
||||
/// See [`CustomCursor`] for more details.
|
||||
#[derive(Debug)]
|
||||
pub struct CustomCursorBuilder {
|
||||
pub(crate) inner: PlatformCustomCursorBuilder,
|
||||
}
|
||||
|
||||
impl CustomCursorBuilder {
|
||||
pub fn build(self, window_target: &EventLoopWindowTarget) -> CustomCursor {
|
||||
CustomCursor {
|
||||
inner: PlatformCustomCursor::build(self.inner, &window_target.p),
|
||||
}
|
||||
}
|
||||
pub struct CustomCursorSource {
|
||||
pub(crate) inner: PlatformCustomCursorSource,
|
||||
}
|
||||
|
||||
/// An error produced when using [`CustomCursor::from_rgba`] with invalid arguments.
|
||||
@@ -178,12 +175,14 @@ impl fmt::Display for BadImage {
|
||||
|
||||
impl Error for BadImage {}
|
||||
|
||||
/// Platforms export this directly as `PlatformCustomCursorBuilder` if they need to only work with images.
|
||||
/// Platforms export this directly as `PlatformCustomCursorSource` if they need to only work with
|
||||
/// images.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct OnlyCursorImageBuilder(pub(crate) CursorImage);
|
||||
pub(crate) struct OnlyCursorImageSource(pub(crate) CursorImage);
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl OnlyCursorImageBuilder {
|
||||
impl OnlyCursorImageSource {
|
||||
pub(crate) fn from_rgba(
|
||||
rgba: Vec<u8>,
|
||||
width: u16,
|
||||
@@ -196,6 +195,7 @@ impl OnlyCursorImageBuilder {
|
||||
}
|
||||
|
||||
/// Platforms export this directly as `PlatformCustomCursor` if they don't implement caching.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct OnlyCursorImage(pub(crate) Arc<CursorImage>);
|
||||
|
||||
@@ -213,16 +213,6 @@ impl PartialEq for OnlyCursorImage {
|
||||
|
||||
impl Eq for OnlyCursorImage {}
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl OnlyCursorImage {
|
||||
pub(crate) fn build(
|
||||
builder: OnlyCursorImageBuilder,
|
||||
_: &platform_impl::EventLoopWindowTarget,
|
||||
) -> Self {
|
||||
Self(Arc::new(builder.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub(crate) struct CursorImage {
|
||||
@@ -297,8 +287,4 @@ impl NoCustomCursor {
|
||||
CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y)?;
|
||||
Ok(Self)
|
||||
}
|
||||
|
||||
fn build(self, _: &platform_impl::EventLoopWindowTarget) -> NoCustomCursor {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
use crate::platform_impl;
|
||||
use std::{error, fmt};
|
||||
|
||||
#[doc(inline)]
|
||||
pub use winit_core::error::NotSupportedError;
|
||||
use crate::platform_impl;
|
||||
|
||||
// TODO: Rename
|
||||
/// An error that may be generated when requesting Winit state
|
||||
@@ -16,10 +14,10 @@ pub enum ExternalError {
|
||||
Os(OsError),
|
||||
}
|
||||
|
||||
impl From<winit_core::event::InnerSizeIgnored> for ExternalError {
|
||||
fn from(_: winit_core::event::InnerSizeIgnored) -> Self {
|
||||
Self::Ignored
|
||||
}
|
||||
/// The error type for when the requested operation is not supported by the backend.
|
||||
#[derive(Clone)]
|
||||
pub struct NotSupportedError {
|
||||
_marker: (),
|
||||
}
|
||||
|
||||
/// The error type for when the OS cannot perform the requested operation.
|
||||
@@ -49,6 +47,14 @@ impl From<OsError> for EventLoopError {
|
||||
}
|
||||
}
|
||||
|
||||
impl NotSupportedError {
|
||||
#[inline]
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn new() -> NotSupportedError {
|
||||
NotSupportedError { _marker: () }
|
||||
}
|
||||
}
|
||||
|
||||
impl OsError {
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn new(line: u32, file: &'static str, error: platform_impl::OsError) -> OsError {
|
||||
@@ -82,6 +88,18 @@ impl fmt::Display for ExternalError {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for NotSupportedError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
f.debug_struct("NotSupportedError").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for NotSupportedError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
f.pad("the requested operation is not supported by Winit")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EventLoopError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
match self {
|
||||
@@ -95,6 +113,7 @@ impl fmt::Display for EventLoopError {
|
||||
|
||||
impl error::Error for OsError {}
|
||||
impl error::Error for ExternalError {}
|
||||
impl error::Error for NotSupportedError {}
|
||||
impl error::Error for EventLoopError {}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -106,6 +125,11 @@ mod tests {
|
||||
// Eat attributes for testing
|
||||
#[test]
|
||||
fn ensure_fmt_does_not_panic() {
|
||||
let _ = format!(
|
||||
"{:?}, {}",
|
||||
NotSupportedError::new(),
|
||||
NotSupportedError::new().clone()
|
||||
);
|
||||
let _ = format!(
|
||||
"{:?}, {}",
|
||||
ExternalError::NotSupported(NotSupportedError::new()),
|
||||
@@ -1,263 +1,120 @@
|
||||
//! Incoming notifications from the GUI system.
|
||||
|
||||
use crate::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use crate::event_loop::AsyncRequestSerial;
|
||||
use crate::keyboard::{self, ModifiersKeyState, ModifiersKeys, ModifiersState};
|
||||
use crate::window::{ActivationToken, Theme, WindowId};
|
||||
|
||||
use std::fmt;
|
||||
//! The [`Event`] enum and assorted supporting types.
|
||||
//!
|
||||
//! These are sent to the closure given to [`EventLoop::run_app(...)`], where they get
|
||||
//! processed and used to modify the program state. For more details, see the root-level documentation.
|
||||
//!
|
||||
//! Some of these events represent different "parts" of a traditional event-handling loop. You could
|
||||
//! approximate the basic ordering loop of [`EventLoop::run_app(...)`] like this:
|
||||
//!
|
||||
//! ```rust,ignore
|
||||
//! let mut start_cause = StartCause::Init;
|
||||
//!
|
||||
//! while !elwt.exiting() {
|
||||
//! app.new_events(event_loop, start_cause);
|
||||
//!
|
||||
//! for event in (window events, user events, device events) {
|
||||
//! // This will pick the right method on the application based on the event.
|
||||
//! app.handle_event(event_loop, event);
|
||||
//! }
|
||||
//!
|
||||
//! for window_id in (redraw windows) {
|
||||
//! app.window_event(event_loop, window_id, RedrawRequested);
|
||||
//! }
|
||||
//!
|
||||
//! app.about_to_wait(event_loop);
|
||||
//! start_cause = wait_if_necessary();
|
||||
//! }
|
||||
//!
|
||||
//! app.exiting(event_loop);
|
||||
//! ```
|
||||
//!
|
||||
//! This leaves out timing details like [`ControlFlow::WaitUntil`] but hopefully
|
||||
//! describes what happens in what order.
|
||||
//!
|
||||
//! [`EventLoop::run_app(...)`]: crate::event_loop::EventLoop::run_app
|
||||
//! [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Mutex, Weak};
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
use std::time::Instant;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
use smol_str::SmolStr;
|
||||
#[cfg(web_platform)]
|
||||
use web_time::Instant;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
pub use serde::{Deserialize, Serialize};
|
||||
|
||||
use smol_str::SmolStr;
|
||||
|
||||
/// Identifier of an input device.
|
||||
///
|
||||
/// Whenever you receive an event arising from a particular input device, this event contains a `DeviceId` which
|
||||
/// identifies its origin. Note that devices may be virtual (representing an on-screen cursor and keyboard focus) or
|
||||
/// physical. Virtual devices typically aggregate inputs from multiple physical devices.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId(u64);
|
||||
|
||||
impl DeviceId {
|
||||
/// Returns a dummy id, useful for unit testing.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The only guarantee made about the return value of this function is that
|
||||
/// it will always be equal to itself and to future values returned by this function.
|
||||
/// No other guarantees are made. This may be equal to a real `DeviceId`.
|
||||
///
|
||||
/// **Passing this into a winit function will result in undefined behavior.**
|
||||
pub const unsafe fn dummy() -> Self {
|
||||
DeviceId(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for DeviceId {
|
||||
fn from(value: u64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DeviceId> for u64 {
|
||||
fn from(value: DeviceId) -> Self {
|
||||
value.0
|
||||
}
|
||||
}
|
||||
use crate::error::ExternalError;
|
||||
#[cfg(doc)]
|
||||
use crate::window::Window;
|
||||
use crate::{
|
||||
dpi::{PhysicalPosition, PhysicalSize},
|
||||
event_loop::AsyncRequestSerial,
|
||||
keyboard::{self, ModifiersKeyState, ModifiersKeys, ModifiersState},
|
||||
platform_impl,
|
||||
window::{ActivationToken, Theme, WindowId},
|
||||
};
|
||||
|
||||
/// Describes a generic event.
|
||||
///
|
||||
/// See the module-level docs for more information on the event loop manages each event.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Event<T: 'static, KeyExtra> {
|
||||
/// Emitted when new events arrive from the OS to be processed.
|
||||
pub enum Event<T: 'static> {
|
||||
/// See [`ApplicationHandler::new_events`] for details.
|
||||
///
|
||||
/// This event type is useful as a place to put code that should be done before you start
|
||||
/// processing events, such as updating frame timing information for benchmarking or checking
|
||||
/// the [`StartCause`] to see if a timer set by
|
||||
/// [`ControlFlow::WaitUntil`](crate::event_loop::ControlFlow::WaitUntil) has elapsed.
|
||||
/// [`ApplicationHandler::new_events`]: crate::application::ApplicationHandler::new_events
|
||||
NewEvents(StartCause),
|
||||
|
||||
/// Emitted when the OS sends an event to a winit window.
|
||||
/// See [`ApplicationHandler::window_event`] for details.
|
||||
///
|
||||
/// [`ApplicationHandler::window_event`]: crate::application::ApplicationHandler::window_event
|
||||
WindowEvent {
|
||||
window_id: WindowId,
|
||||
event: WindowEvent<KeyExtra>,
|
||||
event: WindowEvent,
|
||||
},
|
||||
|
||||
/// Emitted when the OS sends an event to a device.
|
||||
/// See [`ApplicationHandler::device_event`] for details.
|
||||
///
|
||||
/// [`ApplicationHandler::device_event`]: crate::application::ApplicationHandler::device_event
|
||||
DeviceEvent {
|
||||
device_id: DeviceId,
|
||||
event: DeviceEvent,
|
||||
},
|
||||
|
||||
/// Emitted when an event is sent from [`EventLoopProxy::send_event`](https://docs.rs/winit/latest/winit/event_loop/struct.EventLoopProxy.html#method.send_event)
|
||||
/// See [`ApplicationHandler::user_event`] for details.
|
||||
///
|
||||
/// [`ApplicationHandler::user_event`]: crate::application::ApplicationHandler::user_event
|
||||
UserEvent(T),
|
||||
|
||||
/// Emitted when the application has been suspended.
|
||||
/// See [`ApplicationHandler::suspended`] for details.
|
||||
///
|
||||
/// # Portability
|
||||
///
|
||||
/// Not all platforms support the notion of suspending applications, and there may be no
|
||||
/// technical way to guarantee being able to emit a `Suspended` event if the OS has
|
||||
/// no formal application lifecycle (currently only Android, iOS, and Web do). For this reason,
|
||||
/// Winit does not currently try to emit pseudo `Suspended` events before the application
|
||||
/// quits on platforms without an application lifecycle.
|
||||
///
|
||||
/// Considering that the implementation of `Suspended` and [`Resumed`] events may be internally
|
||||
/// driven by multiple platform-specific events, and that there may be subtle differences across
|
||||
/// platforms with how these internal events are delivered, it's recommended that applications
|
||||
/// be able to gracefully handle redundant (i.e. back-to-back) `Suspended` or [`Resumed`] events.
|
||||
///
|
||||
/// Also see [`Resumed`] notes.
|
||||
///
|
||||
/// ## Android
|
||||
///
|
||||
/// On Android, the `Suspended` event is only sent when the application's associated
|
||||
/// [`SurfaceView`] is destroyed. This is expected to closely correlate with the [`onPause`]
|
||||
/// lifecycle event but there may technically be a discrepancy.
|
||||
///
|
||||
/// [`onPause`]: https://developer.android.com/reference/android/app/Activity#onPause()
|
||||
///
|
||||
/// Applications that need to run on Android should assume their [`SurfaceView`] has been
|
||||
/// destroyed, which indirectly invalidates any existing render surfaces that may have been
|
||||
/// created outside of Winit (such as an `EGLSurface`, [`VkSurfaceKHR`] or [`wgpu::Surface`]).
|
||||
///
|
||||
/// After being `Suspended` on Android applications must drop all render surfaces before
|
||||
/// the event callback completes, which may be re-created when the application is next [`Resumed`].
|
||||
///
|
||||
/// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView
|
||||
/// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle
|
||||
/// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html
|
||||
/// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html
|
||||
///
|
||||
/// ## iOS
|
||||
///
|
||||
/// On iOS, the `Suspended` event is currently emitted in response to an
|
||||
/// [`applicationWillResignActive`] callback which means that the application is
|
||||
/// about to transition from the active to inactive state (according to the
|
||||
/// [iOS application lifecycle]).
|
||||
///
|
||||
/// [`applicationWillResignActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622950-applicationwillresignactive
|
||||
/// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
|
||||
///
|
||||
/// ## Web
|
||||
///
|
||||
/// On Web, the `Suspended` event is emitted in response to a [`pagehide`] event
|
||||
/// with the property [`persisted`] being true, which means that the page is being
|
||||
/// put in the [`bfcache`] (back/forward cache) - an in-memory cache that stores a
|
||||
/// complete snapshot of a page (including the JavaScript heap) as the user is
|
||||
/// navigating away.
|
||||
///
|
||||
/// [`pagehide`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event
|
||||
/// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
|
||||
/// [`bfcache`]: https://web.dev/bfcache/
|
||||
///
|
||||
/// [`Resumed`]: Self::Resumed
|
||||
/// [`ApplicationHandler::suspended`]: crate::application::ApplicationHandler::suspended
|
||||
Suspended,
|
||||
|
||||
/// Emitted when the application has been resumed.
|
||||
/// See [`ApplicationHandler::resumed`] for details.
|
||||
///
|
||||
/// For consistency, all platforms emit a `Resumed` event even if they don't themselves have a
|
||||
/// formal suspend/resume lifecycle. For systems without a standard suspend/resume lifecycle
|
||||
/// the `Resumed` event is always emitted after the [`NewEvents(StartCause::Init)`][StartCause::Init]
|
||||
/// event.
|
||||
///
|
||||
/// # Portability
|
||||
///
|
||||
/// It's recommended that applications should only initialize their graphics context and create
|
||||
/// a window after they have received their first `Resumed` event. Some systems
|
||||
/// (specifically Android) won't allow applications to create a render surface until they are
|
||||
/// resumed.
|
||||
///
|
||||
/// Considering that the implementation of [`Suspended`] and `Resumed` events may be internally
|
||||
/// driven by multiple platform-specific events, and that there may be subtle differences across
|
||||
/// platforms with how these internal events are delivered, it's recommended that applications
|
||||
/// be able to gracefully handle redundant (i.e. back-to-back) [`Suspended`] or `Resumed` events.
|
||||
///
|
||||
/// Also see [`Suspended`] notes.
|
||||
///
|
||||
/// ## Android
|
||||
///
|
||||
/// On Android, the `Resumed` event is sent when a new [`SurfaceView`] has been created. This is
|
||||
/// expected to closely correlate with the [`onResume`] lifecycle event but there may technically
|
||||
/// be a discrepancy.
|
||||
///
|
||||
/// [`onResume`]: https://developer.android.com/reference/android/app/Activity#onResume()
|
||||
///
|
||||
/// Applications that need to run on Android must wait until they have been `Resumed`
|
||||
/// before they will be able to create a render surface (such as an `EGLSurface`,
|
||||
/// [`VkSurfaceKHR`] or [`wgpu::Surface`]) which depend on having a
|
||||
/// [`SurfaceView`]. Applications must also assume that if they are [`Suspended`], then their
|
||||
/// render surfaces are invalid and should be dropped.
|
||||
///
|
||||
/// Also see [`Suspended`] notes.
|
||||
///
|
||||
/// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView
|
||||
/// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle
|
||||
/// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html
|
||||
/// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html
|
||||
///
|
||||
/// ## iOS
|
||||
///
|
||||
/// On iOS, the `Resumed` event is emitted in response to an [`applicationDidBecomeActive`]
|
||||
/// callback which means the application is "active" (according to the
|
||||
/// [iOS application lifecycle]).
|
||||
///
|
||||
/// [`applicationDidBecomeActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive
|
||||
/// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
|
||||
///
|
||||
/// ## Web
|
||||
///
|
||||
/// On Web, the `Resumed` event is emitted in response to a [`pageshow`] event
|
||||
/// with the property [`persisted`] being true, which means that the page is being
|
||||
/// restored from the [`bfcache`] (back/forward cache) - an in-memory cache that
|
||||
/// stores a complete snapshot of a page (including the JavaScript heap) as the
|
||||
/// user is navigating away.
|
||||
///
|
||||
/// [`pageshow`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event
|
||||
/// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
|
||||
/// [`bfcache`]: https://web.dev/bfcache/
|
||||
///
|
||||
/// [`Suspended`]: Self::Suspended
|
||||
/// [`ApplicationHandler::resumed`]: crate::application::ApplicationHandler::resumed
|
||||
Resumed,
|
||||
|
||||
/// Emitted when the event loop is about to block and wait for new events.
|
||||
/// See [`ApplicationHandler::about_to_wait`] for details.
|
||||
///
|
||||
/// Most applications shouldn't need to hook into this event since there is no real relationship
|
||||
/// between how often the event loop needs to wake up and the dispatching of any specific events.
|
||||
///
|
||||
/// High frequency event sources, such as input devices could potentially lead to lots of wake
|
||||
/// ups and also lots of corresponding `AboutToWait` events.
|
||||
///
|
||||
/// This is not an ideal event to drive application rendering from and instead applications
|
||||
/// should render in response to [`WindowEvent::RedrawRequested`] events.
|
||||
/// [`ApplicationHandler::about_to_wait`]: crate::application::ApplicationHandler::about_to_wait
|
||||
AboutToWait,
|
||||
|
||||
/// Emitted when the event loop is being shut down.
|
||||
/// See [`ApplicationHandler::exiting`] for details.
|
||||
///
|
||||
/// This is irreversible - if this event is emitted, it is guaranteed to be the last event that
|
||||
/// gets emitted. You generally want to treat this as a "do on quit" event.
|
||||
/// [`ApplicationHandler::exiting`]: crate::application::ApplicationHandler::exiting
|
||||
LoopExiting,
|
||||
|
||||
/// Emitted when the application has received a memory warning.
|
||||
/// See [`ApplicationHandler::memory_warning`] for details.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// ### Android
|
||||
///
|
||||
/// On Android, the `MemoryWarning` event is sent when [`onLowMemory`] was called. The application
|
||||
/// must [release memory] or risk being killed.
|
||||
///
|
||||
/// [`onLowMemory`]: https://developer.android.com/reference/android/app/Application.html#onLowMemory()
|
||||
/// [release memory]: https://developer.android.com/topic/performance/memory#release
|
||||
///
|
||||
/// ### iOS
|
||||
///
|
||||
/// On iOS, the `MemoryWarning` event is emitted in response to an [`applicationDidReceiveMemoryWarning`]
|
||||
/// callback. The application must free as much memory as possible or risk being terminated, see
|
||||
/// [how to respond to memory warnings].
|
||||
///
|
||||
/// [`applicationDidReceiveMemoryWarning`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623063-applicationdidreceivememorywarni
|
||||
/// [how to respond to memory warnings]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle/responding_to_memory_warnings
|
||||
///
|
||||
/// ### Others
|
||||
///
|
||||
/// - **macOS / Wayland / Windows / Orbital:** Unsupported.
|
||||
/// [`ApplicationHandler::memory_warning`]: crate::application::ApplicationHandler::memory_warning
|
||||
MemoryWarning,
|
||||
}
|
||||
|
||||
impl<T, Extra> Event<T, Extra> {
|
||||
impl<T> Event<T> {
|
||||
#[allow(clippy::result_large_err)]
|
||||
pub fn map_nonuser_event<U>(self) -> Result<Event<U, Extra>, Event<T, Extra>> {
|
||||
pub fn map_nonuser_event<U>(self) -> Result<Event<U>, Event<T>> {
|
||||
use self::Event::*;
|
||||
match self {
|
||||
UserEvent(_) => Err(self),
|
||||
@@ -304,14 +161,12 @@ pub enum StartCause {
|
||||
}
|
||||
|
||||
/// Describes an event from a [`Window`].
|
||||
///
|
||||
/// [`Window`]: https://docs.rs/winit/latest/winit/window/struct.Window.html
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum WindowEvent<KeyExtra> {
|
||||
pub enum WindowEvent {
|
||||
/// The activation token was delivered back and now could be used.
|
||||
///
|
||||
#[cfg_attr(
|
||||
not(any(x11_platform, wayland_platfrom)),
|
||||
not(any(x11_platform, wayland_platform)),
|
||||
allow(rustdoc::broken_intra_doc_links)
|
||||
)]
|
||||
/// Delivered in response to [`request_activation_token`].
|
||||
@@ -369,7 +224,7 @@ pub enum WindowEvent<KeyExtra> {
|
||||
/// events which are not marked as `is_synthetic`.
|
||||
KeyboardInput {
|
||||
device_id: DeviceId,
|
||||
event: KeyEvent<KeyExtra>,
|
||||
event: KeyEvent,
|
||||
|
||||
/// If `true`, the event was generated synthetically by winit
|
||||
/// in one of the following circumstances:
|
||||
@@ -393,8 +248,6 @@ pub enum WindowEvent<KeyExtra> {
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **iOS / Android / Web / Orbital:** Unsupported.
|
||||
///
|
||||
/// [`Window::set_ime_allowed`]: https://docs.rs/winit/latest/winit/window/struct.Window.html#method.set_ime_allowed
|
||||
Ime(Ime),
|
||||
|
||||
/// The cursor has moved on the window.
|
||||
@@ -477,7 +330,7 @@ pub enum WindowEvent<KeyExtra> {
|
||||
/// The event is general enough that its generating gesture is allowed to vary
|
||||
/// across platforms. It could also be generated by another device.
|
||||
///
|
||||
/// Unfortunatly, neither [Windows](https://support.microsoft.com/en-us/windows/touch-gestures-for-windows-a9d28305-4818-a5df-4e2b-e5590f850741)
|
||||
/// Unfortunately, neither [Windows](https://support.microsoft.com/en-us/windows/touch-gestures-for-windows-a9d28305-4818-a5df-4e2b-e5590f850741)
|
||||
/// nor [Wayland](https://wayland.freedesktop.org/libinput/doc/latest/gestures.html)
|
||||
/// support this gesture or any other gesture with the same effect.
|
||||
///
|
||||
@@ -540,11 +393,10 @@ pub enum WindowEvent<KeyExtra> {
|
||||
/// * Changing the display's scale factor (e.g. in Control Panel on Windows).
|
||||
/// * Moving the window to a display with a different scale factor.
|
||||
///
|
||||
/// After this event callback has been processed, the window will be resized to whatever value
|
||||
/// is pointed to by the `new_inner_size` reference. By default, this will contain the size suggested
|
||||
/// by the OS, but it can be changed to any value.
|
||||
/// To update the window size, use the provided [`InnerSizeWriter`] handle. By default, the window is
|
||||
/// resized to the value suggested by the OS, but it can be changed to any value.
|
||||
///
|
||||
/// For more information about DPI in general, see the [`dpi`](crate::dpi) module.
|
||||
/// For more information about DPI in general, see the [`dpi`] crate.
|
||||
ScaleFactorChanged {
|
||||
scale_factor: f64,
|
||||
/// Handle to update inner size during scale changes.
|
||||
@@ -600,11 +452,33 @@ pub enum WindowEvent<KeyExtra> {
|
||||
///
|
||||
/// Winit will aggregate duplicate redraw requests into a single event, to
|
||||
/// help avoid duplicating rendering work.
|
||||
///
|
||||
/// [`Window::request_redraw`]: https://docs.rs/winit/latest/winit/window/struct.Window.html#method.request_redraw
|
||||
RedrawRequested,
|
||||
}
|
||||
|
||||
/// Identifier of an input device.
|
||||
///
|
||||
/// Whenever you receive an event arising from a particular input device, this event contains a `DeviceId` which
|
||||
/// identifies its origin. Note that devices may be virtual (representing an on-screen cursor and keyboard focus) or
|
||||
/// physical. Virtual devices typically aggregate inputs from multiple physical devices.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId(pub(crate) platform_impl::DeviceId);
|
||||
|
||||
impl DeviceId {
|
||||
/// Returns a dummy id, useful for unit testing.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The only guarantee made about the return value of this function is that
|
||||
/// it will always be equal to itself and to future values returned by this function.
|
||||
/// No other guarantees are made. This may be equal to a real `DeviceId`.
|
||||
///
|
||||
/// **Passing this into a winit function will result in undefined behavior.**
|
||||
pub const unsafe fn dummy() -> Self {
|
||||
#[allow(unused_unsafe)]
|
||||
DeviceId(unsafe { platform_impl::DeviceId::dummy() })
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents raw hardware events that are not associated with any particular window.
|
||||
///
|
||||
/// Useful for interactions that diverge significantly from a conventional 2D GUI, such as 3D camera or first-person
|
||||
@@ -665,7 +539,7 @@ pub struct RawKeyEvent {
|
||||
|
||||
/// Describes a keyboard input targeting a window.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
|
||||
pub struct KeyEvent<Extra> {
|
||||
pub struct KeyEvent {
|
||||
/// Represents the position of a key independent of the currently active layout.
|
||||
///
|
||||
/// It also uniquely identifies the physical key (i.e. it's mostly synonymous with a scancode).
|
||||
@@ -715,7 +589,7 @@ pub struct KeyEvent<Extra> {
|
||||
/// - **Web:** Dead keys might be reported as the real key instead
|
||||
/// of `Dead` depending on the browser/OS.
|
||||
///
|
||||
/// [`key_without_modifiers`]: https://docs.rs/winit/latest/winit/platform/modifier_supplement/trait.KeyEventExtModifierSupplement.html#tymethod.key_without_modifiers
|
||||
/// [`key_without_modifiers`]: crate::platform::modifier_supplement::KeyEventExtModifierSupplement::key_without_modifiers
|
||||
pub logical_key: keyboard::Key,
|
||||
|
||||
/// Contains the text produced by this keypress.
|
||||
@@ -764,6 +638,31 @@ pub struct KeyEvent<Extra> {
|
||||
/// On some systems, holding down a key for some period of time causes that key to be repeated
|
||||
/// as though it were being pressed and released repeatedly. This field is `true` if and only if
|
||||
/// this event is the result of one of those repeats.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// In games, you often want to ignore repated key events - this can be
|
||||
/// done by ignoring events where this property is set.
|
||||
///
|
||||
/// ```
|
||||
/// use winit::event::{WindowEvent, KeyEvent, ElementState};
|
||||
/// use winit::keyboard::{KeyCode, PhysicalKey};
|
||||
/// # let window_event = WindowEvent::RedrawRequested; // To make the example compile
|
||||
/// match window_event {
|
||||
/// WindowEvent::KeyboardInput {
|
||||
/// event: KeyEvent {
|
||||
/// physical_key: PhysicalKey::Code(KeyCode::KeyW),
|
||||
/// state: ElementState::Pressed,
|
||||
/// repeat: false,
|
||||
/// ..
|
||||
/// },
|
||||
/// ..
|
||||
/// } => {
|
||||
/// // The physical key `W` was pressed, and it was not a repeat
|
||||
/// }
|
||||
/// _ => {} // Handle other events
|
||||
/// }
|
||||
/// ```
|
||||
pub repeat: bool,
|
||||
|
||||
/// Platform-specific key event information.
|
||||
@@ -772,7 +671,7 @@ pub struct KeyEvent<Extra> {
|
||||
/// modifiers applied.
|
||||
///
|
||||
/// On Android, iOS, Redox and Web, this type is a no-op.
|
||||
pub extra: Extra,
|
||||
pub(crate) platform_specific: platform_impl::KeyEventExtra,
|
||||
}
|
||||
|
||||
/// Describes keyboard modifiers event.
|
||||
@@ -787,15 +686,6 @@ pub struct Modifiers {
|
||||
}
|
||||
|
||||
impl Modifiers {
|
||||
/// Only `winit` should instantiate this!
|
||||
#[doc(hidden)]
|
||||
pub fn new(state: ModifiersState, pressed_mods: ModifiersKeys) -> Self {
|
||||
Self {
|
||||
state,
|
||||
pressed_mods,
|
||||
}
|
||||
}
|
||||
|
||||
/// The state of the modifiers.
|
||||
pub fn state(&self) -> ModifiersState {
|
||||
self.state
|
||||
@@ -895,8 +785,6 @@ impl From<ModifiersState> for Modifiers {
|
||||
/// Ime::Preedit("", None) // Synthetic event generated by winit to clear preedit.
|
||||
/// Ime::Commit("啊不")
|
||||
/// ```
|
||||
///
|
||||
/// [`Window::set_ime_cursor_area`]: https://docs.rs/winit/latest/winit/window/struct.Window.html#method.set_ime_cursor_area
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum Ime {
|
||||
@@ -905,8 +793,6 @@ pub enum Ime {
|
||||
/// After getting this event you could receive [`Preedit`](Self::Preedit) and
|
||||
/// [`Commit`](Self::Commit) events. You should also start performing IME related requests
|
||||
/// like [`Window::set_ime_cursor_area`].
|
||||
///
|
||||
/// [`Window::set_ime_cursor_area`]: https://docs.rs/winit/latest/winit/window/struct.Window.html#method.set_ime_cursor_area
|
||||
Enabled,
|
||||
|
||||
/// Notifies when a new composing text should be set at the cursor position.
|
||||
@@ -929,8 +815,6 @@ pub enum Ime {
|
||||
/// [`Commit`](Self::Commit) events until the next [`Enabled`](Self::Enabled) event. You should
|
||||
/// also stop issuing IME related requests like [`Window::set_ime_cursor_area`] and clear pending
|
||||
/// preedit text.
|
||||
///
|
||||
/// [`Window::set_ime_cursor_area`]: https://docs.rs/winit/latest/winit/window/struct.Window.html#method.set_ime_cursor_area
|
||||
Disabled,
|
||||
}
|
||||
|
||||
@@ -1110,7 +994,7 @@ pub enum MouseScrollDelta {
|
||||
PixelDelta(PhysicalPosition<f64>),
|
||||
}
|
||||
|
||||
/// Handle to synchroniously change the size of the window from the
|
||||
/// Handle to synchronously change the size of the window from the
|
||||
/// [`WindowEvent`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct InnerSizeWriter {
|
||||
@@ -1119,27 +1003,22 @@ pub struct InnerSizeWriter {
|
||||
|
||||
impl InnerSizeWriter {
|
||||
#[cfg(not(orbital_platform))]
|
||||
pub fn new(new_inner_size: Weak<Mutex<PhysicalSize<u32>>>) -> Self {
|
||||
pub(crate) fn new(new_inner_size: Weak<Mutex<PhysicalSize<u32>>>) -> Self {
|
||||
Self { new_inner_size }
|
||||
}
|
||||
|
||||
/// Try to request inner size which will be set synchroniously on the window.
|
||||
/// Try to request inner size which will be set synchronously on the window.
|
||||
pub fn request_inner_size(
|
||||
&mut self,
|
||||
new_inner_size: PhysicalSize<u32>,
|
||||
) -> Result<(), InnerSizeIgnored> {
|
||||
) -> Result<(), ExternalError> {
|
||||
if let Some(inner) = self.new_inner_size.upgrade() {
|
||||
*inner.lock().unwrap() = new_inner_size;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(InnerSizeIgnored { _private: () })
|
||||
Err(ExternalError::Ignored)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the underlying size.
|
||||
pub fn get(&self) -> PhysicalSize<u32> {
|
||||
*self.new_inner_size.upgrade().unwrap().lock().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for InnerSizeWriter {
|
||||
@@ -1148,25 +1027,6 @@ impl PartialEq for InnerSizeWriter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Could not write the inner size.
|
||||
pub struct InnerSizeIgnored {
|
||||
_private: (),
|
||||
}
|
||||
|
||||
impl fmt::Debug for InnerSizeIgnored {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("InnerSizeIgnored").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for InnerSizeIgnored {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("tried to write inner size after")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InnerSizeIgnored {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::event;
|
||||
@@ -1292,7 +1152,7 @@ mod tests {
|
||||
#[allow(clippy::redundant_clone)]
|
||||
#[test]
|
||||
fn test_event_clone() {
|
||||
foreach_event!(|event: event::Event<(), ()>| {
|
||||
foreach_event!(|event: event::Event<()>| {
|
||||
let event2 = event.clone();
|
||||
assert_eq!(event, event2);
|
||||
})
|
||||
@@ -1300,7 +1160,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_map_nonuser_event() {
|
||||
foreach_event!(|event: event::Event<(), ()>| {
|
||||
foreach_event!(|event: event::Event<()>| {
|
||||
let is_user = matches!(event, event::Event::UserEvent(()));
|
||||
let event2 = event.map_nonuser_event::<()>();
|
||||
if is_user {
|
||||
@@ -1334,7 +1194,7 @@ mod tests {
|
||||
#[allow(clippy::clone_on_copy)]
|
||||
#[test]
|
||||
fn ensure_attrs_do_not_panic() {
|
||||
foreach_event!(|event: event::Event<(), ()>| {
|
||||
foreach_event!(|event: event::Event<()>| {
|
||||
let _ = format!("{:?}", event);
|
||||
});
|
||||
let _ = event::StartCause::Init.clone();
|
||||
@@ -8,17 +8,20 @@
|
||||
//! See the root-level documentation for information on how to create and use an event loop to
|
||||
//! handle events.
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::Deref;
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::{error, fmt};
|
||||
|
||||
use crate::error::EventLoopError;
|
||||
use crate::{event::Event, monitor::MonitorHandle, platform_impl};
|
||||
#[cfg(not(web_platform))]
|
||||
use std::time::{Duration, Instant};
|
||||
#[cfg(web_platform)]
|
||||
use web_time::{Duration, Instant};
|
||||
|
||||
#[doc(inline)]
|
||||
pub use winit_core::event_loop::{AsyncRequestSerial, ControlFlow};
|
||||
use crate::application::ApplicationHandler;
|
||||
use crate::error::{EventLoopError, OsError};
|
||||
use crate::window::{CustomCursor, CustomCursorSource, Window, WindowAttributes};
|
||||
use crate::{event::Event, monitor::MonitorHandle, platform_impl};
|
||||
|
||||
/// Provides a way to retrieve events from the system and from the windows that were registered to
|
||||
/// the events loop.
|
||||
@@ -43,11 +46,9 @@ pub struct EventLoop<T: 'static> {
|
||||
/// Target that associates windows with an [`EventLoop`].
|
||||
///
|
||||
/// This type exists to allow you to create new windows while Winit executes
|
||||
/// your callback. [`EventLoop`] will coerce into this type (`impl<T> Deref for
|
||||
/// EventLoop<T>`), so functions that take this as a parameter can also take
|
||||
/// `&EventLoop`.
|
||||
pub struct EventLoopWindowTarget {
|
||||
pub(crate) p: platform_impl::EventLoopWindowTarget,
|
||||
/// your callback.
|
||||
pub struct ActiveEventLoop {
|
||||
pub(crate) p: platform_impl::ActiveEventLoop,
|
||||
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
|
||||
}
|
||||
|
||||
@@ -109,6 +110,8 @@ impl<T> EventLoopBuilder<T> {
|
||||
)]
|
||||
#[inline]
|
||||
pub fn build(&mut self) -> Result<EventLoop<T>, EventLoopError> {
|
||||
let _span = tracing::debug_span!("winit::EventLoopBuilder::build").entered();
|
||||
|
||||
if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
|
||||
return Err(EventLoopError::RecreationAttempt);
|
||||
}
|
||||
@@ -133,9 +136,53 @@ impl<T> fmt::Debug for EventLoop<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for EventLoopWindowTarget {
|
||||
impl fmt::Debug for ActiveEventLoop {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.pad("EventLoopWindowTarget { .. }")
|
||||
f.pad("ActiveEventLoop { .. }")
|
||||
}
|
||||
}
|
||||
|
||||
/// Set through [`ActiveEventLoop::set_control_flow()`].
|
||||
///
|
||||
/// Indicates the desired behavior of the event loop after [`Event::AboutToWait`] is emitted.
|
||||
///
|
||||
/// Defaults to [`Wait`].
|
||||
///
|
||||
/// [`Wait`]: Self::Wait
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ControlFlow {
|
||||
/// When the current loop iteration finishes, immediately begin a new iteration regardless of
|
||||
/// whether or not new events are available to process.
|
||||
Poll,
|
||||
|
||||
/// When the current loop iteration finishes, suspend the thread until another event arrives.
|
||||
#[default]
|
||||
Wait,
|
||||
|
||||
/// When the current loop iteration finishes, suspend the thread until either another event
|
||||
/// arrives or the given time is reached.
|
||||
///
|
||||
/// Useful for implementing efficient timers. Applications which want to render at the display's
|
||||
/// native refresh rate should instead use [`Poll`] and the VSync functionality of a graphics API
|
||||
/// to reduce odds of missed frames.
|
||||
///
|
||||
/// [`Poll`]: Self::Poll
|
||||
WaitUntil(Instant),
|
||||
}
|
||||
|
||||
impl ControlFlow {
|
||||
/// Creates a [`ControlFlow`] that waits until a timeout has expired.
|
||||
///
|
||||
/// In most cases, this is set to [`WaitUntil`]. However, if the timeout overflows, it is
|
||||
/// instead set to [`Wait`].
|
||||
///
|
||||
/// [`WaitUntil`]: Self::WaitUntil
|
||||
/// [`Wait`]: Self::Wait
|
||||
pub fn wait_duration(timeout: Duration) -> Self {
|
||||
match Instant::now().checked_add(timeout) {
|
||||
Some(instant) => Self::WaitUntil(instant),
|
||||
None => Self::Wait,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,8 +216,22 @@ impl<T> EventLoop<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the event loop in the calling thread and calls the given `event_handler` closure
|
||||
/// to dispatch any pending events.
|
||||
/// See [`run_app`].
|
||||
///
|
||||
/// [`run_app`]: Self::run_app
|
||||
#[inline]
|
||||
#[deprecated = "use `EventLoop::run_app` instead"]
|
||||
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
||||
pub fn run<F>(self, event_handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(Event<T>, &ActiveEventLoop),
|
||||
{
|
||||
let _span = tracing::debug_span!("winit::EventLoop::run").entered();
|
||||
|
||||
self.event_loop.run(event_handler)
|
||||
}
|
||||
|
||||
/// Run the application with the event loop on the calling thread.
|
||||
///
|
||||
/// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
|
||||
///
|
||||
@@ -185,40 +246,100 @@ impl<T> EventLoop<T> {
|
||||
/// Web applications are recommended to use
|
||||
#[cfg_attr(
|
||||
web_platform,
|
||||
doc = "[`EventLoopExtWebSys::spawn()`][crate::platform::web::EventLoopExtWebSys::spawn()]"
|
||||
doc = "[`EventLoopExtWebSys::spawn_app()`][crate::platform::web::EventLoopExtWebSys::spawn_app()]"
|
||||
)]
|
||||
#[cfg_attr(not(web_platform), doc = "`EventLoopExtWebSys::spawn()`")]
|
||||
/// [^1] instead of [`run()`] to avoid the need
|
||||
/// [^1] instead of [`run_app()`] to avoid the need
|
||||
/// for the Javascript exception trick, and to make it clearer that the event loop runs
|
||||
/// asynchronously (via the browser's own, internal, event loop) and doesn't block the
|
||||
/// current thread of execution like it does on other platforms.
|
||||
///
|
||||
/// This function won't be available with `target_feature = "exception-handling"`.
|
||||
///
|
||||
/// [`set_control_flow()`]: EventLoopWindowTarget::set_control_flow()
|
||||
/// [`run()`]: Self::run()
|
||||
/// [^1]: `EventLoopExtWebSys::spawn()` is only available on Web.
|
||||
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
||||
/// [`run_app()`]: Self::run_app()
|
||||
/// [^1]: `EventLoopExtWebSys::spawn_app()` is only available on Web.
|
||||
#[inline]
|
||||
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
||||
pub fn run<F>(self, event_handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(Event<T>, &EventLoopWindowTarget),
|
||||
{
|
||||
self.event_loop.run(event_handler)
|
||||
pub fn run_app<A: ApplicationHandler<T>>(self, app: &mut A) -> Result<(), EventLoopError> {
|
||||
self.event_loop
|
||||
.run(|event, event_loop| dispatch_event_for_app(app, event_loop, event))
|
||||
}
|
||||
|
||||
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events to the main event loop.
|
||||
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events
|
||||
/// to the main event loop, possibly from another thread.
|
||||
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||
EventLoopProxy {
|
||||
event_loop_proxy: self.event_loop.create_proxy(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a persistent reference to the underlying platform display.
|
||||
///
|
||||
/// See the [`OwnedDisplayHandle`] type for more information.
|
||||
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||
OwnedDisplayHandle {
|
||||
platform: self.event_loop.window_target().p.owned_display_handle(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Change if or when [`DeviceEvent`]s are captured.
|
||||
///
|
||||
/// See [`ActiveEventLoop::listen_device_events`] for details.
|
||||
///
|
||||
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
||||
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
||||
let _span = tracing::debug_span!(
|
||||
"winit::EventLoop::listen_device_events",
|
||||
allowed = ?allowed
|
||||
)
|
||||
.entered();
|
||||
|
||||
self.event_loop
|
||||
.window_target()
|
||||
.p
|
||||
.listen_device_events(allowed);
|
||||
}
|
||||
|
||||
/// Sets the [`ControlFlow`].
|
||||
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||
self.event_loop
|
||||
.window_target()
|
||||
.p
|
||||
.set_control_flow(control_flow)
|
||||
}
|
||||
|
||||
/// Create a window.
|
||||
///
|
||||
/// Creating window without event loop running often leads to improper window creation;
|
||||
/// use [`ActiveEventLoop::create_window`] instead.
|
||||
#[deprecated = "use `ActiveEventLoop::create_window` instead"]
|
||||
#[inline]
|
||||
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
|
||||
let _span = tracing::debug_span!(
|
||||
"winit::EventLoop::create_window",
|
||||
window_attributes = ?window_attributes
|
||||
)
|
||||
.entered();
|
||||
|
||||
let window =
|
||||
platform_impl::Window::new(&self.event_loop.window_target().p, window_attributes)?;
|
||||
Ok(Window { window })
|
||||
}
|
||||
|
||||
/// Create custom cursor.
|
||||
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
|
||||
self.event_loop
|
||||
.window_target()
|
||||
.p
|
||||
.create_custom_cursor(custom_cursor)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
impl<T> rwh_06::HasDisplayHandle for EventLoop<T> {
|
||||
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||
rwh_06::HasDisplayHandle::display_handle(&**self)
|
||||
rwh_06::HasDisplayHandle::display_handle(self.event_loop.window_target())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,7 +347,7 @@ impl<T> rwh_06::HasDisplayHandle for EventLoop<T> {
|
||||
unsafe impl<T> rwh_05::HasRawDisplayHandle for EventLoop<T> {
|
||||
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||
rwh_05::HasRawDisplayHandle::raw_display_handle(&**self)
|
||||
rwh_05::HasRawDisplayHandle::raw_display_handle(self.event_loop.window_target())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,11 +355,11 @@ unsafe impl<T> rwh_05::HasRawDisplayHandle for EventLoop<T> {
|
||||
impl<T> AsFd for EventLoop<T> {
|
||||
/// Get the underlying [EventLoop]'s `fd` which you can register
|
||||
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||
/// loop must be polled with the [`pump_events`] API.
|
||||
/// loop must be polled with the [`pump_app_events`] API.
|
||||
///
|
||||
/// [`calloop`]: https://crates.io/crates/calloop
|
||||
/// [`mio`]: https://crates.io/crates/mio
|
||||
/// [`pump_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_events
|
||||
/// [`pump_app_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_app_events
|
||||
fn as_fd(&self) -> BorrowedFd<'_> {
|
||||
self.event_loop.as_fd()
|
||||
}
|
||||
@@ -248,27 +369,49 @@ impl<T> AsFd for EventLoop<T> {
|
||||
impl<T> AsRawFd for EventLoop<T> {
|
||||
/// Get the underlying [EventLoop]'s raw `fd` which you can register
|
||||
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||
/// loop must be polled with the [`pump_events`] API.
|
||||
/// loop must be polled with the [`pump_app_events`] API.
|
||||
///
|
||||
/// [`calloop`]: https://crates.io/crates/calloop
|
||||
/// [`mio`]: https://crates.io/crates/mio
|
||||
/// [`pump_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_events
|
||||
/// [`pump_app_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_app_events
|
||||
fn as_raw_fd(&self) -> RawFd {
|
||||
self.event_loop.as_raw_fd()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for EventLoop<T> {
|
||||
type Target = EventLoopWindowTarget;
|
||||
fn deref(&self) -> &EventLoopWindowTarget {
|
||||
self.event_loop.window_target()
|
||||
}
|
||||
}
|
||||
impl ActiveEventLoop {
|
||||
/// Create the window.
|
||||
///
|
||||
/// Possible causes of error include denied permission, incompatible system, and lack of memory.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Web:** The window is created but not inserted into the web page automatically. Please
|
||||
/// see the web platform module for more information.
|
||||
#[inline]
|
||||
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
|
||||
let _span = tracing::debug_span!(
|
||||
"winit::ActiveEventLoop::create_window",
|
||||
window_attributes = ?window_attributes
|
||||
)
|
||||
.entered();
|
||||
|
||||
let window = platform_impl::Window::new(&self.p, window_attributes)?;
|
||||
Ok(Window { window })
|
||||
}
|
||||
|
||||
/// Create custom cursor.
|
||||
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
|
||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::create_custom_cursor",).entered();
|
||||
|
||||
self.p.create_custom_cursor(custom_cursor)
|
||||
}
|
||||
|
||||
impl EventLoopWindowTarget {
|
||||
/// Returns the list of all the monitors available on the system.
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::available_monitors",).entered();
|
||||
|
||||
#[allow(clippy::useless_conversion)] // false positive on some platforms
|
||||
self.p
|
||||
.available_monitors()
|
||||
@@ -285,6 +428,8 @@ impl EventLoopWindowTarget {
|
||||
/// **Wayland / Web:** Always returns `None`.
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::primary_monitor",).entered();
|
||||
|
||||
self.p
|
||||
.primary_monitor()
|
||||
.map(|inner| MonitorHandle { inner })
|
||||
@@ -302,6 +447,12 @@ impl EventLoopWindowTarget {
|
||||
///
|
||||
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
||||
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
||||
let _span = tracing::debug_span!(
|
||||
"winit::ActiveEventLoop::listen_device_events",
|
||||
allowed = ?allowed
|
||||
)
|
||||
.entered();
|
||||
|
||||
self.p.listen_device_events(allowed);
|
||||
}
|
||||
|
||||
@@ -319,6 +470,8 @@ impl EventLoopWindowTarget {
|
||||
///
|
||||
/// See [`LoopExiting`](Event::LoopExiting).
|
||||
pub fn exit(&self) {
|
||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::exit",).entered();
|
||||
|
||||
self.p.exit()
|
||||
}
|
||||
|
||||
@@ -340,7 +493,7 @@ impl EventLoopWindowTarget {
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
impl rwh_06::HasDisplayHandle for EventLoopWindowTarget {
|
||||
impl rwh_06::HasDisplayHandle for ActiveEventLoop {
|
||||
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||
let raw = self.p.raw_display_handle_rwh_06()?;
|
||||
// SAFETY: The display will never be deallocated while the event loop is alive.
|
||||
@@ -349,7 +502,7 @@ impl rwh_06::HasDisplayHandle for EventLoopWindowTarget {
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
unsafe impl rwh_05::HasRawDisplayHandle for EventLoopWindowTarget {
|
||||
unsafe impl rwh_05::HasRawDisplayHandle for ActiveEventLoop {
|
||||
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||
self.p.raw_display_handle_rwh_05()
|
||||
@@ -360,7 +513,7 @@ unsafe impl rwh_05::HasRawDisplayHandle for EventLoopWindowTarget {
|
||||
///
|
||||
/// The purpose of this type is to provide a cheaply clonable handle to the underlying
|
||||
/// display handle. This is often used by graphics APIs to connect to the underlying APIs.
|
||||
/// It is difficult to keep a handle to the [`EventLoop`] type or the [`EventLoopWindowTarget`]
|
||||
/// It is difficult to keep a handle to the [`EventLoop`] type or the [`ActiveEventLoop`]
|
||||
/// type. In contrast, this type involves no lifetimes and can be persisted for as long as
|
||||
/// needed.
|
||||
///
|
||||
@@ -424,6 +577,8 @@ impl<T: 'static> EventLoopProxy<T> {
|
||||
///
|
||||
/// [`UserEvent(event)`]: Event::UserEvent
|
||||
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||
let _span = tracing::debug_span!("winit::EventLoopProxy::send_event",).entered();
|
||||
|
||||
self.event_loop_proxy.send_event(event)
|
||||
}
|
||||
}
|
||||
@@ -460,3 +615,49 @@ pub enum DeviceEvents {
|
||||
/// Never capture device events.
|
||||
Never,
|
||||
}
|
||||
|
||||
/// A unique identifier of the winit's async request.
|
||||
///
|
||||
/// This could be used to identify the async request once it's done
|
||||
/// and a specific action must be taken.
|
||||
///
|
||||
/// One of the handling scenarios could be to maintain a working list
|
||||
/// containing [`AsyncRequestSerial`] and some closure associated with it.
|
||||
/// Then once event is arriving the working list is being traversed and a job
|
||||
/// executed and removed from the list.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AsyncRequestSerial {
|
||||
serial: usize,
|
||||
}
|
||||
|
||||
impl AsyncRequestSerial {
|
||||
// TODO(kchibisov): Remove `cfg` when the clipboard will be added.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn get() -> Self {
|
||||
static CURRENT_SERIAL: AtomicUsize = AtomicUsize::new(0);
|
||||
// NOTE: We rely on wrap around here, while the user may just request
|
||||
// in the loop usize::MAX times that's issue is considered on them.
|
||||
let serial = CURRENT_SERIAL.fetch_add(1, Ordering::Relaxed);
|
||||
Self { serial }
|
||||
}
|
||||
}
|
||||
|
||||
/// Shim for various run APIs.
|
||||
#[inline(always)]
|
||||
pub(crate) fn dispatch_event_for_app<T: 'static, A: ApplicationHandler<T>>(
|
||||
app: &mut A,
|
||||
event_loop: &ActiveEventLoop,
|
||||
event: Event<T>,
|
||||
) {
|
||||
match event {
|
||||
Event::NewEvents(cause) => app.new_events(event_loop, cause),
|
||||
Event::WindowEvent { window_id, event } => app.window_event(event_loop, window_id, event),
|
||||
Event::DeviceEvent { device_id, event } => app.device_event(event_loop, device_id, event),
|
||||
Event::UserEvent(event) => app.user_event(event_loop, event),
|
||||
Event::Suspended => app.suspended(event_loop),
|
||||
Event::Resumed => app.resumed(event_loop),
|
||||
Event::AboutToWait => app.about_to_wait(event_loop),
|
||||
Event::LoopExiting => app.exiting(event_loop),
|
||||
Event::MemoryWarning => app.memory_warning(event_loop),
|
||||
}
|
||||
}
|
||||
@@ -118,6 +118,8 @@ impl Icon {
|
||||
/// The length of `rgba` must be divisible by 4, and `width * height` must equal
|
||||
/// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
|
||||
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||
let _span = tracing::debug_span!("winit::Icon::from_rgba", width, height).entered();
|
||||
|
||||
Ok(Icon {
|
||||
inner: PlatformIcon::from_rgba(rgba, width, height)?,
|
||||
})
|
||||
@@ -20,7 +20,7 @@
|
||||
// the W3C short notice apply to the `Key` and `KeyCode` enums and their variants and the
|
||||
// documentation attached to their variants.
|
||||
|
||||
// --------- BEGGINING OF W3C LICENSE --------------------------------------------------------------
|
||||
// --------- BEGINNING OF W3C LICENSE --------------------------------------------------------------
|
||||
//
|
||||
// License
|
||||
//
|
||||
@@ -55,7 +55,7 @@
|
||||
//
|
||||
// --------- END OF W3C LICENSE --------------------------------------------------------------------
|
||||
|
||||
// --------- BEGGINING OF W3C SHORT NOTICE ---------------------------------------------------------
|
||||
// --------- BEGINNING OF W3C SHORT NOTICE ---------------------------------------------------------
|
||||
//
|
||||
// winit: https://github.com/rust-windowing/winit
|
||||
//
|
||||
@@ -744,7 +744,7 @@ pub enum KeyCode {
|
||||
/// - The `Super` variant here, is named `Meta` in the aforementioned specification. (There's
|
||||
/// another key which the specification calls `Super`. That does not exist here.)
|
||||
/// - The `Space` variant here, can be identified by the character it generates in the
|
||||
/// specificaiton.
|
||||
/// specification.
|
||||
///
|
||||
/// [`KeyboardEvent.key`]: https://w3c.github.io/uievents-key/
|
||||
#[non_exhaustive]
|
||||
@@ -914,7 +914,7 @@ pub enum NamedKey {
|
||||
Standby,
|
||||
/// The WakeUp key. (`KEYCODE_WAKEUP`)
|
||||
WakeUp,
|
||||
/// Initate the multi-candidate mode.
|
||||
/// Initiate the multi-candidate mode.
|
||||
AllCandidates,
|
||||
Alphanumeric,
|
||||
/// Initiate the Code Input mode to allow characters to be entered by
|
||||
@@ -1454,35 +1454,12 @@ pub enum NamedKey {
|
||||
F35,
|
||||
}
|
||||
|
||||
// NOTE: the exact modifier key is not used to represent modifiers state in the
|
||||
// first place due to a fact that modifiers state could be changed without any
|
||||
// key being pressed and on some platforms like Wayland/X11 which key resulted
|
||||
// in modifiers change is hidden, also, not that it really matters.
|
||||
//
|
||||
// The reason this API is even exposed is mostly to provide a way for users
|
||||
// to treat modifiers differently based on their position, which is required
|
||||
// on macOS due to their AltGr/Option situation.
|
||||
bitflags! {
|
||||
#[doc(hidden)]
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ModifiersKeys: u8 {
|
||||
const LSHIFT = 0b0000_0001;
|
||||
const RSHIFT = 0b0000_0010;
|
||||
const LCONTROL = 0b0000_0100;
|
||||
const RCONTROL = 0b0000_1000;
|
||||
const LALT = 0b0001_0000;
|
||||
const RALT = 0b0010_0000;
|
||||
const LSUPER = 0b0100_0000;
|
||||
const RSUPER = 0b1000_0000;
|
||||
}
|
||||
}
|
||||
|
||||
/// Key represents the meaning of a keypress.
|
||||
///
|
||||
/// This is a superset of the UI Events Specification's [`KeyboardEvent.key`] with
|
||||
/// additions:
|
||||
/// - All simple variants are wrapped under the `Named` variant
|
||||
/// - The `Unidentified` variant here, can still identifiy a key through it's `NativeKeyCode`.
|
||||
/// - The `Unidentified` variant here, can still identify a key through it's `NativeKeyCode`.
|
||||
/// - The `Dead` variant here, can specify the character which is inserted when pressing the
|
||||
/// dead-key twice.
|
||||
///
|
||||
@@ -1588,7 +1565,7 @@ impl NamedKey {
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use winit_core::keyboard::NamedKey;
|
||||
/// use winit::keyboard::NamedKey;
|
||||
///
|
||||
/// assert_eq!(NamedKey::Enter.to_text(), Some("\r"));
|
||||
/// assert_eq!(NamedKey::F20.to_text(), None);
|
||||
@@ -1611,7 +1588,7 @@ impl Key {
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use winit_core::keyboard::{NamedKey, Key};
|
||||
/// use winit::keyboard::{NamedKey, Key};
|
||||
///
|
||||
/// assert_eq!(Key::Character("a".into()).to_text(), Some("a"));
|
||||
/// assert_eq!(Key::Named(NamedKey::Enter).to_text(), Some("\r"));
|
||||
@@ -1750,6 +1727,28 @@ pub enum ModifiersKeyState {
|
||||
Unknown,
|
||||
}
|
||||
|
||||
// NOTE: the exact modifier key is not used to represent modifiers state in the
|
||||
// first place due to a fact that modifiers state could be changed without any
|
||||
// key being pressed and on some platforms like Wayland/X11 which key resulted
|
||||
// in modifiers change is hidden, also, not that it really matters.
|
||||
//
|
||||
// The reason this API is even exposed is mostly to provide a way for users
|
||||
// to treat modifiers differently based on their position, which is required
|
||||
// on macOS due to their AltGr/Option situation.
|
||||
bitflags! {
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct ModifiersKeys: u8 {
|
||||
const LSHIFT = 0b0000_0001;
|
||||
const RSHIFT = 0b0000_0010;
|
||||
const LCONTROL = 0b0000_0100;
|
||||
const RCONTROL = 0b0000_1000;
|
||||
const LALT = 0b0001_0000;
|
||||
const RALT = 0b0010_0000;
|
||||
const LSUPER = 0b0100_0000;
|
||||
const RSUPER = 0b1000_0000;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
mod modifiers_serde {
|
||||
use super::ModifiersState;
|
||||
217
src/lib.rs
Normal file
@@ -0,0 +1,217 @@
|
||||
//! Winit is a cross-platform window creation and event loop management library.
|
||||
//!
|
||||
//! # Building windows
|
||||
//!
|
||||
//! Before you can create a [`Window`], you first need to build an [`EventLoop`]. This is done with
|
||||
//! the [`EventLoop::new()`] function.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use winit::event_loop::EventLoop;
|
||||
//! let event_loop = EventLoop::new().unwrap();
|
||||
//! ```
|
||||
//!
|
||||
//! Then you create a [`Window`] with [`create_window`].
|
||||
//!
|
||||
//! # Event handling
|
||||
//!
|
||||
//! Once a [`Window`] has been created, it will generate different *events*. A [`Window`] object can
|
||||
//! generate [`WindowEvent`]s when certain input events occur, such as a cursor moving over the
|
||||
//! window or a key getting pressed while the window is focused. Devices can generate
|
||||
//! [`DeviceEvent`]s, which contain unfiltered event data that isn't specific to a certain window.
|
||||
//! Some user activity, like mouse movement, can generate both a [`WindowEvent`] *and* a
|
||||
//! [`DeviceEvent`]. You can also create and handle your own custom [`Event::UserEvent`]s, if desired.
|
||||
//!
|
||||
//! You can retrieve events by calling [`EventLoop::run_app()`]. This function will
|
||||
//! dispatch events for every [`Window`] that was created with that particular [`EventLoop`], and
|
||||
//! will run until [`exit()`] is used, at which point [`Event::LoopExiting`].
|
||||
//!
|
||||
//! Winit no longer uses a `EventLoop::poll_events() -> impl Iterator<Event>`-based event loop
|
||||
//! model, since that can't be implemented properly on some platforms (e.g web, iOS) and works poorly on
|
||||
//! most other platforms. However, this model can be re-implemented to an extent with
|
||||
#![cfg_attr(
|
||||
any(
|
||||
windows_platform,
|
||||
macos_platform,
|
||||
android_platform,
|
||||
x11_platform,
|
||||
wayland_platform
|
||||
),
|
||||
doc = "[`EventLoopExtPumpEvents::pump_app_events()`][platform::pump_events::EventLoopExtPumpEvents::pump_app_events()]"
|
||||
)]
|
||||
#![cfg_attr(
|
||||
not(any(
|
||||
windows_platform,
|
||||
macos_platform,
|
||||
android_platform,
|
||||
x11_platform,
|
||||
wayland_platform
|
||||
)),
|
||||
doc = "`EventLoopExtPumpEvents::pump_app_events()`"
|
||||
)]
|
||||
//! [^1]. See that method's documentation for more reasons about why
|
||||
//! it's discouraged beyond compatibility reasons.
|
||||
//!
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use winit::application::ApplicationHandler;
|
||||
//! use winit::event::WindowEvent;
|
||||
//! use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
//! use winit::window::{Window, WindowId};
|
||||
//!
|
||||
//! #[derive(Default)]
|
||||
//! struct App {
|
||||
//! window: Option<Window>,
|
||||
//! }
|
||||
//!
|
||||
//! impl ApplicationHandler for App {
|
||||
//! fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
//! self.window = Some(event_loop.create_window(Window::default_attributes()).unwrap());
|
||||
//! }
|
||||
//!
|
||||
//! fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
||||
//! match event {
|
||||
//! WindowEvent::CloseRequested => {
|
||||
//! println!("The close button was pressed; stopping");
|
||||
//! event_loop.exit();
|
||||
//! },
|
||||
//! WindowEvent::RedrawRequested => {
|
||||
//! // Redraw the application.
|
||||
//! //
|
||||
//! // It's preferable for applications that do not render continuously to render in
|
||||
//! // this event rather than in AboutToWait, since rendering in here allows
|
||||
//! // the program to gracefully handle redraws requested by the OS.
|
||||
//!
|
||||
//! // Draw.
|
||||
//!
|
||||
//! // Queue a RedrawRequested event.
|
||||
//! //
|
||||
//! // You only need to call this if you've determined that you need to redraw in
|
||||
//! // applications which do not always need to. Applications that redraw continuously
|
||||
//! // can render here instead.
|
||||
//! self.window.as_ref().unwrap().request_redraw();
|
||||
//! }
|
||||
//! _ => (),
|
||||
//! }
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! let event_loop = EventLoop::new().unwrap();
|
||||
//!
|
||||
//! // ControlFlow::Poll continuously runs the event loop, even if the OS hasn't
|
||||
//! // dispatched any events. This is ideal for games and similar applications.
|
||||
//! event_loop.set_control_flow(ControlFlow::Poll);
|
||||
//!
|
||||
//! // ControlFlow::Wait pauses the event loop if no events are available to process.
|
||||
//! // This is ideal for non-game applications that only update in response to user
|
||||
//! // input, and uses significantly less power/CPU time than ControlFlow::Poll.
|
||||
//! event_loop.set_control_flow(ControlFlow::Wait);
|
||||
//!
|
||||
//! let mut app = App::default();
|
||||
//! event_loop.run_app(&mut app);
|
||||
//! ```
|
||||
//!
|
||||
//! [`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be
|
||||
//! compared to the value returned by [`Window::id()`] to determine which [`Window`]
|
||||
//! dispatched the event.
|
||||
//!
|
||||
//! # Drawing on the window
|
||||
//!
|
||||
//! Winit doesn't directly provide any methods for drawing on a [`Window`]. However, it allows you to
|
||||
//! retrieve the raw handle of the window and display (see the [`platform`] module and/or the
|
||||
//! [`raw_window_handle`] and [`raw_display_handle`] methods), which in turn allows
|
||||
//! you to create an OpenGL/Vulkan/DirectX/Metal/etc. context that can be used to render graphics.
|
||||
//!
|
||||
//! Note that many platforms will display garbage data in the window's client area if the
|
||||
//! application doesn't render anything to the window by the time the desktop compositor is ready to
|
||||
//! display the window to the user. If you notice this happening, you should create the window with
|
||||
//! [`visible` set to `false`](crate::window::WindowAttributes::with_visible) and explicitly make the
|
||||
//! window visible only once you're ready to render into it.
|
||||
//!
|
||||
//! # UI scaling
|
||||
//!
|
||||
//! UI scaling is important, go read the docs for the [`dpi`] crate for an
|
||||
//! introduction.
|
||||
//!
|
||||
//! All of Winit's functions return physical types, but can take either logical or physical
|
||||
//! coordinates as input, allowing you to use the most convenient coordinate system for your
|
||||
//! particular application.
|
||||
//!
|
||||
//! Winit will dispatch a [`ScaleFactorChanged`] event whenever a window's scale factor has changed.
|
||||
//! This can happen if the user drags their window from a standard-resolution monitor to a high-DPI
|
||||
//! monitor or if the user changes their DPI settings. This allows you to rescale your application's
|
||||
//! UI elements and adjust how the platform changes the window's size to reflect the new scale
|
||||
//! factor. If a window hasn't received a [`ScaleFactorChanged`] event, its scale factor
|
||||
//! can be found by calling [`window.scale_factor()`].
|
||||
//!
|
||||
//! [`ScaleFactorChanged`]: event::WindowEvent::ScaleFactorChanged
|
||||
//! [`window.scale_factor()`]: window::Window::scale_factor
|
||||
//!
|
||||
//! # Cargo Features
|
||||
//!
|
||||
//! Winit provides the following Cargo features:
|
||||
//!
|
||||
//! * `x11` (enabled by default): On Unix platforms, enables the X11 backend.
|
||||
//! * `wayland` (enabled by default): On Unix platforms, enables the Wayland
|
||||
//! backend.
|
||||
//! * `rwh_04`: Implement `raw-window-handle v0.4` traits.
|
||||
//! * `rwh_05`: Implement `raw-window-handle v0.5` traits.
|
||||
//! * `rwh_06`: Implement `raw-window-handle v0.6` traits.
|
||||
//! * `serde`: Enables serialization/deserialization of certain types with
|
||||
//! [Serde](https://crates.io/crates/serde).
|
||||
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
||||
//!
|
||||
//! See the [`platform`] module for documentation on platform-specific cargo
|
||||
//! features.
|
||||
//!
|
||||
//! [`EventLoop`]: event_loop::EventLoop
|
||||
//! [`EventLoop::new()`]: event_loop::EventLoop::new
|
||||
//! [`EventLoop::run_app()`]: event_loop::EventLoop::run_app
|
||||
//! [`exit()`]: event_loop::ActiveEventLoop::exit
|
||||
//! [`Window`]: window::Window
|
||||
//! [`WindowId`]: window::WindowId
|
||||
//! [`WindowAttributes`]: window::WindowAttributes
|
||||
//! [window_new]: window::Window::new
|
||||
//! [`create_window`]: event_loop::ActiveEventLoop::create_window
|
||||
//! [`Window::id()`]: window::Window::id
|
||||
//! [`WindowEvent`]: event::WindowEvent
|
||||
//! [`DeviceEvent`]: event::DeviceEvent
|
||||
//! [`Event::UserEvent`]: event::Event::UserEvent
|
||||
//! [`Event::LoopExiting`]: event::Event::LoopExiting
|
||||
//! [`raw_window_handle`]: ./window/struct.Window.html#method.raw_window_handle
|
||||
//! [`raw_display_handle`]: ./window/struct.Window.html#method.raw_display_handle
|
||||
//! [^1]: `EventLoopExtPumpEvents::pump_app_events()` is only available on Windows, macOS, Android, X11 and Wayland.
|
||||
|
||||
#![deny(rust_2018_idioms)]
|
||||
#![deny(rustdoc::broken_intra_doc_links)]
|
||||
#![deny(clippy::all)]
|
||||
#![deny(unsafe_op_in_unsafe_fn)]
|
||||
#![cfg_attr(clippy, deny(warnings))]
|
||||
// Doc feature labels can be tested locally by running RUSTDOCFLAGS="--cfg=docsrs" cargo +nightly doc
|
||||
#![cfg_attr(
|
||||
docsrs,
|
||||
feature(doc_auto_cfg, doc_cfg_hide),
|
||||
doc(cfg_hide(doc, docsrs))
|
||||
)]
|
||||
#![allow(clippy::missing_safety_doc)]
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
pub use rwh_06 as raw_window_handle;
|
||||
|
||||
// Re-export DPI types so that users don't have to put it in Cargo.toml.
|
||||
#[doc(inline)]
|
||||
pub use dpi;
|
||||
|
||||
pub mod application;
|
||||
#[macro_use]
|
||||
pub mod error;
|
||||
mod cursor;
|
||||
pub mod event;
|
||||
pub mod event_loop;
|
||||
mod icon;
|
||||
pub mod keyboard;
|
||||
pub mod monitor;
|
||||
mod platform_impl;
|
||||
mod utils;
|
||||
pub mod window;
|
||||
|
||||
pub mod platform;
|
||||
@@ -3,7 +3,7 @@
|
||||
//! If you want to get basic information about a monitor, you can use the
|
||||
//! [`MonitorHandle`] type. This is retrieved from one of the following
|
||||
//! methods, which return an iterator of [`MonitorHandle`]:
|
||||
//! - [`EventLoopWindowTarget::available_monitors`](crate::event_loop::EventLoopWindowTarget::available_monitors).
|
||||
//! - [`ActiveEventLoop::available_monitors`](crate::event_loop::ActiveEventLoop::available_monitors).
|
||||
//! - [`Window::available_monitors`](crate::window::Window::available_monitors).
|
||||
use crate::{
|
||||
dpi::{PhysicalPosition, PhysicalSize},
|
||||
@@ -145,7 +145,7 @@ impl MonitorHandle {
|
||||
/// Returns the scale factor of the underlying monitor. To map logical pixels to physical
|
||||
/// pixels and vice versa, use [`Window::scale_factor`].
|
||||
///
|
||||
/// See the [`dpi`](crate::dpi) module for more information.
|
||||
/// See the [`dpi`] module for more information.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
170
src/platform/android.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
//! # Android
|
||||
//!
|
||||
//! The Android backend builds on (and exposes types from) the [`ndk`](https://docs.rs/ndk/) crate.
|
||||
//!
|
||||
//! Native Android applications need some form of "glue" crate that is responsible
|
||||
//! for defining the main entry point for your Rust application as well as tracking
|
||||
//! various life-cycle events and synchronizing with the main JVM thread.
|
||||
//!
|
||||
//! Winit uses the [android-activity](https://docs.rs/android-activity/) as a
|
||||
//! glue crate (prior to `0.28` it used
|
||||
//! [ndk-glue](https://github.com/rust-windowing/android-ndk-rs/tree/master/ndk-glue)).
|
||||
//!
|
||||
//! The version of the glue crate that your application depends on _must_ match the
|
||||
//! version that Winit depends on because the glue crate is responsible for your
|
||||
//! application's main entry point. If Cargo resolves multiple versions, they will
|
||||
//! clash.
|
||||
//!
|
||||
//! `winit` glue compatibility table:
|
||||
//!
|
||||
//! | winit | ndk-glue |
|
||||
//! | :---: | :--------------------------: |
|
||||
//! | 0.29 | `android-activity = "0.5"` |
|
||||
//! | 0.28 | `android-activity = "0.4"` |
|
||||
//! | 0.27 | `ndk-glue = "0.7"` |
|
||||
//! | 0.26 | `ndk-glue = "0.5"` |
|
||||
//! | 0.25 | `ndk-glue = "0.3"` |
|
||||
//! | 0.24 | `ndk-glue = "0.2"` |
|
||||
//!
|
||||
//! The recommended way to avoid a conflict with the glue version is to avoid explicitly
|
||||
//! depending on the `android-activity` crate, and instead consume the API that
|
||||
//! is re-exported by Winit under `winit::platform::android::activity::*`
|
||||
//!
|
||||
//! Running on an Android device needs a dynamic system library. Add this to Cargo.toml:
|
||||
//!
|
||||
//! ```toml
|
||||
//! [lib]
|
||||
//! name = "main"
|
||||
//! crate-type = ["cdylib"]
|
||||
//! ```
|
||||
//!
|
||||
//! All Android applications are based on an `Activity` subclass, and the
|
||||
//! `android-activity` crate is designed to support different choices for this base
|
||||
//! class. Your application _must_ specify the base class it needs via a feature flag:
|
||||
//!
|
||||
//! | Base Class | Feature Flag | Notes |
|
||||
//! | :--------------: | :---------------: | :-----: |
|
||||
//! | `NativeActivity` | `android-native-activity` | Built-in to Android - it is possible to use without compiling any Java or Kotlin code. Java or Kotlin code may be needed to subclass `NativeActivity` to access some platform features. It does not derive from the [`AndroidAppCompat`] base class.|
|
||||
//! | [`GameActivity`] | `android-game-activity` | Derives from [`AndroidAppCompat`], a defacto standard `Activity` base class that helps support a wider range of Android versions. Requires a build system that can compile Java or Kotlin and fetch Android dependencies from a [Maven repository][agdk_jetpack] (or link with an embedded [release][agdk_releases] of [`GameActivity`]) |
|
||||
//!
|
||||
//! [`GameActivity`]: https://developer.android.com/games/agdk/game-activity
|
||||
//! [`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input
|
||||
//! [`AndroidAppCompat`]: https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity
|
||||
//! [agdk_jetpack]: https://developer.android.com/jetpack/androidx/releases/games
|
||||
//! [agdk_releases]: https://developer.android.com/games/agdk/download#agdk-libraries
|
||||
//! [Gradle]: https://developer.android.com/studio/build
|
||||
//!
|
||||
//! For more details, refer to these `android-activity` [example applications](https://github.com/rust-mobile/android-activity/tree/main/examples).
|
||||
//!
|
||||
//! ## Converting from `ndk-glue` to `android-activity`
|
||||
//!
|
||||
//! If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building with `cargo apk`, then the minimal changes would be:
|
||||
//! 1. Remove `ndk-glue` from your `Cargo.toml`
|
||||
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.15", features = [ "android-native-activity" ] }`
|
||||
//! 3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize logging as above).
|
||||
//! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above).
|
||||
|
||||
use crate::{
|
||||
event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder},
|
||||
window::{Window, WindowAttributes},
|
||||
};
|
||||
|
||||
use self::activity::{AndroidApp, ConfigurationRef, Rect};
|
||||
|
||||
/// Additional methods on [`EventLoop`] that are specific to Android.
|
||||
pub trait EventLoopExtAndroid {}
|
||||
|
||||
impl<T> EventLoopExtAndroid for EventLoop<T> {}
|
||||
|
||||
/// Additional methods on [`ActiveEventLoop`] that are specific to Android.
|
||||
pub trait ActiveEventLoopExtAndroid {}
|
||||
|
||||
/// Additional methods on [`Window`] that are specific to Android.
|
||||
pub trait WindowExtAndroid {
|
||||
fn content_rect(&self) -> Rect;
|
||||
|
||||
fn config(&self) -> ConfigurationRef;
|
||||
}
|
||||
|
||||
impl WindowExtAndroid for Window {
|
||||
fn content_rect(&self) -> Rect {
|
||||
self.window.content_rect()
|
||||
}
|
||||
|
||||
fn config(&self) -> ConfigurationRef {
|
||||
self.window.config()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveEventLoopExtAndroid for ActiveEventLoop {}
|
||||
|
||||
/// Additional methods on [`WindowAttributes`] that are specific to Android.
|
||||
pub trait WindowAttributesExtAndroid {}
|
||||
|
||||
impl WindowAttributesExtAndroid for WindowAttributes {}
|
||||
|
||||
pub trait EventLoopBuilderExtAndroid {
|
||||
/// Associates the `AndroidApp` that was passed to `android_main()` with the event loop
|
||||
///
|
||||
/// This must be called on Android since the `AndroidApp` is not global state.
|
||||
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self;
|
||||
|
||||
/// Calling this will mark the volume keys to be manually handled by the application
|
||||
///
|
||||
/// Default is to let the operating system handle the volume keys
|
||||
fn handle_volume_keys(&mut self) -> &mut Self;
|
||||
}
|
||||
|
||||
impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
|
||||
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self {
|
||||
self.platform_specific.android_app = Some(app);
|
||||
self
|
||||
}
|
||||
|
||||
fn handle_volume_keys(&mut self) -> &mut Self {
|
||||
self.platform_specific.ignore_volume_keys = false;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-export of the `android_activity` API
|
||||
///
|
||||
/// Winit re-exports the `android_activity` API for convenience so that most
|
||||
/// applications can rely on the Winit crate to resolve the required version of
|
||||
/// `android_activity` and avoid any chance of a conflict between Winit and the
|
||||
/// application crate.
|
||||
///
|
||||
/// Unlike most libraries there can only be a single implementation
|
||||
/// of the `android_activity` glue crate linked with an application because
|
||||
/// it is responsible for the application's `android_main()` entry point.
|
||||
///
|
||||
/// Since Winit depends on a specific version of `android_activity` the simplest
|
||||
/// way to avoid creating a conflict is for applications to avoid explicitly
|
||||
/// depending on the `android_activity` crate, and instead consume the API that
|
||||
/// is re-exported by Winit.
|
||||
///
|
||||
/// For compatibility applications should then import the `AndroidApp` type for
|
||||
/// their `android_main(app: AndroidApp)` function like:
|
||||
/// ```rust
|
||||
/// #[cfg(target_os="android")]
|
||||
/// use winit::platform::android::activity::AndroidApp;
|
||||
/// ```
|
||||
pub mod activity {
|
||||
// We enable the `"native-activity"` feature just so that we can build the
|
||||
// docs, but it'll be very confusing for users to see the docs with that
|
||||
// feature enabled, so we avoid inlining it so that they're forced to view
|
||||
// it on the crate's own docs.rs page.
|
||||
#[doc(no_inline)]
|
||||
#[cfg(android_platform)]
|
||||
pub use android_activity::*;
|
||||
|
||||
#[cfg(not(android_platform))]
|
||||
#[doc(hidden)]
|
||||
pub struct Rect;
|
||||
#[cfg(not(android_platform))]
|
||||
#[doc(hidden)]
|
||||
pub struct ConfigurationRef;
|
||||
#[cfg(not(android_platform))]
|
||||
#[doc(hidden)]
|
||||
pub struct AndroidApp;
|
||||
}
|
||||
@@ -1,9 +1,75 @@
|
||||
//! # iOS / UIKit
|
||||
//!
|
||||
//! Winit has an OS requirement of iOS 8 or higher, and is regularly tested on
|
||||
//! iOS 9.3.
|
||||
//!
|
||||
//! iOS's main `UIApplicationMain` does some init work that's required by all
|
||||
//! UI-related code (see issue [#1705]). It is best to create your windows
|
||||
//! inside `Event::Resumed`.
|
||||
//!
|
||||
//! [#1705]: https://github.com/rust-windowing/winit/issues/1705
|
||||
//!
|
||||
//! ## Building app
|
||||
//!
|
||||
//! To build ios app you will need rustc built for this targets:
|
||||
//!
|
||||
//! - armv7-apple-ios
|
||||
//! - armv7s-apple-ios
|
||||
//! - i386-apple-ios
|
||||
//! - aarch64-apple-ios
|
||||
//! - x86_64-apple-ios
|
||||
//!
|
||||
//! Then
|
||||
//!
|
||||
//! ```
|
||||
//! cargo build --target=...
|
||||
//! ```
|
||||
//! The simplest way to integrate your app into xcode environment is to build it
|
||||
//! as a static library. Wrap your main function and export it.
|
||||
//!
|
||||
//! ```rust, ignore
|
||||
//! #[no_mangle]
|
||||
//! pub extern fn start_winit_app() {
|
||||
//! start_inner()
|
||||
//! }
|
||||
//!
|
||||
//! fn start_inner() {
|
||||
//! ...
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! Compile project and then drag resulting .a into Xcode project. Add winit.h to xcode.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! void start_winit_app();
|
||||
//! ```
|
||||
//!
|
||||
//! Use start_winit_app inside your xcode's main function.
|
||||
//!
|
||||
//!
|
||||
//! ## 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 is LoopExiting
|
||||
//!
|
||||
//! Keep in mind that after LoopExiting event is received every attempt to draw with
|
||||
//! opengl will result in segfault.
|
||||
//!
|
||||
//! Also note that app may not receive the LoopExiting event if suspended; it might be SIGKILL'ed.
|
||||
|
||||
use std::os::raw::c_void;
|
||||
|
||||
use crate::{
|
||||
event_loop::EventLoop,
|
||||
monitor::{MonitorHandle, VideoModeHandle},
|
||||
window::{Window, WindowBuilder},
|
||||
window::{Window, WindowAttributes},
|
||||
};
|
||||
|
||||
/// Additional methods on [`EventLoop`] that are specific to iOS.
|
||||
@@ -159,8 +225,8 @@ impl WindowExtIOS for Window {
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on [`WindowBuilder`] that are specific to iOS.
|
||||
pub trait WindowBuilderExtIOS {
|
||||
/// Additional methods on [`WindowAttributes`] that are specific to iOS.
|
||||
pub trait WindowAttributesExtIOS {
|
||||
/// 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
|
||||
@@ -214,42 +280,41 @@ pub trait WindowBuilderExtIOS {
|
||||
fn with_preferred_status_bar_style(self, status_bar_style: StatusBarStyle) -> Self;
|
||||
}
|
||||
|
||||
impl WindowBuilderExtIOS for WindowBuilder {
|
||||
impl WindowAttributesExtIOS for WindowAttributes {
|
||||
#[inline]
|
||||
fn with_scale_factor(mut self, scale_factor: f64) -> Self {
|
||||
self.window.platform_specific.scale_factor = Some(scale_factor);
|
||||
self.platform_specific.scale_factor = Some(scale_factor);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_valid_orientations(mut self, valid_orientations: ValidOrientations) -> Self {
|
||||
self.window.platform_specific.valid_orientations = valid_orientations;
|
||||
self.platform_specific.valid_orientations = valid_orientations;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_prefers_home_indicator_hidden(mut self, hidden: bool) -> Self {
|
||||
self.window.platform_specific.prefers_home_indicator_hidden = hidden;
|
||||
self.platform_specific.prefers_home_indicator_hidden = hidden;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_preferred_screen_edges_deferring_system_gestures(mut self, edges: ScreenEdge) -> Self {
|
||||
self.window
|
||||
.platform_specific
|
||||
self.platform_specific
|
||||
.preferred_screen_edges_deferring_system_gestures = edges;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_prefers_status_bar_hidden(mut self, hidden: bool) -> Self {
|
||||
self.window.platform_specific.prefers_status_bar_hidden = hidden;
|
||||
self.platform_specific.prefers_status_bar_hidden = hidden;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_preferred_status_bar_style(mut self, status_bar_style: StatusBarStyle) -> Self {
|
||||
self.window.platform_specific.preferred_status_bar_style = status_bar_style;
|
||||
self.platform_specific.preferred_status_bar_style = status_bar_style;
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,28 @@
|
||||
//! # macOS / AppKit
|
||||
//!
|
||||
//! Winit has an OS requirement of macOS 10.11 or higher (same as Rust
|
||||
//! itself), and is regularly tested on macOS 10.14.
|
||||
//!
|
||||
//! A lot of functionality expects the application to be ready before you
|
||||
//! start doing anything; this includes creating windows, fetching monitors,
|
||||
//! drawing, and so on, see issues [#2238], [#2051] and [#2087].
|
||||
//!
|
||||
//! If you encounter problems, you should try doing your initialization inside
|
||||
//! `Event::Resumed`.
|
||||
//!
|
||||
//! [#2238]: https://github.com/rust-windowing/winit/issues/2238
|
||||
//! [#2051]: https://github.com/rust-windowing/winit/issues/2051
|
||||
//! [#2087]: https://github.com/rust-windowing/winit/issues/2087
|
||||
|
||||
use std::os::raw::c_void;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
||||
event_loop::{ActiveEventLoop, EventLoopBuilder},
|
||||
monitor::MonitorHandle,
|
||||
window::{Window, WindowBuilder},
|
||||
window::{Window, WindowAttributes},
|
||||
};
|
||||
|
||||
/// Additional methods on [`Window`] that are specific to MacOS.
|
||||
@@ -174,15 +190,15 @@ pub enum ActivationPolicy {
|
||||
Prohibited,
|
||||
}
|
||||
|
||||
/// Additional methods on [`WindowBuilder`] that are specific to MacOS.
|
||||
/// Additional methods on [`WindowAttributes`] that are specific to MacOS.
|
||||
///
|
||||
/// **Note:** Properties dealing with the titlebar will be overwritten by the [`WindowBuilder::with_decorations`] method:
|
||||
/// **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`
|
||||
pub trait WindowBuilderExtMacOS {
|
||||
pub trait WindowAttributesExtMacOS {
|
||||
/// Enables click-and-drag behavior for the entire window, not just the titlebar.
|
||||
fn with_movable_by_window_background(self, movable_by_window_background: bool) -> Self;
|
||||
/// Makes the titlebar transparent and allows the content to appear behind it.
|
||||
@@ -209,65 +225,64 @@ pub trait WindowBuilderExtMacOS {
|
||||
fn with_option_as_alt(self, option_as_alt: OptionAsAlt) -> Self;
|
||||
}
|
||||
|
||||
impl WindowBuilderExtMacOS for WindowBuilder {
|
||||
impl WindowAttributesExtMacOS for WindowAttributes {
|
||||
#[inline]
|
||||
fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> Self {
|
||||
self.window.platform_specific.movable_by_window_background = movable_by_window_background;
|
||||
self.platform_specific.movable_by_window_background = movable_by_window_background;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self {
|
||||
self.window.platform_specific.titlebar_transparent = titlebar_transparent;
|
||||
self.platform_specific.titlebar_transparent = titlebar_transparent;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> Self {
|
||||
self.window.platform_specific.titlebar_hidden = titlebar_hidden;
|
||||
self.platform_specific.titlebar_hidden = titlebar_hidden;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> Self {
|
||||
self.window.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
||||
self.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_title_hidden(mut self, title_hidden: bool) -> Self {
|
||||
self.window.platform_specific.title_hidden = title_hidden;
|
||||
self.platform_specific.title_hidden = title_hidden;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> Self {
|
||||
self.window.platform_specific.fullsize_content_view = fullsize_content_view;
|
||||
self.platform_specific.fullsize_content_view = fullsize_content_view;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> Self {
|
||||
self.window.platform_specific.disallow_hidpi = disallow_hidpi;
|
||||
self.platform_specific.disallow_hidpi = disallow_hidpi;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_has_shadow(mut self, has_shadow: bool) -> Self {
|
||||
self.window.platform_specific.has_shadow = has_shadow;
|
||||
self.platform_specific.has_shadow = has_shadow;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_accepts_first_mouse(mut self, accepts_first_mouse: bool) -> Self {
|
||||
self.window.platform_specific.accepts_first_mouse = accepts_first_mouse;
|
||||
self.platform_specific.accepts_first_mouse = accepts_first_mouse;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self {
|
||||
self.window
|
||||
.platform_specific
|
||||
self.platform_specific
|
||||
.tabbing_identifier
|
||||
.replace(tabbing_identifier.to_string());
|
||||
self
|
||||
@@ -275,7 +290,7 @@ impl WindowBuilderExtMacOS for WindowBuilder {
|
||||
|
||||
#[inline]
|
||||
fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> Self {
|
||||
self.window.platform_specific.option_as_alt = option_as_alt;
|
||||
self.platform_specific.option_as_alt = option_as_alt;
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -375,8 +390,8 @@ impl MonitorHandleExtMacOS for MonitorHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on [`EventLoopWindowTarget`] that are specific to macOS.
|
||||
pub trait EventLoopWindowTargetExtMacOS {
|
||||
/// 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.
|
||||
@@ -389,7 +404,7 @@ pub trait EventLoopWindowTargetExtMacOS {
|
||||
fn allows_automatic_window_tabbing(&self) -> bool;
|
||||
}
|
||||
|
||||
impl EventLoopWindowTargetExtMacOS for EventLoopWindowTarget {
|
||||
impl ActiveEventLoopExtMacOS for ActiveEventLoop {
|
||||
fn hide_application(&self) {
|
||||
self.p.hide_application()
|
||||
}
|
||||
@@ -46,6 +46,7 @@ pub mod pump_events;
|
||||
macos_platform,
|
||||
x11_platform,
|
||||
wayland_platform,
|
||||
orbital_platform,
|
||||
docsrs
|
||||
))]
|
||||
pub mod modifier_supplement;
|
||||
@@ -25,8 +25,7 @@ pub trait KeyEventExtModifierSupplement {
|
||||
impl KeyEventExtModifierSupplement for KeyEvent {
|
||||
#[inline]
|
||||
fn text_with_all_modifiers(&self) -> Option<&str> {
|
||||
self.extra
|
||||
.extra
|
||||
self.platform_specific
|
||||
.text_with_all_modifiers
|
||||
.as_ref()
|
||||
.map(|s| s.as_str())
|
||||
@@ -34,6 +33,6 @@ impl KeyEventExtModifierSupplement for KeyEvent {
|
||||
|
||||
#[inline]
|
||||
fn key_without_modifiers(&self) -> Key {
|
||||
self.extra.extra.key_without_modifiers.clone()
|
||||
self.platform_specific.key_without_modifiers.clone()
|
||||
}
|
||||
}
|
||||
6
src/platform/orbital.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
//! # Orbital / Redox OS
|
||||
//!
|
||||
//! Redox OS has some functionality not yet present that will be implemented
|
||||
//! when its orbital display server provides it.
|
||||
|
||||
// There are no Orbital specific traits yet.
|
||||
@@ -1,22 +1,13 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::{
|
||||
event::Event,
|
||||
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||
};
|
||||
|
||||
/// The return status for `pump_events`
|
||||
pub enum PumpStatus {
|
||||
/// Continue running external loop.
|
||||
Continue,
|
||||
/// Exit external loop.
|
||||
Exit(i32),
|
||||
}
|
||||
use crate::application::ApplicationHandler;
|
||||
use crate::event::Event;
|
||||
use crate::event_loop::{self, ActiveEventLoop, EventLoop};
|
||||
|
||||
/// Additional methods on [`EventLoop`] for pumping events within an external event loop
|
||||
pub trait EventLoopExtPumpEvents {
|
||||
/// A type provided by the user that can be passed through [`Event::UserEvent`].
|
||||
type UserEvent;
|
||||
type UserEvent: 'static;
|
||||
|
||||
/// Pump the `EventLoop` to check for and dispatch pending events.
|
||||
///
|
||||
@@ -32,68 +23,6 @@ pub trait EventLoopExtPumpEvents {
|
||||
/// Passing a `timeout` of `None` means that it may wait indefinitely for new
|
||||
/// events before returning control back to the external loop.
|
||||
///
|
||||
/// ## Example
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// # // Copied from examples/window_pump_events.rs
|
||||
/// # #[cfg(any(
|
||||
/// # windows_platform,
|
||||
/// # macos_platform,
|
||||
/// # x11_platform,
|
||||
/// # wayland_platform,
|
||||
/// # android_platform,
|
||||
/// # ))]
|
||||
/// fn main() -> std::process::ExitCode {
|
||||
/// # use std::{process::ExitCode, thread::sleep, time::Duration};
|
||||
/// #
|
||||
/// # use simple_logger::SimpleLogger;
|
||||
/// # use winit::{
|
||||
/// # event::{Event, WindowEvent},
|
||||
/// # event_loop::EventLoop,
|
||||
/// # platform::pump_events::{EventLoopExtPumpEvents, PumpStatus},
|
||||
/// # window::Window,
|
||||
/// # };
|
||||
/// let mut event_loop = EventLoop::new().unwrap();
|
||||
/// #
|
||||
/// # SimpleLogger::new().init().unwrap();
|
||||
/// let window = Window::builder()
|
||||
/// .with_title("A fantastic window!")
|
||||
/// .build(&event_loop)
|
||||
/// .unwrap();
|
||||
///
|
||||
/// 'main: loop {
|
||||
/// let timeout = Some(Duration::ZERO);
|
||||
/// let status = event_loop.pump_events(timeout, |event, elwt| {
|
||||
/// # if let Event::WindowEvent { event, .. } = &event {
|
||||
/// # // Print only Window events to reduce noise
|
||||
/// # println!("{event:?}");
|
||||
/// # }
|
||||
/// #
|
||||
/// match event {
|
||||
/// Event::WindowEvent {
|
||||
/// event: WindowEvent::CloseRequested,
|
||||
/// window_id,
|
||||
/// } if window_id == window.id() => elwt.exit(),
|
||||
/// Event::AboutToWait => {
|
||||
/// window.request_redraw();
|
||||
/// }
|
||||
/// _ => (),
|
||||
/// }
|
||||
/// });
|
||||
/// if let PumpStatus::Exit(exit_code) = status {
|
||||
/// break 'main ExitCode::from(exit_code as u8);
|
||||
/// }
|
||||
///
|
||||
/// // Sleep for 1/60 second to simulate application work
|
||||
/// //
|
||||
/// // Since `pump_events` doesn't block it will be important to
|
||||
/// // throttle the loop in the app somehow.
|
||||
/// println!("Update()");
|
||||
/// sleep(Duration::from_millis(16));
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// **Note:** This is not a portable API, and its usage involves a number of
|
||||
/// caveats and trade offs that should be considered before using this API!
|
||||
///
|
||||
@@ -137,12 +66,14 @@ pub trait EventLoopExtPumpEvents {
|
||||
/// other lifecycle events occur while the event is buffered.
|
||||
///
|
||||
/// ## Supported Platforms
|
||||
///
|
||||
/// - Windows
|
||||
/// - Linux
|
||||
/// - MacOS
|
||||
/// - Android
|
||||
///
|
||||
/// ## Unsupported Platforms
|
||||
///
|
||||
/// - **Web:** This API is fundamentally incompatible with the event-based way in which
|
||||
/// Web browsers work because it's not possible to have a long-running external
|
||||
/// loop that would block the browser and there is nothing that can be
|
||||
@@ -152,6 +83,7 @@ pub trait EventLoopExtPumpEvents {
|
||||
/// there's no way to support the same approach to polling as on MacOS.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Windows**: The implementation will use `PeekMessage` when checking for
|
||||
/// window messages to avoid blocking your external event loop.
|
||||
///
|
||||
@@ -172,9 +104,24 @@ pub trait EventLoopExtPumpEvents {
|
||||
/// If you render outside of Winit you are likely to see window resizing artifacts
|
||||
/// since MacOS expects applications to render synchronously during any `drawRect`
|
||||
/// callback.
|
||||
fn pump_app_events<A: ApplicationHandler<Self::UserEvent>>(
|
||||
&mut self,
|
||||
timeout: Option<Duration>,
|
||||
app: &mut A,
|
||||
) -> PumpStatus {
|
||||
#[allow(deprecated)]
|
||||
self.pump_events(timeout, |event, event_loop| {
|
||||
event_loop::dispatch_event_for_app(app, event_loop, event)
|
||||
})
|
||||
}
|
||||
|
||||
/// See [`pump_app_events`].
|
||||
///
|
||||
/// [`pump_app_events`]: Self::pump_app_events
|
||||
#[deprecated = "use EventLoopExtPumpEvents::pump_app_events"]
|
||||
fn pump_events<F>(&mut self, timeout: Option<Duration>, event_handler: F) -> PumpStatus
|
||||
where
|
||||
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget);
|
||||
F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop);
|
||||
}
|
||||
|
||||
impl<T> EventLoopExtPumpEvents for EventLoop<T> {
|
||||
@@ -182,8 +129,16 @@ impl<T> EventLoopExtPumpEvents for EventLoop<T> {
|
||||
|
||||
fn pump_events<F>(&mut self, timeout: Option<Duration>, event_handler: F) -> PumpStatus
|
||||
where
|
||||
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget),
|
||||
F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop),
|
||||
{
|
||||
self.event_loop.pump_events(timeout, event_handler)
|
||||
}
|
||||
}
|
||||
|
||||
/// The return status for `pump_events`
|
||||
pub enum PumpStatus {
|
||||
/// Continue running external loop.
|
||||
Continue,
|
||||
/// Exit external loop.
|
||||
Exit(i32),
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
use crate::{
|
||||
error::EventLoopError,
|
||||
event::Event,
|
||||
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||
};
|
||||
use crate::application::ApplicationHandler;
|
||||
use crate::error::EventLoopError;
|
||||
use crate::event::Event;
|
||||
use crate::event_loop::{self, ActiveEventLoop, EventLoop};
|
||||
|
||||
#[cfg(doc)]
|
||||
use crate::{platform::pump_events::EventLoopExtPumpEvents, window::Window};
|
||||
@@ -10,12 +9,19 @@ use crate::{platform::pump_events::EventLoopExtPumpEvents, window::Window};
|
||||
/// Additional methods on [`EventLoop`] to return control flow to the caller.
|
||||
pub trait EventLoopExtRunOnDemand {
|
||||
/// A type provided by the user that can be passed through [`Event::UserEvent`].
|
||||
type UserEvent;
|
||||
type UserEvent: 'static;
|
||||
|
||||
/// Runs the event loop in the calling thread and calls the given `event_handler` closure
|
||||
/// to dispatch any window system events.
|
||||
/// See [`run_app_on_demand`].
|
||||
///
|
||||
/// Unlike [`EventLoop::run`], this function accepts non-`'static` (i.e. non-`move`) closures
|
||||
/// [`run_app_on_demand`]: Self::run_app_on_demand
|
||||
#[deprecated = "use EventLoopExtRunOnDemand::run_app_on_demand"]
|
||||
fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop);
|
||||
|
||||
/// Run the application with the event loop on the calling thread.
|
||||
///
|
||||
/// Unlike [`EventLoop::run_app`], this function accepts non-`'static` (i.e. non-`move`) closures
|
||||
/// and it is possible to return control back to the caller without
|
||||
/// consuming the `EventLoop` (by using [`exit()`]) and
|
||||
/// so the event loop can be re-run after it has exit.
|
||||
@@ -26,11 +32,10 @@ pub trait EventLoopExtRunOnDemand {
|
||||
///
|
||||
/// This API is not designed to run an event loop in bursts that you can exit from and return
|
||||
/// to while maintaining the full state of your application. (If you need something like this
|
||||
/// you can look at the [`EventLoopExtPumpEvents::pump_events()`] API)
|
||||
/// you can look at the [`EventLoopExtPumpEvents::pump_app_events()`] API)
|
||||
///
|
||||
/// Each time `run_on_demand` is called the `event_handler` can expect to receive a
|
||||
/// `NewEvents(Init)` and `Resumed` event (even on platforms that have no suspend/resume
|
||||
/// lifecycle) - which can be used to consistently initialize application state.
|
||||
/// Each time `run_app_on_demand` is called the startup sequence of `init`, followed by
|
||||
/// `resume` is being preserved.
|
||||
///
|
||||
/// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
|
||||
///
|
||||
@@ -40,8 +45,8 @@ pub trait EventLoopExtRunOnDemand {
|
||||
/// backend it is possible to use `EventLoopExtWebSys::spawn()`[^1] more than once instead).
|
||||
/// - No [`Window`] state can be carried between separate runs of the event loop.
|
||||
///
|
||||
/// You are strongly encouraged to use [`EventLoop::run()`] for portability, unless you specifically need
|
||||
/// the ability to re-run a single event loop more than once
|
||||
/// You are strongly encouraged to use [`EventLoop::run_app()`] for portability, unless you
|
||||
/// specifically need the ability to re-run a single event loop more than once
|
||||
///
|
||||
/// # Supported Platforms
|
||||
/// - Windows
|
||||
@@ -62,11 +67,17 @@ pub trait EventLoopExtRunOnDemand {
|
||||
doc = "[^1]: `spawn()` is only available on `wasm` platforms."
|
||||
)]
|
||||
///
|
||||
/// [`exit()`]: EventLoopWindowTarget::exit()
|
||||
/// [`set_control_flow()`]: EventLoopWindowTarget::set_control_flow()
|
||||
fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget);
|
||||
/// [`exit()`]: ActiveEventLoop::exit()
|
||||
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
||||
fn run_app_on_demand<A: ApplicationHandler<Self::UserEvent>>(
|
||||
&mut self,
|
||||
app: &mut A,
|
||||
) -> Result<(), EventLoopError> {
|
||||
#[allow(deprecated)]
|
||||
self.run_on_demand(|event, event_loop| {
|
||||
event_loop::dispatch_event_for_app(app, event_loop, event)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventLoopExtRunOnDemand for EventLoop<T> {
|
||||
@@ -74,14 +85,14 @@ impl<T> EventLoopExtRunOnDemand for EventLoop<T> {
|
||||
|
||||
fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget),
|
||||
F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop),
|
||||
{
|
||||
self.event_loop.window_target().clear_exit();
|
||||
self.event_loop.run_on_demand(event_handler)
|
||||
}
|
||||
}
|
||||
|
||||
impl EventLoopWindowTarget {
|
||||
impl ActiveEventLoop {
|
||||
/// Clear exit status.
|
||||
pub(crate) fn clear_exit(&self) {
|
||||
self.p.clear_exit()
|
||||
@@ -9,7 +9,7 @@ use crate::keyboard::{KeyCode, PhysicalKey};
|
||||
pub trait PhysicalKeyExtScancode {
|
||||
/// The raw value of the platform-specific physical key identifier.
|
||||
///
|
||||
/// Returns `Some(key_id)` if the conversion was succesful; returns `None` otherwise.
|
||||
/// Returns `Some(key_id)` if the conversion was successful; returns `None` otherwise.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
/// - **Windows:** A 16bit extended scancode
|
||||
@@ -24,8 +24,8 @@
|
||||
use std::env;
|
||||
|
||||
use crate::error::NotSupportedError;
|
||||
use crate::event_loop::{AsyncRequestSerial, EventLoopWindowTarget};
|
||||
use crate::window::{ActivationToken, Window, WindowBuilder};
|
||||
use crate::event_loop::{ActiveEventLoop, AsyncRequestSerial};
|
||||
use crate::window::{ActivationToken, Window, WindowAttributes};
|
||||
|
||||
/// The variable which is used mostly on X11.
|
||||
const X11_VAR: &str = "DESKTOP_STARTUP_ID";
|
||||
@@ -47,7 +47,7 @@ pub trait WindowExtStartupNotify {
|
||||
fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError>;
|
||||
}
|
||||
|
||||
pub trait WindowBuilderExtStartupNotify {
|
||||
pub trait WindowAttributesExtStartupNotify {
|
||||
/// Use this [`ActivationToken`] during window creation.
|
||||
///
|
||||
/// Not using such a token upon a window could make your window not gaining
|
||||
@@ -55,16 +55,16 @@ pub trait WindowBuilderExtStartupNotify {
|
||||
fn with_activation_token(self, token: ActivationToken) -> Self;
|
||||
}
|
||||
|
||||
impl EventLoopExtStartupNotify for EventLoopWindowTarget {
|
||||
impl EventLoopExtStartupNotify for ActiveEventLoop {
|
||||
fn read_token_from_env(&self) -> Option<ActivationToken> {
|
||||
match self.p {
|
||||
#[cfg(wayland_platform)]
|
||||
crate::platform_impl::EventLoopWindowTarget::Wayland(_) => env::var(WAYLAND_VAR),
|
||||
crate::platform_impl::ActiveEventLoop::Wayland(_) => env::var(WAYLAND_VAR),
|
||||
#[cfg(x11_platform)]
|
||||
crate::platform_impl::EventLoopWindowTarget::X(_) => env::var(X11_VAR),
|
||||
crate::platform_impl::ActiveEventLoop::X(_) => env::var(X11_VAR),
|
||||
}
|
||||
.ok()
|
||||
.map(ActivationToken::new)
|
||||
.map(ActivationToken::_new)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,9 @@ impl WindowExtStartupNotify for Window {
|
||||
}
|
||||
}
|
||||
|
||||
impl WindowBuilderExtStartupNotify for WindowBuilder {
|
||||
impl WindowAttributesExtStartupNotify for WindowAttributes {
|
||||
fn with_activation_token(mut self, token: ActivationToken) -> Self {
|
||||
self.window.platform_specific.activation_token = Some(token);
|
||||
self.platform_specific.activation_token = Some(token);
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -94,6 +94,6 @@ pub fn reset_activation_token_env() {
|
||||
///
|
||||
/// This could be used before running daemon processes.
|
||||
pub fn set_activation_token_env(token: ActivationToken) {
|
||||
env::set_var(X11_VAR, token.token());
|
||||
env::set_var(WAYLAND_VAR, token.token());
|
||||
env::set_var(X11_VAR, &token._token);
|
||||
env::set_var(WAYLAND_VAR, token._token);
|
||||
}
|
||||
@@ -1,18 +1,33 @@
|
||||
//! # Wayland
|
||||
//!
|
||||
//! **Note:** Windows don't appear on Wayland until you draw/present to them.
|
||||
//!
|
||||
//! By default, Winit loads system libraries using `dlopen`. This can be
|
||||
//! disabled by disabling the `"wayland-dlopen"` cargo feature.
|
||||
//!
|
||||
//! ## Client-side decorations
|
||||
//!
|
||||
//! Winit provides client-side decorations by default, but the behaviour can
|
||||
//! be controlled with the following feature flags:
|
||||
//!
|
||||
//! * `wayland-csd-adwaita` (default).
|
||||
//! * `wayland-csd-adwaita-crossfont`.
|
||||
//! * `wayland-csd-adwaita-notitle`.
|
||||
use crate::{
|
||||
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
||||
event_loop::{ActiveEventLoop, EventLoopBuilder},
|
||||
monitor::MonitorHandle,
|
||||
window::{Window, WindowBuilder},
|
||||
window::{Window, WindowAttributes},
|
||||
};
|
||||
|
||||
pub use crate::window::Theme;
|
||||
|
||||
/// Additional methods on [`EventLoopWindowTarget`] that are specific to Wayland.
|
||||
pub trait EventLoopWindowTargetExtWayland {
|
||||
/// True if the [`EventLoopWindowTarget`] uses Wayland.
|
||||
/// Additional methods on [`ActiveEventLoop`] that are specific to Wayland.
|
||||
pub trait ActiveEventLoopExtWayland {
|
||||
/// True if the [`ActiveEventLoop`] uses Wayland.
|
||||
fn is_wayland(&self) -> bool;
|
||||
}
|
||||
|
||||
impl EventLoopWindowTargetExtWayland for EventLoopWindowTarget {
|
||||
impl ActiveEventLoopExtWayland for ActiveEventLoop {
|
||||
#[inline]
|
||||
fn is_wayland(&self) -> bool {
|
||||
self.p.is_wayland()
|
||||
@@ -50,22 +65,22 @@ pub trait WindowExtWayland {}
|
||||
|
||||
impl WindowExtWayland for Window {}
|
||||
|
||||
/// Additional methods on [`WindowBuilder`] that are specific to Wayland.
|
||||
pub trait WindowBuilderExtWayland {
|
||||
/// Additional methods on [`WindowAttributes`] that are specific to Wayland.
|
||||
pub trait WindowAttributesExtWayland {
|
||||
/// Build window with the given name.
|
||||
///
|
||||
/// The `general` name sets an application ID, which should match the `.desktop`
|
||||
/// file destributed with your program. The `instance` is a `no-op`.
|
||||
/// file distributed with your program. The `instance` is a `no-op`.
|
||||
///
|
||||
/// For details about application ID conventions, see the
|
||||
/// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
|
||||
fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self;
|
||||
}
|
||||
|
||||
impl WindowBuilderExtWayland for WindowBuilder {
|
||||
impl WindowAttributesExtWayland for WindowAttributes {
|
||||
#[inline]
|
||||
fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
|
||||
self.window.platform_specific.name = Some(crate::platform_impl::ApplicationName::new(
|
||||
self.platform_specific.name = Some(crate::platform_impl::ApplicationName::new(
|
||||
general.into(),
|
||||
instance.into(),
|
||||
));
|
||||
@@ -1,12 +1,31 @@
|
||||
//! The web target does not automatically insert the canvas element object into the web page, to
|
||||
//! allow end users to determine how the page should be laid out. Use the [`WindowExtWebSys`] trait
|
||||
//! to retrieve the canvas from the Window. Alternatively, use the [`WindowBuilderExtWebSys`] trait
|
||||
//! to provide your own canvas.
|
||||
//! # Web
|
||||
//!
|
||||
//! The officially supported browsers are Chrome, Firefox and Safari 13.1+,
|
||||
//! though forks of these should work fine.
|
||||
//!
|
||||
//! Winit supports compiling to the `wasm32-unknown-unknown` target with
|
||||
//! `web-sys`.
|
||||
//!
|
||||
//! On the web platform, a Winit window is backed by a `<canvas>` element. You
|
||||
//! can either [provide Winit with a `<canvas>` element][with_canvas], or
|
||||
//! [let Winit create a `<canvas>` element which you can then retrieve][get]
|
||||
//! and insert it into the DOM yourself.
|
||||
//!
|
||||
//! Currently, there is no example code using Winit on Web, see [#3473]. For
|
||||
//! information on using Rust on WebAssembly, check out the [Rust and
|
||||
//! WebAssembly book].
|
||||
//!
|
||||
//! [with_canvas]: WindowAttributesExtWebSys::with_canvas
|
||||
//! [get]: WindowExtWebSys::canvas
|
||||
//! [#3473]: https://github.com/rust-windowing/winit/issues/3473
|
||||
//! [Rust and WebAssembly book]: https://rustwasm.github.io/book/
|
||||
//!
|
||||
//! ## CSS properties
|
||||
//!
|
||||
//! It is recommended **not** to apply certain CSS properties to the canvas:
|
||||
//! - [`transform`]
|
||||
//! - [`border`]
|
||||
//! - [`padding`]
|
||||
//! - [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform)
|
||||
//! - [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border)
|
||||
//! - [`padding`](https://developer.mozilla.org/en-US/docs/Web/CSS/padding)
|
||||
//!
|
||||
//! The following APIs can't take them into account and will therefore provide inaccurate results:
|
||||
//! - [`WindowEvent::Resized`] and [`Window::(set_)inner_size()`]
|
||||
@@ -16,16 +35,13 @@
|
||||
//! - [`Window::set_outer_position()`]
|
||||
//!
|
||||
//! [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized
|
||||
//! [`Window::(set_)inner_size()`]: crate::window::Window::inner_size()
|
||||
//! [`Window::(set_)inner_size()`]: crate::window::Window::inner_size
|
||||
//! [`WindowEvent::Occluded`]: crate::event::WindowEvent::Occluded
|
||||
//! [`WindowEvent::CursorMoved`]: crate::event::WindowEvent::CursorMoved
|
||||
//! [`WindowEvent::CursorEntered`]: crate::event::WindowEvent::CursorEntered
|
||||
//! [`WindowEvent::CursorLeft`]: crate::event::WindowEvent::CursorLeft
|
||||
//! [`WindowEvent::Touch`]: crate::event::WindowEvent::Touch
|
||||
//! [`Window::set_outer_position()`]: crate::window::Window::set_outer_position()
|
||||
//! [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
|
||||
//! [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border
|
||||
//! [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding
|
||||
//! [`Window::set_outer_position()`]: crate::window::Window::set_outer_position
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
@@ -37,13 +53,14 @@ use std::time::Duration;
|
||||
#[cfg(web_platform)]
|
||||
use web_sys::HtmlCanvasElement;
|
||||
|
||||
use crate::cursor::CustomCursorBuilder;
|
||||
use crate::application::ApplicationHandler;
|
||||
use crate::cursor::CustomCursorSource;
|
||||
use crate::event::Event;
|
||||
use crate::event_loop::{EventLoop, EventLoopWindowTarget};
|
||||
use crate::event_loop::{self, ActiveEventLoop, EventLoop};
|
||||
#[cfg(web_platform)]
|
||||
use crate::platform_impl::CustomCursorFuture as PlatformCustomCursorFuture;
|
||||
use crate::platform_impl::{PlatformCustomCursor, PlatformCustomCursorBuilder};
|
||||
use crate::window::{CustomCursor, Window, WindowBuilder};
|
||||
use crate::platform_impl::PlatformCustomCursorSource;
|
||||
use crate::window::{CustomCursor, Window, WindowAttributes};
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
#[doc(hidden)]
|
||||
@@ -85,9 +102,9 @@ impl WindowExtWebSys for Window {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait WindowBuilderExtWebSys {
|
||||
pub trait WindowAttributesExtWebSys {
|
||||
/// Pass an [`HtmlCanvasElement`] to be used for this [`Window`]. If [`None`],
|
||||
/// [`WindowBuilder::build()`] will create one.
|
||||
/// [`WindowAttributes::default()`] will create one.
|
||||
///
|
||||
/// In any case, the canvas won't be automatically inserted into the web page.
|
||||
///
|
||||
@@ -119,24 +136,24 @@ pub trait WindowBuilderExtWebSys {
|
||||
fn with_append(self, append: bool) -> Self;
|
||||
}
|
||||
|
||||
impl WindowBuilderExtWebSys for WindowBuilder {
|
||||
impl WindowAttributesExtWebSys for WindowAttributes {
|
||||
fn with_canvas(mut self, canvas: Option<HtmlCanvasElement>) -> Self {
|
||||
self.window.platform_specific.set_canvas(canvas);
|
||||
self.platform_specific.set_canvas(canvas);
|
||||
self
|
||||
}
|
||||
|
||||
fn with_prevent_default(mut self, prevent_default: bool) -> Self {
|
||||
self.window.platform_specific.prevent_default = prevent_default;
|
||||
self.platform_specific.prevent_default = prevent_default;
|
||||
self
|
||||
}
|
||||
|
||||
fn with_focusable(mut self, focusable: bool) -> Self {
|
||||
self.window.platform_specific.focusable = focusable;
|
||||
self.platform_specific.focusable = focusable;
|
||||
self
|
||||
}
|
||||
|
||||
fn with_append(mut self, append: bool) -> Self {
|
||||
self.window.platform_specific.append = append;
|
||||
self.platform_specific.append = append;
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -144,18 +161,18 @@ impl WindowBuilderExtWebSys for WindowBuilder {
|
||||
/// Additional methods on `EventLoop` that are specific to the web.
|
||||
pub trait EventLoopExtWebSys {
|
||||
/// A type provided by the user that can be passed through `Event::UserEvent`.
|
||||
type UserEvent;
|
||||
type UserEvent: 'static;
|
||||
|
||||
/// Initializes the winit event loop.
|
||||
///
|
||||
/// Unlike
|
||||
#[cfg_attr(
|
||||
all(web_platform, target_feature = "exception-handling"),
|
||||
doc = "`run()`"
|
||||
doc = "`run_app()`"
|
||||
)]
|
||||
#[cfg_attr(
|
||||
not(all(web_platform, target_feature = "exception-handling")),
|
||||
doc = "[`run()`]"
|
||||
doc = "[`run_app()`]"
|
||||
)]
|
||||
/// [^1], this returns immediately, and doesn't throw an exception in order to
|
||||
/// satisfy its [`!`] return type.
|
||||
@@ -167,26 +184,38 @@ pub trait EventLoopExtWebSys {
|
||||
///
|
||||
#[cfg_attr(
|
||||
not(all(web_platform, target_feature = "exception-handling")),
|
||||
doc = "[`run()`]: EventLoop::run()"
|
||||
doc = "[`run_app()`]: EventLoop::run_app()"
|
||||
)]
|
||||
/// [^1]: `run()` is _not_ available on WASM when the target supports `exception-handling`.
|
||||
/// [^1]: `run_app()` is _not_ available on WASM when the target supports `exception-handling`.
|
||||
fn spawn_app<A: ApplicationHandler<Self::UserEvent> + 'static>(self, app: A);
|
||||
|
||||
/// See [`spawn_app`].
|
||||
///
|
||||
/// [`spawn_app`]: Self::spawn_app
|
||||
#[deprecated = "use EventLoopExtWebSys::spawn_app"]
|
||||
fn spawn<F>(self, event_handler: F)
|
||||
where
|
||||
F: 'static + FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget);
|
||||
F: 'static + FnMut(Event<Self::UserEvent>, &ActiveEventLoop);
|
||||
}
|
||||
|
||||
impl<T> EventLoopExtWebSys for EventLoop<T> {
|
||||
type UserEvent = T;
|
||||
|
||||
fn spawn_app<A: ApplicationHandler<Self::UserEvent> + 'static>(self, mut app: A) {
|
||||
self.event_loop.spawn(move |event, event_loop| {
|
||||
event_loop::dispatch_event_for_app(&mut app, event_loop, event)
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn<F>(self, event_handler: F)
|
||||
where
|
||||
F: 'static + FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget),
|
||||
F: 'static + FnMut(Event<Self::UserEvent>, &ActiveEventLoop),
|
||||
{
|
||||
self.event_loop.spawn(event_handler)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait EventLoopWindowTargetExtWebSys {
|
||||
pub trait ActiveEventLoopExtWebSys {
|
||||
/// Sets the strategy for [`ControlFlow::Poll`].
|
||||
///
|
||||
/// See [`PollStrategy`].
|
||||
@@ -200,9 +229,18 @@ pub trait EventLoopWindowTargetExtWebSys {
|
||||
///
|
||||
/// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll
|
||||
fn poll_strategy(&self) -> PollStrategy;
|
||||
|
||||
/// Async version of [`ActiveEventLoop::create_custom_cursor()`] which waits until the
|
||||
/// cursor has completely finished loading.
|
||||
fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture;
|
||||
}
|
||||
|
||||
impl EventLoopWindowTargetExtWebSys for EventLoopWindowTarget {
|
||||
impl ActiveEventLoopExtWebSys for ActiveEventLoop {
|
||||
#[inline]
|
||||
fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture {
|
||||
self.p.create_custom_cursor_async(source)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_poll_strategy(&self, strategy: PollStrategy) {
|
||||
self.p.set_poll_strategy(strategy);
|
||||
@@ -249,14 +287,14 @@ pub trait CustomCursorExtWebSys {
|
||||
/// but browser support for image formats is inconsistent. Using [PNG] is recommended.
|
||||
///
|
||||
/// [PNG]: https://en.wikipedia.org/wiki/PNG
|
||||
fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorBuilder;
|
||||
fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorSource;
|
||||
|
||||
/// Crates a new animated cursor from multiple [`CustomCursor`]s.
|
||||
/// Supplied `cursors` can't be empty or other animations.
|
||||
fn from_animation(
|
||||
duration: Duration,
|
||||
cursors: Vec<CustomCursor>,
|
||||
) -> Result<CustomCursorBuilder, BadAnimation>;
|
||||
) -> Result<CustomCursorSource, BadAnimation>;
|
||||
}
|
||||
|
||||
impl CustomCursorExtWebSys for CustomCursor {
|
||||
@@ -264,9 +302,9 @@ impl CustomCursorExtWebSys for CustomCursor {
|
||||
self.inner.animation
|
||||
}
|
||||
|
||||
fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorBuilder {
|
||||
CustomCursorBuilder {
|
||||
inner: PlatformCustomCursorBuilder::Url {
|
||||
fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorSource {
|
||||
CustomCursorSource {
|
||||
inner: PlatformCustomCursorSource::Url {
|
||||
url,
|
||||
hotspot_x,
|
||||
hotspot_y,
|
||||
@@ -277,7 +315,7 @@ impl CustomCursorExtWebSys for CustomCursor {
|
||||
fn from_animation(
|
||||
duration: Duration,
|
||||
cursors: Vec<CustomCursor>,
|
||||
) -> Result<CustomCursorBuilder, BadAnimation> {
|
||||
) -> Result<CustomCursorSource, BadAnimation> {
|
||||
if cursors.is_empty() {
|
||||
return Err(BadAnimation::Empty);
|
||||
}
|
||||
@@ -286,8 +324,8 @@ impl CustomCursorExtWebSys for CustomCursor {
|
||||
return Err(BadAnimation::Animation);
|
||||
}
|
||||
|
||||
Ok(CustomCursorBuilder {
|
||||
inner: PlatformCustomCursorBuilder::Animation { duration, cursors },
|
||||
Ok(CustomCursorSource {
|
||||
inner: PlatformCustomCursorSource::Animation { duration, cursors },
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -312,26 +350,11 @@ impl fmt::Display for BadAnimation {
|
||||
|
||||
impl Error for BadAnimation {}
|
||||
|
||||
pub trait CustomCursorBuilderExtWebSys {
|
||||
/// Async version of [`CustomCursorBuilder::build()`] which waits until the
|
||||
/// cursor has completely finished loading.
|
||||
fn build_async(self, window_target: &EventLoopWindowTarget) -> CustomCursorFuture;
|
||||
}
|
||||
|
||||
impl CustomCursorBuilderExtWebSys for CustomCursorBuilder {
|
||||
fn build_async(self, window_target: &EventLoopWindowTarget) -> CustomCursorFuture {
|
||||
CustomCursorFuture(PlatformCustomCursor::build_async(
|
||||
self.inner,
|
||||
&window_target.p,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
struct PlatformCustomCursorFuture;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CustomCursorFuture(PlatformCustomCursorFuture);
|
||||
pub struct CustomCursorFuture(pub(crate) PlatformCustomCursorFuture);
|
||||
|
||||
impl Future for CustomCursorFuture {
|
||||
type Output = Result<CustomCursor, CustomCursorError>;
|
||||
@@ -1,3 +1,7 @@
|
||||
//! # Windows
|
||||
//!
|
||||
//! The supported OS version is Windows 7 or higher, though Windows 10 is
|
||||
//! tested regularly.
|
||||
use std::{ffi::c_void, path::Path};
|
||||
|
||||
use crate::{
|
||||
@@ -5,7 +9,7 @@ use crate::{
|
||||
event::DeviceId,
|
||||
event_loop::EventLoopBuilder,
|
||||
monitor::MonitorHandle,
|
||||
window::{BadIcon, Icon, Window, WindowBuilder},
|
||||
window::{BadIcon, Icon, Window, WindowAttributes},
|
||||
};
|
||||
|
||||
/// Window Handle type used by Win32 API
|
||||
@@ -198,7 +202,7 @@ pub trait WindowExtWindows {
|
||||
///
|
||||
/// A window must be enabled before it can be activated.
|
||||
/// If an application has create a modal dialog box by disabling its owner window
|
||||
/// (as described in [`WindowBuilderExtWindows::with_owner_window`]), the application must enable
|
||||
/// (as described in [`WindowAttributesExtWindows::with_owner_window`]), the application must enable
|
||||
/// the owner window before destroying the dialog box.
|
||||
/// Otherwise, another window will receive the keyboard focus and be activated.
|
||||
///
|
||||
@@ -296,11 +300,11 @@ impl WindowExtWindows for Window {
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on `WindowBuilder` that are specific to Windows.
|
||||
/// Additional methods on `WindowAttributes` that are specific to Windows.
|
||||
#[allow(rustdoc::broken_intra_doc_links)]
|
||||
pub trait WindowBuilderExtWindows {
|
||||
pub trait WindowAttributesExtWindows {
|
||||
/// Set an owner to the window to be created. Can be used to create a dialog box, for example.
|
||||
/// This only works when [`WindowBuilder::with_parent_window`] isn't called or set to `None`.
|
||||
/// This only works when [`WindowAttributes::with_parent_window`] isn't called or set to `None`.
|
||||
/// Can be used in combination with [`WindowExtWindows::set_enable(false)`](WindowExtWindows::set_enable)
|
||||
/// on the owner window to create a modal dialog box.
|
||||
///
|
||||
@@ -386,88 +390,88 @@ pub trait WindowBuilderExtWindows {
|
||||
fn with_corner_preference(self, corners: CornerPreference) -> Self;
|
||||
}
|
||||
|
||||
impl WindowBuilderExtWindows for WindowBuilder {
|
||||
impl WindowAttributesExtWindows for WindowAttributes {
|
||||
#[inline]
|
||||
fn with_owner_window(mut self, parent: HWND) -> Self {
|
||||
self.window.platform_specific.owner = Some(parent);
|
||||
self.platform_specific.owner = Some(parent);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_menu(mut self, menu: HMENU) -> Self {
|
||||
self.window.platform_specific.menu = Some(menu);
|
||||
self.platform_specific.menu = Some(menu);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_taskbar_icon(mut self, taskbar_icon: Option<Icon>) -> Self {
|
||||
self.window.platform_specific.taskbar_icon = taskbar_icon;
|
||||
self.platform_specific.taskbar_icon = taskbar_icon;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_no_redirection_bitmap(mut self, flag: bool) -> Self {
|
||||
self.window.platform_specific.no_redirection_bitmap = flag;
|
||||
self.platform_specific.no_redirection_bitmap = flag;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_drag_and_drop(mut self, flag: bool) -> Self {
|
||||
self.window.platform_specific.drag_and_drop = flag;
|
||||
self.platform_specific.drag_and_drop = flag;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_skip_taskbar(mut self, skip: bool) -> Self {
|
||||
self.window.platform_specific.skip_taskbar = skip;
|
||||
self.platform_specific.skip_taskbar = skip;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_class_name<S: Into<String>>(mut self, class_name: S) -> Self {
|
||||
self.window.platform_specific.class_name = class_name.into();
|
||||
self.platform_specific.class_name = class_name.into();
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_undecorated_shadow(mut self, shadow: bool) -> Self {
|
||||
self.window.platform_specific.decoration_shadow = shadow;
|
||||
self.platform_specific.decoration_shadow = shadow;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_system_backdrop(mut self, backdrop_type: BackdropType) -> Self {
|
||||
self.window.platform_specific.backdrop_type = backdrop_type;
|
||||
self.platform_specific.backdrop_type = backdrop_type;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_clip_children(mut self, flag: bool) -> Self {
|
||||
self.window.platform_specific.clip_children = flag;
|
||||
self.platform_specific.clip_children = flag;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_border_color(mut self, color: Option<Color>) -> Self {
|
||||
self.window.platform_specific.border_color = Some(color.unwrap_or(Color::NONE));
|
||||
self.platform_specific.border_color = Some(color.unwrap_or(Color::NONE));
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_title_background_color(mut self, color: Option<Color>) -> Self {
|
||||
self.window.platform_specific.title_background_color = Some(color.unwrap_or(Color::NONE));
|
||||
self.platform_specific.title_background_color = Some(color.unwrap_or(Color::NONE));
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_title_text_color(mut self, color: Color) -> Self {
|
||||
self.window.platform_specific.title_text_color = Some(color);
|
||||
self.platform_specific.title_text_color = Some(color);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_corner_preference(mut self, corners: CornerPreference) -> Self {
|
||||
self.window.platform_specific.corner_preference = Some(corners);
|
||||
self.platform_specific.corner_preference = Some(corners);
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -504,7 +508,7 @@ pub trait DeviceIdExtWindows {
|
||||
impl DeviceIdExtWindows for DeviceId {
|
||||
#[inline]
|
||||
fn persistent_identifier(&self) -> Option<String> {
|
||||
crate::platform_impl::persistent_identifier(*self)
|
||||
self.0.persistent_identifier()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! # X11
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
||||
event_loop::{ActiveEventLoop, EventLoopBuilder},
|
||||
monitor::MonitorHandle,
|
||||
window::{Window, WindowBuilder},
|
||||
window::{Window, WindowAttributes},
|
||||
};
|
||||
|
||||
use crate::dpi::Size;
|
||||
@@ -61,7 +62,7 @@ pub enum WindowType {
|
||||
pub type XlibErrorHook =
|
||||
Box<dyn Fn(*mut std::ffi::c_void, *mut std::ffi::c_void) -> bool + Send + Sync>;
|
||||
|
||||
/// A unique identifer for an X11 visual.
|
||||
/// A unique identifier for an X11 visual.
|
||||
pub type XVisualID = u32;
|
||||
|
||||
/// A unique identifier for an X11 window.
|
||||
@@ -69,7 +70,7 @@ pub type XWindow = u32;
|
||||
|
||||
/// Hook to winit's xlib error handling callback.
|
||||
///
|
||||
/// This method is provided as a safe way to handle the errors comming from X11
|
||||
/// This method is provided as a safe way to handle the errors coming from X11
|
||||
/// when using xlib in external crates, like glutin for GLX access. Trying to
|
||||
/// handle errors by speculating with `XSetErrorHandler` is [`unsafe`].
|
||||
///
|
||||
@@ -89,13 +90,13 @@ pub fn register_xlib_error_hook(hook: XlibErrorHook) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on [`EventLoopWindowTarget`] that are specific to X11.
|
||||
pub trait EventLoopWindowTargetExtX11 {
|
||||
/// True if the [`EventLoopWindowTarget`] uses X11.
|
||||
/// Additional methods on [`ActiveEventLoop`] that are specific to X11.
|
||||
pub trait ActiveEventLoopExtX11 {
|
||||
/// True if the [`ActiveEventLoop`] uses X11.
|
||||
fn is_x11(&self) -> bool;
|
||||
}
|
||||
|
||||
impl EventLoopWindowTargetExtX11 for EventLoopWindowTarget {
|
||||
impl ActiveEventLoopExtX11 for ActiveEventLoop {
|
||||
#[inline]
|
||||
fn is_x11(&self) -> bool {
|
||||
!self.p.is_wayland()
|
||||
@@ -133,8 +134,8 @@ pub trait WindowExtX11 {}
|
||||
|
||||
impl WindowExtX11 for Window {}
|
||||
|
||||
/// Additional methods on [`WindowBuilder`] that are specific to X11.
|
||||
pub trait WindowBuilderExtX11 {
|
||||
/// Additional methods on [`WindowAttributes`] that are specific to X11.
|
||||
pub trait WindowAttributesExtX11 {
|
||||
/// Create this window with a specific X11 visual.
|
||||
fn with_x11_visual(self, visual_id: XVisualID) -> Self;
|
||||
|
||||
@@ -160,12 +161,12 @@ pub trait WindowBuilderExtX11 {
|
||||
/// ```
|
||||
/// # use winit::dpi::{LogicalSize, PhysicalSize};
|
||||
/// # use winit::window::Window;
|
||||
/// # use winit::platform::x11::WindowBuilderExtX11;
|
||||
/// # use winit::platform::x11::WindowAttributesExtX11;
|
||||
/// // Specify the size in logical dimensions like this:
|
||||
/// Window::builder().with_base_size(LogicalSize::new(400.0, 200.0));
|
||||
/// Window::default_attributes().with_base_size(LogicalSize::new(400.0, 200.0));
|
||||
///
|
||||
/// // Or specify the size in physical dimensions like this:
|
||||
/// Window::builder().with_base_size(PhysicalSize::new(400, 200));
|
||||
/// Window::default_attributes().with_base_size(PhysicalSize::new(400, 200));
|
||||
/// ```
|
||||
fn with_base_size<S: Into<Size>>(self, base_size: S) -> Self;
|
||||
|
||||
@@ -175,34 +176,33 @@ pub trait WindowBuilderExtX11 {
|
||||
///
|
||||
/// ```no_run
|
||||
/// use winit::window::Window;
|
||||
/// use winit::platform::x11::{XWindow, WindowBuilderExtX11};
|
||||
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// let event_loop = winit::event_loop::EventLoop::new().unwrap();
|
||||
/// use winit::event_loop::ActiveEventLoop;
|
||||
/// use winit::platform::x11::{XWindow, WindowAttributesExtX11};
|
||||
/// # fn create_window(event_loop: &ActiveEventLoop) -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// let parent_window_id = std::env::args().nth(1).unwrap().parse::<XWindow>()?;
|
||||
/// let window = Window::builder()
|
||||
/// .with_embed_parent_window(parent_window_id)
|
||||
/// .build(&event_loop)?;
|
||||
/// let window_attributes = Window::default_attributes().with_embed_parent_window(parent_window_id);
|
||||
/// let window = event_loop.create_window(window_attributes)?;
|
||||
/// # Ok(()) }
|
||||
/// ```
|
||||
fn with_embed_parent_window(self, parent_window_id: XWindow) -> Self;
|
||||
}
|
||||
|
||||
impl WindowBuilderExtX11 for WindowBuilder {
|
||||
impl WindowAttributesExtX11 for WindowAttributes {
|
||||
#[inline]
|
||||
fn with_x11_visual(mut self, visual_id: XVisualID) -> Self {
|
||||
self.window.platform_specific.x11.visual_id = Some(visual_id);
|
||||
self.platform_specific.x11.visual_id = Some(visual_id);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_x11_screen(mut self, screen_id: i32) -> Self {
|
||||
self.window.platform_specific.x11.screen_id = Some(screen_id);
|
||||
self.platform_specific.x11.screen_id = Some(screen_id);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
|
||||
self.window.platform_specific.name = Some(crate::platform_impl::ApplicationName::new(
|
||||
self.platform_specific.name = Some(crate::platform_impl::ApplicationName::new(
|
||||
general.into(),
|
||||
instance.into(),
|
||||
));
|
||||
@@ -211,25 +211,25 @@ impl WindowBuilderExtX11 for WindowBuilder {
|
||||
|
||||
#[inline]
|
||||
fn with_override_redirect(mut self, override_redirect: bool) -> Self {
|
||||
self.window.platform_specific.x11.override_redirect = override_redirect;
|
||||
self.platform_specific.x11.override_redirect = override_redirect;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_x11_window_type(mut self, x11_window_types: Vec<WindowType>) -> Self {
|
||||
self.window.platform_specific.x11.x11_window_types = x11_window_types;
|
||||
self.platform_specific.x11.x11_window_types = x11_window_types;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_base_size<S: Into<Size>>(mut self, base_size: S) -> Self {
|
||||
self.window.platform_specific.x11.base_size = Some(base_size.into());
|
||||
self.platform_specific.x11.base_size = Some(base_size.into());
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_embed_parent_window(mut self, parent_window_id: XWindow) -> Self {
|
||||
self.window.platform_specific.x11.embed_window = Some(parent_window_id);
|
||||
self.platform_specific.x11.embed_window = Some(parent_window_id);
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -174,7 +174,7 @@ pub fn character_map_and_combine_key(
|
||||
let key_map = match app.device_key_character_map(device_id) {
|
||||
Ok(key_map) => key_map,
|
||||
Err(err) => {
|
||||
log::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
|
||||
tracing::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
@@ -188,7 +188,7 @@ pub fn character_map_and_combine_key(
|
||||
Ok(Some(key)) => Some(key),
|
||||
Ok(None) => None,
|
||||
Err(err) => {
|
||||
log::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
|
||||
tracing::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -213,7 +213,7 @@ pub fn character_map_and_combine_key(
|
||||
None
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!("KeyEvent: Failed to get key map character: {err:?}");
|
||||
tracing::warn!("KeyEvent: Failed to get key map character: {err:?}");
|
||||
*combining_accent = None;
|
||||
None
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use std::{
|
||||
marker::PhantomData,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc, Arc, Mutex, RwLock,
|
||||
mpsc, Arc, Mutex,
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
@@ -16,27 +16,29 @@ use android_activity::input::{InputEvent, KeyAction, Keycode, MotionAction};
|
||||
use android_activity::{
|
||||
AndroidApp, AndroidAppWaker, ConfigurationRef, InputStatus, MainEvent, Rect,
|
||||
};
|
||||
use log::{debug, trace, warn};
|
||||
use once_cell::sync::Lazy;
|
||||
use tracing::{debug, trace, warn};
|
||||
|
||||
use crate::{
|
||||
cursor::Cursor,
|
||||
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
|
||||
error,
|
||||
event::{self, Force, InnerSizeWriter, StartCause},
|
||||
event_loop::{self, ControlFlow, DeviceEvents, EventLoopWindowTarget as RootELW},
|
||||
event_loop::{self, ActiveEventLoop as RootAEL, ControlFlow, DeviceEvents},
|
||||
platform::pump_events::PumpStatus,
|
||||
window::{
|
||||
self, CursorGrabMode, ImePurpose, ResizeDirection, Theme, WindowButtons, WindowId,
|
||||
WindowLevel,
|
||||
self, CursorGrabMode, CustomCursor, CustomCursorSource, ImePurpose, ResizeDirection, Theme,
|
||||
WindowButtons, WindowLevel,
|
||||
},
|
||||
};
|
||||
use crate::{error::EventLoopError, platform_impl::Fullscreen};
|
||||
|
||||
mod keycodes;
|
||||
|
||||
static HAS_FOCUS: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(true));
|
||||
const WINDOW_ID: u64 = 0;
|
||||
pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursor;
|
||||
pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursorSource;
|
||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||
|
||||
static HAS_FOCUS: AtomicBool = AtomicBool::new(true);
|
||||
|
||||
/// Returns the minimum `Option<Duration>`, taking into account that `None`
|
||||
/// equates to an infinite timeout, not a zero timeout (so can't just use
|
||||
@@ -143,7 +145,7 @@ pub struct KeyEventExtra {}
|
||||
|
||||
pub struct EventLoop<T: 'static> {
|
||||
android_app: AndroidApp,
|
||||
window_target: event_loop::EventLoopWindowTarget,
|
||||
window_target: event_loop::ActiveEventLoop,
|
||||
redraw_flag: SharedFlag,
|
||||
user_events_sender: mpsc::Sender<T>,
|
||||
user_events_receiver: PeekableReceiver<T>, //must wake looper whenever something gets sent
|
||||
@@ -181,8 +183,8 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
Ok(Self {
|
||||
android_app: android_app.clone(),
|
||||
window_target: event_loop::EventLoopWindowTarget {
|
||||
p: EventLoopWindowTarget {
|
||||
window_target: event_loop::ActiveEventLoop {
|
||||
p: ActiveEventLoop {
|
||||
app: android_app.clone(),
|
||||
control_flow: Cell::new(ControlFlow::default()),
|
||||
exit: Cell::new(false),
|
||||
@@ -207,7 +209,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
fn single_iteration<F>(&mut self, main_event: Option<MainEvent<'_>>, callback: &mut F)
|
||||
where
|
||||
F: FnMut(event::Event<T>, &RootELW),
|
||||
F: FnMut(event::Event<T>, &RootAEL),
|
||||
{
|
||||
trace!("Mainloop iteration");
|
||||
|
||||
@@ -233,20 +235,20 @@ impl<T: 'static> EventLoop<T> {
|
||||
warn!("TODO: find a way to notify application of content rect change");
|
||||
}
|
||||
MainEvent::GainedFocus => {
|
||||
*HAS_FOCUS.write().unwrap() = true;
|
||||
HAS_FOCUS.store(true, Ordering::Relaxed);
|
||||
callback(
|
||||
event::Event::WindowEvent {
|
||||
window_id: WindowId::from(WINDOW_ID),
|
||||
window_id: window::WindowId(WindowId),
|
||||
event: event::WindowEvent::Focused(true),
|
||||
},
|
||||
self.window_target(),
|
||||
);
|
||||
}
|
||||
MainEvent::LostFocus => {
|
||||
*HAS_FOCUS.write().unwrap() = false;
|
||||
HAS_FOCUS.store(false, Ordering::Relaxed);
|
||||
callback(
|
||||
event::Event::WindowEvent {
|
||||
window_id: WindowId::from(WINDOW_ID),
|
||||
window_id: window::WindowId(WindowId),
|
||||
event: event::WindowEvent::Focused(false),
|
||||
},
|
||||
self.window_target(),
|
||||
@@ -261,7 +263,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
MonitorHandle::new(self.android_app.clone()).size(),
|
||||
));
|
||||
let event = event::Event::WindowEvent {
|
||||
window_id: WindowId::from(WINDOW_ID),
|
||||
window_id: window::WindowId(WindowId),
|
||||
event: event::WindowEvent::ScaleFactorChanged {
|
||||
inner_size_writer: InnerSizeWriter::new(Arc::downgrade(
|
||||
&new_inner_size,
|
||||
@@ -328,7 +330,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
log::warn!("Failed to get input events iterator: {err:?}");
|
||||
tracing::warn!("Failed to get input events iterator: {err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -349,7 +351,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
PhysicalSize::new(0, 0)
|
||||
};
|
||||
let event = event::Event::WindowEvent {
|
||||
window_id: WindowId::from(WINDOW_ID),
|
||||
window_id: window::WindowId(WindowId),
|
||||
event: event::WindowEvent::Resized(size),
|
||||
};
|
||||
callback(event, self.window_target());
|
||||
@@ -359,7 +361,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
if pending_redraw {
|
||||
pending_redraw = false;
|
||||
let event = event::Event::WindowEvent {
|
||||
window_id: WindowId::from(WINDOW_ID),
|
||||
window_id: window::WindowId(WindowId),
|
||||
event: event::WindowEvent::RedrawRequested,
|
||||
};
|
||||
callback(event, self.window_target());
|
||||
@@ -379,13 +381,13 @@ impl<T: 'static> EventLoop<T> {
|
||||
callback: &mut F,
|
||||
) -> InputStatus
|
||||
where
|
||||
F: FnMut(event::Event<T>, &RootELW),
|
||||
F: FnMut(event::Event<T>, &RootAEL),
|
||||
{
|
||||
let mut input_status = InputStatus::Handled;
|
||||
match event {
|
||||
InputEvent::MotionEvent(motion_event) => {
|
||||
let window_id = WindowId::from(WINDOW_ID);
|
||||
let device_id = event::DeviceId::from(motion_event.device_id() as u64);
|
||||
let window_id = window::WindowId(WindowId);
|
||||
let device_id = event::DeviceId(DeviceId(motion_event.device_id()));
|
||||
|
||||
let phase = match motion_event.action() {
|
||||
MotionAction::Down | MotionAction::PointerDown => {
|
||||
@@ -455,9 +457,9 @@ impl<T: 'static> EventLoop<T> {
|
||||
);
|
||||
|
||||
let event = event::Event::WindowEvent {
|
||||
window_id: WindowId::from(WINDOW_ID),
|
||||
window_id: window::WindowId(WindowId),
|
||||
event: event::WindowEvent::KeyboardInput {
|
||||
device_id: event::DeviceId::from(key.device_id() as u64),
|
||||
device_id: event::DeviceId(DeviceId(key.device_id())),
|
||||
event: event::KeyEvent {
|
||||
state,
|
||||
physical_key: keycodes::to_physical_key(keycode),
|
||||
@@ -465,9 +467,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
location: keycodes::to_location(keycode),
|
||||
repeat: key.repeat_count() > 0,
|
||||
text: None,
|
||||
extra: event::KeyExtra {
|
||||
extra: KeyEventExtra {},
|
||||
},
|
||||
platform_specific: KeyEventExtra {},
|
||||
},
|
||||
is_synthetic: false,
|
||||
},
|
||||
@@ -486,14 +486,14 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
pub fn run<F>(mut self, event_handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(event::Event<T>, &event_loop::EventLoopWindowTarget),
|
||||
F: FnMut(event::Event<T>, &event_loop::ActiveEventLoop),
|
||||
{
|
||||
self.run_on_demand(event_handler)
|
||||
}
|
||||
|
||||
pub fn run_on_demand<F>(&mut self, mut event_handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(event::Event<T>, &event_loop::EventLoopWindowTarget),
|
||||
F: FnMut(event::Event<T>, &event_loop::ActiveEventLoop),
|
||||
{
|
||||
loop {
|
||||
match self.pump_events(None, &mut event_handler) {
|
||||
@@ -512,7 +512,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
pub fn pump_events<F>(&mut self, timeout: Option<Duration>, mut callback: F) -> PumpStatus
|
||||
where
|
||||
F: FnMut(event::Event<T>, &RootELW),
|
||||
F: FnMut(event::Event<T>, &RootAEL),
|
||||
{
|
||||
if !self.loop_running {
|
||||
self.loop_running = true;
|
||||
@@ -545,7 +545,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
fn poll_events_with_timeout<F>(&mut self, mut timeout: Option<Duration>, mut callback: F)
|
||||
where
|
||||
F: FnMut(event::Event<T>, &RootELW),
|
||||
F: FnMut(event::Event<T>, &RootAEL),
|
||||
{
|
||||
let start = Instant::now();
|
||||
|
||||
@@ -621,7 +621,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
});
|
||||
}
|
||||
|
||||
pub fn window_target(&self) -> &event_loop::EventLoopWindowTarget {
|
||||
pub fn window_target(&self) -> &event_loop::ActiveEventLoop {
|
||||
&self.window_target
|
||||
}
|
||||
|
||||
@@ -665,18 +665,25 @@ impl<T> EventLoopProxy<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoopWindowTarget {
|
||||
pub struct ActiveEventLoop {
|
||||
app: AndroidApp,
|
||||
control_flow: Cell<ControlFlow>,
|
||||
exit: Cell<bool>,
|
||||
redraw_requester: RedrawRequester,
|
||||
}
|
||||
|
||||
impl EventLoopWindowTarget {
|
||||
impl ActiveEventLoop {
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
Some(MonitorHandle::new(self.app.clone()))
|
||||
}
|
||||
|
||||
pub fn create_custom_cursor(&self, source: CustomCursorSource) -> CustomCursor {
|
||||
let _ = source.inner;
|
||||
CustomCursor {
|
||||
inner: PlatformCustomCursor,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
let mut v = VecDeque::with_capacity(1);
|
||||
v.push_back(MonitorHandle::new(self.app.clone()));
|
||||
@@ -746,8 +753,38 @@ impl OwnedDisplayHandle {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub(crate) struct WindowId;
|
||||
|
||||
impl WindowId {
|
||||
pub const fn dummy() -> Self {
|
||||
WindowId
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WindowId> for u64 {
|
||||
fn from(_: WindowId) -> Self {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for WindowId {
|
||||
fn from(_: u64) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct DeviceId(i32);
|
||||
|
||||
impl DeviceId {
|
||||
pub const fn dummy() -> Self {
|
||||
DeviceId(0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct PlatformSpecificWindowBuilderAttributes;
|
||||
pub struct PlatformSpecificWindowAttributes;
|
||||
|
||||
pub(crate) struct Window {
|
||||
app: AndroidApp,
|
||||
@@ -756,7 +793,7 @@ pub(crate) struct Window {
|
||||
|
||||
impl Window {
|
||||
pub(crate) fn new(
|
||||
el: &EventLoopWindowTarget,
|
||||
el: &ActiveEventLoop,
|
||||
_window_attrs: window::WindowAttributes,
|
||||
) -> Result<Self, error::OsError> {
|
||||
// FIXME this ignores requested window attributes
|
||||
@@ -776,7 +813,7 @@ impl Window {
|
||||
}
|
||||
|
||||
pub fn id(&self) -> WindowId {
|
||||
WindowId::from(WINDOW_ID)
|
||||
WindowId
|
||||
}
|
||||
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
@@ -977,7 +1014,7 @@ impl Window {
|
||||
if let Some(native_window) = self.app.native_window().as_ref() {
|
||||
native_window.raw_window_handle()
|
||||
} else {
|
||||
log::error!("Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events.");
|
||||
tracing::error!("Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events.");
|
||||
Err(rwh_06::HandleError::Unavailable)
|
||||
}
|
||||
}
|
||||
@@ -1008,7 +1045,7 @@ impl Window {
|
||||
pub fn set_content_protected(&self, _protected: bool) {}
|
||||
|
||||
pub fn has_focus(&self) -> bool {
|
||||
*HAS_FOCUS.read().unwrap()
|
||||
HAS_FOCUS.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn title(&self) -> String {
|
||||
@@ -1028,10 +1065,6 @@ impl Display for OsError {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursor;
|
||||
pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursorBuilder;
|
||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct MonitorHandle {
|
||||
app: AndroidApp,
|
||||
103
src/platform_impl/ios/app_delegate.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
use icrate::Foundation::{MainThreadMarker, NSObject, NSObjectProtocol};
|
||||
use objc2::{declare_class, mutability, ClassType, DeclaredClass};
|
||||
|
||||
use super::app_state::{self, EventWrapper};
|
||||
use super::uikit::{UIApplication, UIWindow};
|
||||
use super::window::WinitUIWindow;
|
||||
use crate::{
|
||||
event::{Event, WindowEvent},
|
||||
window::WindowId as RootWindowId,
|
||||
};
|
||||
|
||||
declare_class!(
|
||||
pub struct AppDelegate;
|
||||
|
||||
unsafe impl ClassType for AppDelegate {
|
||||
type Super = NSObject;
|
||||
type Mutability = mutability::InteriorMutable;
|
||||
const NAME: &'static str = "WinitApplicationDelegate";
|
||||
}
|
||||
|
||||
impl DeclaredClass for AppDelegate {}
|
||||
|
||||
// UIApplicationDelegate protocol
|
||||
unsafe impl AppDelegate {
|
||||
#[method(application:didFinishLaunchingWithOptions:)]
|
||||
fn did_finish_launching(&self, _application: &UIApplication, _: *mut NSObject) -> bool {
|
||||
app_state::did_finish_launching(MainThreadMarker::new().unwrap());
|
||||
true
|
||||
}
|
||||
|
||||
#[method(applicationDidBecomeActive:)]
|
||||
fn did_become_active(&self, _application: &UIApplication) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::Resumed))
|
||||
}
|
||||
|
||||
#[method(applicationWillResignActive:)]
|
||||
fn will_resign_active(&self, _application: &UIApplication) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::Suspended))
|
||||
}
|
||||
|
||||
#[method(applicationWillEnterForeground:)]
|
||||
fn will_enter_foreground(&self, application: &UIApplication) {
|
||||
self.send_occluded_event_for_all_windows(application, false);
|
||||
}
|
||||
|
||||
#[method(applicationDidEnterBackground:)]
|
||||
fn did_enter_background(&self, application: &UIApplication) {
|
||||
self.send_occluded_event_for_all_windows(application, true);
|
||||
}
|
||||
|
||||
#[method(applicationWillTerminate:)]
|
||||
fn will_terminate(&self, application: &UIApplication) {
|
||||
let mut events = Vec::new();
|
||||
for window in application.windows().iter() {
|
||||
if window.is_kind_of::<WinitUIWindow>() {
|
||||
// SAFETY: We just checked that the window is a `winit` window
|
||||
let window = unsafe {
|
||||
let ptr: *const UIWindow = window;
|
||||
let ptr: *const WinitUIWindow = ptr.cast();
|
||||
&*ptr
|
||||
};
|
||||
events.push(EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::Destroyed,
|
||||
}));
|
||||
}
|
||||
}
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_events(mtm, events);
|
||||
app_state::terminated(mtm);
|
||||
}
|
||||
|
||||
#[method(applicationDidReceiveMemoryWarning:)]
|
||||
fn did_receive_memory_warning(&self, _application: &UIApplication) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::MemoryWarning))
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl AppDelegate {
|
||||
fn send_occluded_event_for_all_windows(&self, application: &UIApplication, occluded: bool) {
|
||||
let mut events = Vec::new();
|
||||
for window in application.windows().iter() {
|
||||
if window.is_kind_of::<WinitUIWindow>() {
|
||||
// SAFETY: We just checked that the window is a `winit` window
|
||||
let window = unsafe {
|
||||
let ptr: *const UIWindow = window;
|
||||
let ptr: *const WinitUIWindow = ptr.cast();
|
||||
&*ptr
|
||||
};
|
||||
events.push(EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::Occluded(occluded),
|
||||
}));
|
||||
}
|
||||
}
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_events(mtm, events);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use std::{
|
||||
fmt, mem,
|
||||
os::raw::c_void,
|
||||
ptr,
|
||||
sync::{Arc, Mutex},
|
||||
sync::{Arc, Mutex, OnceLock},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
@@ -22,14 +22,14 @@ use icrate::Foundation::{
|
||||
use objc2::rc::Id;
|
||||
use objc2::runtime::AnyObject;
|
||||
use objc2::{msg_send, sel};
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
use super::uikit::UIView;
|
||||
use super::view::WinitUIWindow;
|
||||
use super::window::WinitUIWindow;
|
||||
use crate::{
|
||||
dpi::PhysicalSize,
|
||||
event::{Event, InnerSizeWriter, StartCause, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoopWindowTarget as RootEventLoopWindowTarget},
|
||||
event_loop::{ActiveEventLoop as RootActiveEventLoop, ControlFlow},
|
||||
window::WindowId as RootWindowId,
|
||||
};
|
||||
|
||||
macro_rules! bug {
|
||||
@@ -49,8 +49,8 @@ pub(crate) struct HandlePendingUserEvents;
|
||||
|
||||
pub(crate) struct EventLoopHandler {
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub(crate) handler: Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootEventLoopWindowTarget)>,
|
||||
pub(crate) event_loop: RootEventLoopWindowTarget,
|
||||
pub(crate) handler: Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop)>,
|
||||
pub(crate) event_loop: RootActiveEventLoop,
|
||||
}
|
||||
|
||||
impl fmt::Debug for EventLoopHandler {
|
||||
@@ -92,14 +92,16 @@ enum UserCallbackTransitionResult<'a> {
|
||||
},
|
||||
}
|
||||
|
||||
fn is_redraw(event: &Event<HandlePendingUserEvents>) -> bool {
|
||||
matches!(
|
||||
event,
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::RedrawRequested,
|
||||
..
|
||||
}
|
||||
)
|
||||
impl Event<HandlePendingUserEvents> {
|
||||
fn is_redraw(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::RedrawRequested,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// this is the state machine for the app lifecycle
|
||||
@@ -548,7 +550,7 @@ pub fn did_finish_launching(mtm: MainThreadMarker) {
|
||||
//
|
||||
// relevant iOS log:
|
||||
// ```
|
||||
// [ApplicationLifecycle] Windows were created before application initialzation
|
||||
// [ApplicationLifecycle] Windows were created before application initialization
|
||||
// completed. This may result in incorrect visual appearance.
|
||||
// ```
|
||||
let screen = window.screen();
|
||||
@@ -619,10 +621,10 @@ pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(
|
||||
for wrapper in events {
|
||||
match wrapper {
|
||||
EventWrapper::StaticEvent(event) => {
|
||||
if !processing_redraws && is_redraw(&event) {
|
||||
log::info!("processing `RedrawRequested` during the main event loop");
|
||||
} else if processing_redraws && !is_redraw(&event) {
|
||||
log::warn!(
|
||||
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
|
||||
);
|
||||
@@ -673,10 +675,10 @@ pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(
|
||||
for wrapper in queued_events {
|
||||
match wrapper {
|
||||
EventWrapper::StaticEvent(event) => {
|
||||
if !processing_redraws && is_redraw(&event) {
|
||||
log::info!("processing `RedrawRequested` during the main event loop");
|
||||
} else if processing_redraws && !is_redraw(&event) {
|
||||
log::warn!(
|
||||
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
|
||||
);
|
||||
@@ -765,7 +767,7 @@ pub fn handle_main_events_cleared(mtm: MainThreadMarker) {
|
||||
.into_iter()
|
||||
.map(|window| {
|
||||
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: window.id(),
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::RedrawRequested,
|
||||
})
|
||||
})
|
||||
@@ -796,7 +798,7 @@ fn handle_hidpi_proxy(handler: &mut EventLoopHandler, event: ScaleFactorChanged)
|
||||
} = event;
|
||||
let new_inner_size = Arc::new(Mutex::new(suggested_size));
|
||||
let event = Event::WindowEvent {
|
||||
window_id: window.id(),
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::ScaleFactorChanged {
|
||||
scale_factor,
|
||||
inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&new_inner_size)),
|
||||
@@ -899,17 +901,17 @@ macro_rules! os_capabilities {
|
||||
os_version: NSOperatingSystemVersion,
|
||||
}
|
||||
|
||||
impl From<NSOperatingSystemVersion> for OSCapabilities {
|
||||
fn from(os_version: NSOperatingSystemVersion) -> OSCapabilities {
|
||||
impl OSCapabilities {
|
||||
fn from_os_version(os_version: NSOperatingSystemVersion) -> Self {
|
||||
$(let $name = meets_requirements(os_version, $major, $minor);)*
|
||||
OSCapabilities { $($name,)* os_version, }
|
||||
Self { $($name,)* os_version, }
|
||||
}
|
||||
}
|
||||
|
||||
impl OSCapabilities {$(
|
||||
$(#[$attr])*
|
||||
pub fn $error_name(&self, extra_msg: &str) {
|
||||
log::warn!(
|
||||
tracing::warn!(
|
||||
concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"),
|
||||
$major, $minor, self.os_version.majorVersion, self.os_version.minorVersion, self.os_version.patchVersion,
|
||||
extra_msg
|
||||
@@ -947,25 +949,29 @@ fn meets_requirements(
|
||||
(version.majorVersion, version.minorVersion) >= (required_major, required_minor)
|
||||
}
|
||||
|
||||
pub fn os_capabilities() -> OSCapabilities {
|
||||
static OS_CAPABILITIES: Lazy<OSCapabilities> = Lazy::new(|| {
|
||||
let version: NSOperatingSystemVersion = unsafe {
|
||||
let process_info = NSProcessInfo::processInfo();
|
||||
let atleast_ios_8: bool = msg_send![
|
||||
&process_info,
|
||||
respondsToSelector: sel!(operatingSystemVersion)
|
||||
];
|
||||
// winit requires atleast iOS 8 because no one has put the time into supporting earlier os versions.
|
||||
// Older iOS versions are increasingly difficult to test. For example, Xcode 11 does not support
|
||||
// debugging on devices with an iOS version of less than 8. Another example, in order to use an iOS
|
||||
// simulator older than iOS 8, you must download an older version of Xcode (<9), and at least Xcode 7
|
||||
// has been tested to not even run on macOS 10.15 - Xcode 8 might?
|
||||
//
|
||||
// The minimum required iOS version is likely to grow in the future.
|
||||
assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater");
|
||||
process_info.operatingSystemVersion()
|
||||
};
|
||||
version.into()
|
||||
});
|
||||
OS_CAPABILITIES.clone()
|
||||
fn get_version() -> NSOperatingSystemVersion {
|
||||
unsafe {
|
||||
let process_info = NSProcessInfo::processInfo();
|
||||
let atleast_ios_8: bool = msg_send![
|
||||
&process_info,
|
||||
respondsToSelector: sel!(operatingSystemVersion)
|
||||
];
|
||||
// winit requires atleast iOS 8 because no one has put the time into supporting earlier os versions.
|
||||
// Older iOS versions are increasingly difficult to test. For example, Xcode 11 does not support
|
||||
// debugging on devices with an iOS version of less than 8. Another example, in order to use an iOS
|
||||
// simulator older than iOS 8, you must download an older version of Xcode (<9), and at least Xcode 7
|
||||
// has been tested to not even run on macOS 10.15 - Xcode 8 might?
|
||||
//
|
||||
// The minimum required iOS version is likely to grow in the future.
|
||||
assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater");
|
||||
process_info.operatingSystemVersion()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn os_capabilities() -> OSCapabilities {
|
||||
// Cache the version lookup for efficiency
|
||||
static OS_CAPABILITIES: OnceLock<OSCapabilities> = OnceLock::new();
|
||||
OS_CAPABILITIES
|
||||
.get_or_init(|| OSCapabilities::from_os_version(get_version()))
|
||||
.clone()
|
||||
}
|
||||
@@ -20,25 +20,33 @@ use crate::{
|
||||
error::EventLoopError,
|
||||
event::Event,
|
||||
event_loop::{
|
||||
ControlFlow, DeviceEvents, EventLoopClosed,
|
||||
EventLoopWindowTarget as RootEventLoopWindowTarget,
|
||||
ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents, EventLoopClosed,
|
||||
},
|
||||
platform::ios::Idiom,
|
||||
platform_impl::platform::app_state::{EventLoopHandler, HandlePendingUserEvents},
|
||||
window::{CustomCursor, CustomCursorSource},
|
||||
};
|
||||
|
||||
use super::{app_state, monitor, view, MonitorHandle};
|
||||
use super::{app_delegate::AppDelegate, uikit::UIUserInterfaceIdiom};
|
||||
use super::{app_state, monitor, MonitorHandle};
|
||||
use super::{
|
||||
app_state::AppState,
|
||||
uikit::{UIApplication, UIApplicationMain, UIDevice, UIScreen},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EventLoopWindowTarget {
|
||||
pub struct ActiveEventLoop {
|
||||
pub(super) mtm: MainThreadMarker,
|
||||
}
|
||||
|
||||
impl EventLoopWindowTarget {
|
||||
impl ActiveEventLoop {
|
||||
pub fn create_custom_cursor(&self, source: CustomCursorSource) -> CustomCursor {
|
||||
let _ = source.inner;
|
||||
CustomCursor {
|
||||
inner: super::PlatformCustomCursor,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
monitor::uiscreens(self.mtm)
|
||||
}
|
||||
@@ -76,8 +84,8 @@ impl EventLoopWindowTarget {
|
||||
|
||||
pub(crate) fn exit(&self) {
|
||||
// https://developer.apple.com/library/archive/qa/qa1561/_index.html
|
||||
// it is not possible to quit an iOS app gracefully and programatically
|
||||
log::warn!("`ControlFlow::Exit` ignored on iOS");
|
||||
// it is not possible to quit an iOS app gracefully and programmatically
|
||||
tracing::warn!("`ControlFlow::Exit` ignored on iOS");
|
||||
}
|
||||
|
||||
pub(crate) fn exiting(&self) -> bool {
|
||||
@@ -109,9 +117,9 @@ impl OwnedDisplayHandle {
|
||||
}
|
||||
|
||||
fn map_user_event<T: 'static>(
|
||||
mut handler: impl FnMut(Event<T>, &RootEventLoopWindowTarget),
|
||||
mut handler: impl FnMut(Event<T>, &RootActiveEventLoop),
|
||||
receiver: mpsc::Receiver<T>,
|
||||
) -> impl FnMut(Event<HandlePendingUserEvents>, &RootEventLoopWindowTarget) {
|
||||
) -> impl FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) {
|
||||
move |event, window_target| match event.map_nonuser_event() {
|
||||
Ok(event) => (handler)(event, window_target),
|
||||
Err(_) => {
|
||||
@@ -126,7 +134,7 @@ pub struct EventLoop<T: 'static> {
|
||||
mtm: MainThreadMarker,
|
||||
sender: Sender<T>,
|
||||
receiver: Receiver<T>,
|
||||
window_target: RootEventLoopWindowTarget,
|
||||
window_target: RootActiveEventLoop,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -158,8 +166,8 @@ impl<T: 'static> EventLoop<T> {
|
||||
mtm,
|
||||
sender,
|
||||
receiver,
|
||||
window_target: RootEventLoopWindowTarget {
|
||||
p: EventLoopWindowTarget { mtm },
|
||||
window_target: RootActiveEventLoop {
|
||||
p: ActiveEventLoop { mtm },
|
||||
_marker: PhantomData,
|
||||
},
|
||||
})
|
||||
@@ -167,22 +175,22 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
pub fn run<F>(self, handler: F) -> !
|
||||
where
|
||||
F: FnMut(Event<T>, &RootEventLoopWindowTarget),
|
||||
F: FnMut(Event<T>, &RootActiveEventLoop),
|
||||
{
|
||||
let application = UIApplication::shared(self.mtm);
|
||||
assert!(
|
||||
application.is_none(),
|
||||
"\
|
||||
`EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\n\
|
||||
Note: `EventLoop::run` calls `UIApplicationMain` on iOS",
|
||||
Note: `EventLoop::run_app` calls `UIApplicationMain` on iOS",
|
||||
);
|
||||
|
||||
let handler = map_user_event(handler, self.receiver);
|
||||
|
||||
let handler = unsafe {
|
||||
std::mem::transmute::<
|
||||
Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootEventLoopWindowTarget)>,
|
||||
Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootEventLoopWindowTarget)>,
|
||||
Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop)>,
|
||||
Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop)>,
|
||||
>(Box::new(handler))
|
||||
};
|
||||
|
||||
@@ -194,14 +202,14 @@ impl<T: 'static> EventLoop<T> {
|
||||
app_state::will_launch(self.mtm, handler);
|
||||
|
||||
// Ensure application delegate is initialized
|
||||
view::WinitApplicationDelegate::class();
|
||||
let _ = AppDelegate::class();
|
||||
|
||||
unsafe {
|
||||
UIApplicationMain(
|
||||
0,
|
||||
ptr::null(),
|
||||
None,
|
||||
Some(&NSString::from_str("WinitApplicationDelegate")),
|
||||
Some(&NSString::from_str(AppDelegate::NAME)),
|
||||
)
|
||||
};
|
||||
unreachable!()
|
||||
@@ -211,7 +219,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
EventLoopProxy::new(self.sender.clone())
|
||||
}
|
||||
|
||||
pub fn window_target(&self) -> &RootEventLoopWindowTarget {
|
||||
pub fn window_target(&self) -> &RootActiveEventLoop {
|
||||
&self.window_target
|
||||
}
|
||||
}
|
||||
@@ -219,7 +227,14 @@ impl<T: 'static> EventLoop<T> {
|
||||
// EventLoopExtIOS
|
||||
impl<T: 'static> EventLoop<T> {
|
||||
pub fn idiom(&self) -> Idiom {
|
||||
UIDevice::current(self.mtm).userInterfaceIdiom().into()
|
||||
match UIDevice::current(self.mtm).userInterfaceIdiom() {
|
||||
UIUserInterfaceIdiom::Unspecified => Idiom::Unspecified,
|
||||
UIUserInterfaceIdiom::Phone => Idiom::Phone,
|
||||
UIUserInterfaceIdiom::Pad => Idiom::Pad,
|
||||
UIUserInterfaceIdiom::TV => Idiom::TV,
|
||||
UIUserInterfaceIdiom::CarPlay => Idiom::CarPlay,
|
||||
_ => Idiom::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,6 +244,7 @@ pub struct EventLoopProxy<T> {
|
||||
}
|
||||
|
||||
unsafe impl<T: Send> Send for EventLoopProxy<T> {}
|
||||
unsafe impl<T: Send> Sync for EventLoopProxy<T> {}
|
||||
|
||||
impl<T> Clone for EventLoopProxy<T> {
|
||||
fn clone(&self) -> EventLoopProxy<T> {
|
||||
55
src/platform_impl/ios/mod.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
#![cfg(ios_platform)]
|
||||
#![allow(clippy::let_unit_value)]
|
||||
|
||||
mod app_delegate;
|
||||
mod app_state;
|
||||
mod event_loop;
|
||||
mod monitor;
|
||||
mod uikit;
|
||||
mod view;
|
||||
mod view_controller;
|
||||
mod window;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::event::DeviceId as RootDeviceId;
|
||||
|
||||
pub(crate) use self::{
|
||||
event_loop::{
|
||||
ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle,
|
||||
PlatformSpecificEventLoopAttributes,
|
||||
},
|
||||
monitor::{MonitorHandle, VideoModeHandle},
|
||||
window::{PlatformSpecificWindowAttributes, Window, WindowId},
|
||||
};
|
||||
pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursor;
|
||||
pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursorSource;
|
||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||
pub(crate) use crate::platform_impl::Fullscreen;
|
||||
|
||||
/// There is no way to detect which device that performed a certain event in
|
||||
/// UIKit (i.e. you can't differentiate between different external keyboards,
|
||||
/// or whether it was the main touchscreen, assistive technologies, or some
|
||||
/// other pointer device that caused a touch event).
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId;
|
||||
|
||||
impl DeviceId {
|
||||
pub const unsafe fn dummy() -> Self {
|
||||
DeviceId
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct KeyEventExtra {}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum OsError {}
|
||||
|
||||
impl fmt::Display for OsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "os error")
|
||||
}
|
||||
}
|
||||
41
src/platform_impl/ios/uikit/device.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use icrate::Foundation::{MainThreadMarker, NSInteger, NSObject};
|
||||
use objc2::encode::{Encode, Encoding};
|
||||
use objc2::rc::Id;
|
||||
use objc2::{extern_class, extern_methods, msg_send_id, mutability, ClassType};
|
||||
|
||||
extern_class!(
|
||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct UIDevice;
|
||||
|
||||
unsafe impl ClassType for UIDevice {
|
||||
type Super = NSObject;
|
||||
type Mutability = mutability::InteriorMutable;
|
||||
}
|
||||
);
|
||||
|
||||
extern_methods!(
|
||||
unsafe impl UIDevice {
|
||||
pub fn current(_mtm: MainThreadMarker) -> Id<Self> {
|
||||
unsafe { msg_send_id![Self::class(), currentDevice] }
|
||||
}
|
||||
|
||||
#[method(userInterfaceIdiom)]
|
||||
pub fn userInterfaceIdiom(&self) -> UIUserInterfaceIdiom;
|
||||
}
|
||||
);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct UIUserInterfaceIdiom(NSInteger);
|
||||
|
||||
unsafe impl Encode for UIUserInterfaceIdiom {
|
||||
const ENCODING: Encoding = NSInteger::ENCODING;
|
||||
}
|
||||
|
||||
impl UIUserInterfaceIdiom {
|
||||
pub const Unspecified: UIUserInterfaceIdiom = UIUserInterfaceIdiom(-1);
|
||||
pub const Phone: UIUserInterfaceIdiom = UIUserInterfaceIdiom(0);
|
||||
pub const Pad: UIUserInterfaceIdiom = UIUserInterfaceIdiom(1);
|
||||
pub const TV: UIUserInterfaceIdiom = UIUserInterfaceIdiom(2);
|
||||
pub const CarPlay: UIUserInterfaceIdiom = UIUserInterfaceIdiom(3);
|
||||
}
|
||||
14
src/platform_impl/ios/uikit/geometry.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use icrate::Foundation::NSUInteger;
|
||||
use objc2::encode::{Encode, Encoding};
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct UIRectEdge(pub NSUInteger);
|
||||
|
||||
impl UIRectEdge {
|
||||
pub const NONE: Self = Self(0);
|
||||
}
|
||||
|
||||
unsafe impl Encode for UIRectEdge {
|
||||
const ENCODING: Encoding = NSUInteger::ENCODING;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ mod application;
|
||||
mod coordinate_space;
|
||||
mod device;
|
||||
mod event;
|
||||
mod geometry;
|
||||
mod gesture_recognizer;
|
||||
mod responder;
|
||||
mod screen;
|
||||
@@ -22,8 +23,9 @@ mod window;
|
||||
|
||||
pub(crate) use self::application::UIApplication;
|
||||
pub(crate) use self::coordinate_space::UICoordinateSpace;
|
||||
pub(crate) use self::device::UIDevice;
|
||||
pub(crate) use self::device::{UIDevice, UIUserInterfaceIdiom};
|
||||
pub(crate) use self::event::UIEvent;
|
||||
pub(crate) use self::geometry::UIRectEdge;
|
||||
pub(crate) use self::gesture_recognizer::{
|
||||
UIGestureRecognizer, UIGestureRecognizerState, UIPinchGestureRecognizer,
|
||||
UIRotationGestureRecognizer, UITapGestureRecognizer,
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::platform::ios::StatusBarStyle;
|
||||
use icrate::Foundation::NSInteger;
|
||||
use objc2::encode::{Encode, Encoding};
|
||||
|
||||
@@ -12,16 +11,6 @@ pub enum UIStatusBarStyle {
|
||||
DarkContent = 3,
|
||||
}
|
||||
|
||||
impl From<StatusBarStyle> for UIStatusBarStyle {
|
||||
fn from(value: StatusBarStyle) -> Self {
|
||||
match value {
|
||||
StatusBarStyle::Default => Self::Default,
|
||||
StatusBarStyle::LightContent => Self::LightContent,
|
||||
StatusBarStyle::DarkContent => Self::DarkContent,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Encode for UIStatusBarStyle {
|
||||
const ENCODING: Encoding = NSInteger::ENCODING;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#![allow(clippy::unnecessary_cast)]
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::cell::RefCell;
|
||||
|
||||
use icrate::Foundation::{CGFloat, CGRect, MainThreadMarker, NSObject, NSObjectProtocol, NSSet};
|
||||
use icrate::Foundation::{CGFloat, CGRect, MainThreadMarker, NSObject, NSSet};
|
||||
use objc2::rc::Id;
|
||||
use objc2::runtime::AnyClass;
|
||||
use objc2::{
|
||||
@@ -10,20 +10,16 @@ use objc2::{
|
||||
|
||||
use super::app_state::{self, EventWrapper};
|
||||
use super::uikit::{
|
||||
UIApplication, UIDevice, UIEvent, UIForceTouchCapability, UIGestureRecognizerState,
|
||||
UIInterfaceOrientationMask, UIPinchGestureRecognizer, UIResponder, UIRotationGestureRecognizer,
|
||||
UIStatusBarStyle, UITapGestureRecognizer, UITouch, UITouchPhase, UITouchType,
|
||||
UITraitCollection, UIView, UIViewController, UIWindow,
|
||||
UIEvent, UIForceTouchCapability, UIGestureRecognizerState, UIPinchGestureRecognizer,
|
||||
UIResponder, UIRotationGestureRecognizer, UITapGestureRecognizer, UITouch, UITouchPhase,
|
||||
UITouchType, UITraitCollection, UIView,
|
||||
};
|
||||
use super::window::WinitUIWindow;
|
||||
use crate::{
|
||||
dpi::PhysicalPosition,
|
||||
event::{Event, Force, Touch, TouchPhase, WindowEvent},
|
||||
platform::ios::ValidOrientations,
|
||||
platform_impl::platform::{
|
||||
ffi::{UIRectEdge, UIUserInterfaceIdiom},
|
||||
Fullscreen, DEVICE_ID,
|
||||
},
|
||||
window::{WindowAttributes, WindowId},
|
||||
platform_impl::platform::DEVICE_ID,
|
||||
window::{WindowAttributes, WindowId as RootWindowId},
|
||||
};
|
||||
|
||||
pub struct WinitViewState {
|
||||
@@ -54,7 +50,7 @@ declare_class!(
|
||||
app_state::handle_nonuser_event(
|
||||
mtm,
|
||||
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: window.id(),
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::RedrawRequested,
|
||||
}),
|
||||
);
|
||||
@@ -89,7 +85,7 @@ declare_class!(
|
||||
app_state::handle_nonuser_event(
|
||||
mtm,
|
||||
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: window.id(),
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::Resized(size),
|
||||
}),
|
||||
);
|
||||
@@ -128,7 +124,7 @@ declare_class!(
|
||||
width: screen_frame.size.width as f64,
|
||||
height: screen_frame.size.height as f64,
|
||||
};
|
||||
let window_id = window.id();
|
||||
let window_id = RootWindowId(window.id());
|
||||
app_state::handle_nonuser_events(
|
||||
mtm,
|
||||
std::iter::once(EventWrapper::ScaleFactorChanged(
|
||||
@@ -182,7 +178,7 @@ declare_class!(
|
||||
};
|
||||
|
||||
let gesture_event = EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: window.id(),
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::PinchGesture {
|
||||
device_id: DEVICE_ID,
|
||||
delta: recognizer.velocity() as _,
|
||||
@@ -200,7 +196,7 @@ declare_class!(
|
||||
|
||||
if recognizer.state() == UIGestureRecognizerState::Ended {
|
||||
let gesture_event = EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: window.id(),
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::DoubleTapGesture {
|
||||
device_id: DEVICE_ID,
|
||||
},
|
||||
@@ -228,7 +224,7 @@ declare_class!(
|
||||
// Flip the velocity to match macOS.
|
||||
let delta = -recognizer.velocity() as _;
|
||||
let gesture_event = EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: window.id(),
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::RotationGesture {
|
||||
device_id: DEVICE_ID,
|
||||
delta,
|
||||
@@ -379,7 +375,7 @@ impl WinitView {
|
||||
)
|
||||
};
|
||||
touch_events.push(EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: window.id(),
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::Touch(Touch {
|
||||
device_id: DEVICE_ID,
|
||||
id: touch_id,
|
||||
@@ -393,339 +389,3 @@ impl WinitView {
|
||||
app_state::handle_nonuser_events(mtm, touch_events);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ViewControllerState {
|
||||
prefers_status_bar_hidden: Cell<bool>,
|
||||
preferred_status_bar_style: Cell<UIStatusBarStyle>,
|
||||
prefers_home_indicator_auto_hidden: Cell<bool>,
|
||||
supported_orientations: Cell<UIInterfaceOrientationMask>,
|
||||
preferred_screen_edges_deferring_system_gestures: Cell<UIRectEdge>,
|
||||
}
|
||||
|
||||
declare_class!(
|
||||
pub(crate) struct WinitViewController;
|
||||
|
||||
unsafe impl ClassType for WinitViewController {
|
||||
#[inherits(UIResponder, NSObject)]
|
||||
type Super = UIViewController;
|
||||
type Mutability = mutability::InteriorMutable;
|
||||
const NAME: &'static str = "WinitUIViewController";
|
||||
}
|
||||
|
||||
impl DeclaredClass for WinitViewController {
|
||||
type Ivars = ViewControllerState;
|
||||
}
|
||||
|
||||
unsafe impl WinitViewController {
|
||||
#[method(shouldAutorotate)]
|
||||
fn should_autorotate(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[method(prefersStatusBarHidden)]
|
||||
fn prefers_status_bar_hidden(&self) -> bool {
|
||||
self.ivars().prefers_status_bar_hidden.get()
|
||||
}
|
||||
|
||||
#[method(preferredStatusBarStyle)]
|
||||
fn preferred_status_bar_style(&self) -> UIStatusBarStyle {
|
||||
self.ivars().preferred_status_bar_style.get()
|
||||
}
|
||||
|
||||
#[method(prefersHomeIndicatorAutoHidden)]
|
||||
fn prefers_home_indicator_auto_hidden(&self) -> bool {
|
||||
self.ivars().prefers_home_indicator_auto_hidden.get()
|
||||
}
|
||||
|
||||
#[method(supportedInterfaceOrientations)]
|
||||
fn supported_orientations(&self) -> UIInterfaceOrientationMask {
|
||||
self.ivars().supported_orientations.get()
|
||||
}
|
||||
|
||||
#[method(preferredScreenEdgesDeferringSystemGestures)]
|
||||
fn preferred_screen_edges_deferring_system_gestures(&self) -> UIRectEdge {
|
||||
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: UIStatusBarStyle) {
|
||||
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);
|
||||
let os_capabilities = app_state::os_capabilities();
|
||||
if os_capabilities.home_indicator_hidden {
|
||||
self.setNeedsUpdateOfHomeIndicatorAutoHidden();
|
||||
} else {
|
||||
os_capabilities.home_indicator_hidden_err_msg("ignoring")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_preferred_screen_edges_deferring_system_gestures(&self, val: UIRectEdge) {
|
||||
self.ivars()
|
||||
.preferred_screen_edges_deferring_system_gestures
|
||||
.set(val);
|
||||
let os_capabilities = app_state::os_capabilities();
|
||||
if os_capabilities.defer_system_gestures {
|
||||
self.setNeedsUpdateOfScreenEdgesDeferringSystemGestures();
|
||||
} else {
|
||||
os_capabilities.defer_system_gestures_err_msg("ignoring")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_supported_interface_orientations(
|
||||
&self,
|
||||
mtm: MainThreadMarker,
|
||||
valid_orientations: ValidOrientations,
|
||||
) {
|
||||
let mask = match (
|
||||
valid_orientations,
|
||||
UIDevice::current(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);
|
||||
UIViewController::attemptRotationToDeviceOrientation();
|
||||
}
|
||||
|
||||
pub(crate) fn new(
|
||||
mtm: MainThreadMarker,
|
||||
window_attributes: &WindowAttributes,
|
||||
view: &UIView,
|
||||
) -> Id<Self> {
|
||||
// These are set properly below, we just to set them to something in the meantime.
|
||||
let this = Self::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::NONE),
|
||||
});
|
||||
let this: Id<Self> = unsafe { msg_send_id![super(this), init] };
|
||||
|
||||
this.set_prefers_status_bar_hidden(
|
||||
window_attributes
|
||||
.platform_specific
|
||||
.prefers_status_bar_hidden,
|
||||
);
|
||||
|
||||
this.set_preferred_status_bar_style(
|
||||
window_attributes
|
||||
.platform_specific
|
||||
.preferred_status_bar_style
|
||||
.into(),
|
||||
);
|
||||
|
||||
this.set_supported_interface_orientations(
|
||||
mtm,
|
||||
window_attributes.platform_specific.valid_orientations,
|
||||
);
|
||||
|
||||
this.set_prefers_home_indicator_auto_hidden(
|
||||
window_attributes
|
||||
.platform_specific
|
||||
.prefers_home_indicator_hidden,
|
||||
);
|
||||
|
||||
this.set_preferred_screen_edges_deferring_system_gestures(
|
||||
window_attributes
|
||||
.platform_specific
|
||||
.preferred_screen_edges_deferring_system_gestures
|
||||
.into(),
|
||||
);
|
||||
|
||||
this.setView(Some(view));
|
||||
|
||||
this
|
||||
}
|
||||
}
|
||||
|
||||
declare_class!(
|
||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct WinitUIWindow;
|
||||
|
||||
unsafe impl ClassType for WinitUIWindow {
|
||||
#[inherits(UIResponder, NSObject)]
|
||||
type Super = UIWindow;
|
||||
type Mutability = mutability::InteriorMutable;
|
||||
const NAME: &'static str = "WinitUIWindow";
|
||||
}
|
||||
|
||||
impl DeclaredClass for WinitUIWindow {}
|
||||
|
||||
unsafe impl WinitUIWindow {
|
||||
#[method(becomeKeyWindow)]
|
||||
fn become_key_window(&self) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(
|
||||
mtm,
|
||||
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: self.id(),
|
||||
event: WindowEvent::Focused(true),
|
||||
}),
|
||||
);
|
||||
let _: () = unsafe { msg_send![super(self), becomeKeyWindow] };
|
||||
}
|
||||
|
||||
#[method(resignKeyWindow)]
|
||||
fn resign_key_window(&self) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(
|
||||
mtm,
|
||||
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
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,
|
||||
) -> Id<Self> {
|
||||
let this: Id<Self> = unsafe { msg_send_id![Self::alloc(), initWithFrame: frame] };
|
||||
|
||||
this.setRootViewController(Some(view_controller));
|
||||
|
||||
match window_attributes.fullscreen.clone().map(Into::into) {
|
||||
Some(Fullscreen::Exclusive(ref video_mode)) => {
|
||||
let monitor = video_mode.monitor();
|
||||
let screen = monitor.ui_screen(mtm);
|
||||
screen.setCurrentMode(Some(video_mode.screen_mode(mtm)));
|
||||
this.setScreen(screen);
|
||||
}
|
||||
Some(Fullscreen::Borderless(Some(ref monitor))) => {
|
||||
let screen = monitor.ui_screen(mtm);
|
||||
this.setScreen(screen);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
this
|
||||
}
|
||||
|
||||
pub(crate) fn id(&self) -> WindowId {
|
||||
(self as *const Self as usize as u64).into()
|
||||
}
|
||||
}
|
||||
|
||||
declare_class!(
|
||||
pub struct WinitApplicationDelegate;
|
||||
|
||||
unsafe impl ClassType for WinitApplicationDelegate {
|
||||
type Super = NSObject;
|
||||
type Mutability = mutability::InteriorMutable;
|
||||
const NAME: &'static str = "WinitApplicationDelegate";
|
||||
}
|
||||
|
||||
impl DeclaredClass for WinitApplicationDelegate {}
|
||||
|
||||
// UIApplicationDelegate protocol
|
||||
unsafe impl WinitApplicationDelegate {
|
||||
#[method(application:didFinishLaunchingWithOptions:)]
|
||||
fn did_finish_launching(&self, _application: &UIApplication, _: *mut NSObject) -> bool {
|
||||
app_state::did_finish_launching(MainThreadMarker::new().unwrap());
|
||||
true
|
||||
}
|
||||
|
||||
#[method(applicationDidBecomeActive:)]
|
||||
fn did_become_active(&self, _application: &UIApplication) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::Resumed))
|
||||
}
|
||||
|
||||
#[method(applicationWillResignActive:)]
|
||||
fn will_resign_active(&self, _application: &UIApplication) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::Suspended))
|
||||
}
|
||||
|
||||
#[method(applicationWillEnterForeground:)]
|
||||
fn will_enter_foreground(&self, application: &UIApplication) {
|
||||
self.send_occluded_event_for_all_windows(application, false);
|
||||
}
|
||||
|
||||
#[method(applicationDidEnterBackground:)]
|
||||
fn did_enter_background(&self, application: &UIApplication) {
|
||||
self.send_occluded_event_for_all_windows(application, true);
|
||||
}
|
||||
|
||||
#[method(applicationWillTerminate:)]
|
||||
fn will_terminate(&self, application: &UIApplication) {
|
||||
let mut events = Vec::new();
|
||||
for window in application.windows().iter() {
|
||||
if window.is_kind_of::<WinitUIWindow>() {
|
||||
// SAFETY: We just checked that the window is a `winit` window
|
||||
let window = unsafe {
|
||||
let ptr: *const UIWindow = window;
|
||||
let ptr: *const WinitUIWindow = ptr.cast();
|
||||
&*ptr
|
||||
};
|
||||
events.push(EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: window.id(),
|
||||
event: WindowEvent::Destroyed,
|
||||
}));
|
||||
}
|
||||
}
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_events(mtm, events);
|
||||
app_state::terminated(mtm);
|
||||
}
|
||||
|
||||
#[method(applicationDidReceiveMemoryWarning:)]
|
||||
fn did_receive_memory_warning(&self, _application: &UIApplication) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::MemoryWarning))
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl WinitApplicationDelegate {
|
||||
fn send_occluded_event_for_all_windows(&self, application: &UIApplication, occluded: bool) {
|
||||
let mut events = Vec::new();
|
||||
for window in application.windows().iter() {
|
||||
if window.is_kind_of::<WinitUIWindow>() {
|
||||
// SAFETY: We just checked that the window is a `winit` window
|
||||
let window = unsafe {
|
||||
let ptr: *const UIWindow = window;
|
||||
let ptr: *const WinitUIWindow = ptr.cast();
|
||||
&*ptr
|
||||
};
|
||||
events.push(EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: window.id(),
|
||||
event: WindowEvent::Occluded(occluded),
|
||||
}));
|
||||
}
|
||||
}
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_events(mtm, events);
|
||||
}
|
||||
}
|
||||
192
src/platform_impl/ios/view_controller.rs
Normal file
@@ -0,0 +1,192 @@
|
||||
use std::cell::Cell;
|
||||
|
||||
use icrate::Foundation::{MainThreadMarker, NSObject};
|
||||
use objc2::rc::Id;
|
||||
use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass};
|
||||
|
||||
use super::app_state::{self};
|
||||
use super::uikit::{
|
||||
UIDevice, UIInterfaceOrientationMask, UIRectEdge, UIResponder, UIStatusBarStyle,
|
||||
UIUserInterfaceIdiom, UIView, UIViewController,
|
||||
};
|
||||
use crate::platform::ios::{ScreenEdge, StatusBarStyle};
|
||||
use crate::{platform::ios::ValidOrientations, window::WindowAttributes};
|
||||
|
||||
pub struct ViewControllerState {
|
||||
prefers_status_bar_hidden: Cell<bool>,
|
||||
preferred_status_bar_style: Cell<UIStatusBarStyle>,
|
||||
prefers_home_indicator_auto_hidden: Cell<bool>,
|
||||
supported_orientations: Cell<UIInterfaceOrientationMask>,
|
||||
preferred_screen_edges_deferring_system_gestures: Cell<UIRectEdge>,
|
||||
}
|
||||
|
||||
declare_class!(
|
||||
pub(crate) struct WinitViewController;
|
||||
|
||||
unsafe impl ClassType for WinitViewController {
|
||||
#[inherits(UIResponder, NSObject)]
|
||||
type Super = UIViewController;
|
||||
type Mutability = mutability::InteriorMutable;
|
||||
const NAME: &'static str = "WinitUIViewController";
|
||||
}
|
||||
|
||||
impl DeclaredClass for WinitViewController {
|
||||
type Ivars = ViewControllerState;
|
||||
}
|
||||
|
||||
unsafe impl WinitViewController {
|
||||
#[method(shouldAutorotate)]
|
||||
fn should_autorotate(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[method(prefersStatusBarHidden)]
|
||||
fn prefers_status_bar_hidden(&self) -> bool {
|
||||
self.ivars().prefers_status_bar_hidden.get()
|
||||
}
|
||||
|
||||
#[method(preferredStatusBarStyle)]
|
||||
fn preferred_status_bar_style(&self) -> UIStatusBarStyle {
|
||||
self.ivars().preferred_status_bar_style.get()
|
||||
}
|
||||
|
||||
#[method(prefersHomeIndicatorAutoHidden)]
|
||||
fn prefers_home_indicator_auto_hidden(&self) -> bool {
|
||||
self.ivars().prefers_home_indicator_auto_hidden.get()
|
||||
}
|
||||
|
||||
#[method(supportedInterfaceOrientations)]
|
||||
fn supported_orientations(&self) -> UIInterfaceOrientationMask {
|
||||
self.ivars().supported_orientations.get()
|
||||
}
|
||||
|
||||
#[method(preferredScreenEdgesDeferringSystemGestures)]
|
||||
fn preferred_screen_edges_deferring_system_gestures(&self) -> UIRectEdge {
|
||||
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);
|
||||
let os_capabilities = app_state::os_capabilities();
|
||||
if os_capabilities.home_indicator_hidden {
|
||||
self.setNeedsUpdateOfHomeIndicatorAutoHidden();
|
||||
} else {
|
||||
os_capabilities.home_indicator_hidden_err_msg("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);
|
||||
let os_capabilities = app_state::os_capabilities();
|
||||
if os_capabilities.defer_system_gestures {
|
||||
self.setNeedsUpdateOfScreenEdgesDeferringSystemGestures();
|
||||
} else {
|
||||
os_capabilities.defer_system_gestures_err_msg("ignoring")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_supported_interface_orientations(
|
||||
&self,
|
||||
mtm: MainThreadMarker,
|
||||
valid_orientations: ValidOrientations,
|
||||
) {
|
||||
let mask = match (
|
||||
valid_orientations,
|
||||
UIDevice::current(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);
|
||||
UIViewController::attemptRotationToDeviceOrientation();
|
||||
}
|
||||
|
||||
pub(crate) fn new(
|
||||
mtm: MainThreadMarker,
|
||||
window_attributes: &WindowAttributes,
|
||||
view: &UIView,
|
||||
) -> Id<Self> {
|
||||
// These are set properly below, we just to set them to something in the meantime.
|
||||
let this = Self::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::NONE),
|
||||
});
|
||||
let this: Id<Self> = unsafe { msg_send_id![super(this), init] };
|
||||
|
||||
this.set_prefers_status_bar_hidden(
|
||||
window_attributes
|
||||
.platform_specific
|
||||
.prefers_status_bar_hidden,
|
||||
);
|
||||
|
||||
this.set_preferred_status_bar_style(
|
||||
window_attributes
|
||||
.platform_specific
|
||||
.preferred_status_bar_style,
|
||||
);
|
||||
|
||||
this.set_supported_interface_orientations(
|
||||
mtm,
|
||||
window_attributes.platform_specific.valid_orientations,
|
||||
);
|
||||
|
||||
this.set_prefers_home_indicator_auto_hidden(
|
||||
window_attributes
|
||||
.platform_specific
|
||||
.prefers_home_indicator_hidden,
|
||||
);
|
||||
|
||||
this.set_preferred_screen_edges_deferring_system_gestures(
|
||||
window_attributes
|
||||
.platform_specific
|
||||
.preferred_screen_edges_deferring_system_gestures,
|
||||
);
|
||||
|
||||
this.setView(Some(view));
|
||||
|
||||
this
|
||||
}
|
||||
}
|
||||
@@ -3,29 +3,106 @@
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use icrate::Foundation::{CGFloat, CGPoint, CGRect, CGSize, MainThreadBound, MainThreadMarker};
|
||||
use log::{debug, warn};
|
||||
use objc2::rc::Id;
|
||||
use objc2::{class, msg_send};
|
||||
use objc2::runtime::{AnyObject, NSObject};
|
||||
use objc2::{class, declare_class, msg_send, msg_send_id, mutability, ClassType, DeclaredClass};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use super::app_state::EventWrapper;
|
||||
use super::uikit::{UIApplication, UIScreen, UIScreenOverscanCompensation};
|
||||
use super::view::{WinitUIWindow, WinitView, WinitViewController};
|
||||
use super::uikit::{
|
||||
UIApplication, UIResponder, UIScreen, UIScreenOverscanCompensation, UIViewController, UIWindow,
|
||||
};
|
||||
use super::view::WinitView;
|
||||
use super::view_controller::WinitViewController;
|
||||
use crate::{
|
||||
cursor::Cursor,
|
||||
dpi::{self, LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size},
|
||||
dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size},
|
||||
error::{ExternalError, NotSupportedError, OsError as RootOsError},
|
||||
event::{Event, WindowEvent},
|
||||
icon::Icon,
|
||||
platform::ios::{ScreenEdge, StatusBarStyle, ValidOrientations},
|
||||
platform_impl::platform::{
|
||||
app_state, monitor, EventLoopWindowTarget, Fullscreen, MonitorHandle,
|
||||
},
|
||||
platform_impl::platform::{app_state, monitor, ActiveEventLoop, Fullscreen, MonitorHandle},
|
||||
window::{
|
||||
CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes,
|
||||
WindowButtons, WindowId, WindowLevel,
|
||||
WindowButtons, WindowId as RootWindowId, WindowLevel,
|
||||
},
|
||||
};
|
||||
|
||||
declare_class!(
|
||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct WinitUIWindow;
|
||||
|
||||
unsafe impl ClassType for WinitUIWindow {
|
||||
#[inherits(UIResponder, NSObject)]
|
||||
type Super = UIWindow;
|
||||
type Mutability = mutability::InteriorMutable;
|
||||
const NAME: &'static str = "WinitUIWindow";
|
||||
}
|
||||
|
||||
impl DeclaredClass for WinitUIWindow {}
|
||||
|
||||
unsafe impl WinitUIWindow {
|
||||
#[method(becomeKeyWindow)]
|
||||
fn become_key_window(&self) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(
|
||||
mtm,
|
||||
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(self.id()),
|
||||
event: WindowEvent::Focused(true),
|
||||
}),
|
||||
);
|
||||
let _: () = unsafe { msg_send![super(self), becomeKeyWindow] };
|
||||
}
|
||||
|
||||
#[method(resignKeyWindow)]
|
||||
fn resign_key_window(&self) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(
|
||||
mtm,
|
||||
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(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,
|
||||
) -> Id<Self> {
|
||||
let this: Id<Self> = unsafe { msg_send_id![Self::alloc(), initWithFrame: frame] };
|
||||
|
||||
this.setRootViewController(Some(view_controller));
|
||||
|
||||
match window_attributes.fullscreen.clone().map(Into::into) {
|
||||
Some(Fullscreen::Exclusive(ref video_mode)) => {
|
||||
let monitor = video_mode.monitor();
|
||||
let screen = monitor.ui_screen(mtm);
|
||||
screen.setCurrentMode(Some(video_mode.screen_mode(mtm)));
|
||||
this.setScreen(screen);
|
||||
}
|
||||
Some(Fullscreen::Borderless(Some(ref monitor))) => {
|
||||
let screen = monitor.ui_screen(mtm);
|
||||
this.setScreen(screen);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
this
|
||||
}
|
||||
|
||||
pub(crate) fn id(&self) -> WindowId {
|
||||
(self as *const Self as usize as u64).into()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Inner {
|
||||
window: Id<WinitUIWindow>,
|
||||
view_controller: Id<WinitViewController>,
|
||||
@@ -398,7 +475,7 @@ pub struct Window {
|
||||
|
||||
impl Window {
|
||||
pub(crate) fn new(
|
||||
event_loop: &EventLoopWindowTarget,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_attributes: WindowAttributes,
|
||||
) -> Result<Window, RootOsError> {
|
||||
let mtm = event_loop.mtm;
|
||||
@@ -460,11 +537,11 @@ impl Window {
|
||||
let screen = window.screen();
|
||||
let screen_space = screen.coordinateSpace();
|
||||
let screen_frame = view.convertRect_toCoordinateSpace(bounds, &screen_space);
|
||||
let size = crate::dpi::LogicalSize {
|
||||
let size = LogicalSize {
|
||||
width: screen_frame.size.width as f64,
|
||||
height: screen_frame.size.height as f64,
|
||||
};
|
||||
let window_id = window.id();
|
||||
let window_id = RootWindowId(window.id());
|
||||
app_state::handle_nonuser_events(
|
||||
mtm,
|
||||
std::iter::once(EventWrapper::ScaleFactorChanged(
|
||||
@@ -551,7 +628,7 @@ impl Inner {
|
||||
|
||||
pub fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) {
|
||||
self.view_controller
|
||||
.set_preferred_screen_edges_deferring_system_gestures(edges.into());
|
||||
.set_preferred_screen_edges_deferring_system_gestures(edges);
|
||||
}
|
||||
|
||||
pub fn set_prefers_status_bar_hidden(&self, hidden: bool) {
|
||||
@@ -560,7 +637,7 @@ impl Inner {
|
||||
|
||||
pub fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) {
|
||||
self.view_controller
|
||||
.set_preferred_status_bar_style(status_bar_style.into());
|
||||
.set_preferred_status_bar_style(status_bar_style);
|
||||
}
|
||||
|
||||
pub fn recognize_pinch_gesture(&self, should_recognize: bool) {
|
||||
@@ -612,7 +689,7 @@ impl Inner {
|
||||
let screen_frame = self.rect_to_screen_space(bounds);
|
||||
let status_bar_frame = {
|
||||
let app = UIApplication::shared(MainThreadMarker::new().unwrap()).expect(
|
||||
"`Window::get_inner_position` cannot be called before `EventLoop::run` on iOS",
|
||||
"`Window::get_inner_position` cannot be called before `EventLoop::run_app` on iOS",
|
||||
);
|
||||
app.statusBarFrame()
|
||||
};
|
||||
@@ -638,8 +715,46 @@ impl Inner {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct WindowId {
|
||||
window: *mut WinitUIWindow,
|
||||
}
|
||||
|
||||
impl WindowId {
|
||||
pub const unsafe fn dummy() -> Self {
|
||||
WindowId {
|
||||
window: std::ptr::null_mut(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WindowId> for u64 {
|
||||
fn from(window_id: WindowId) -> Self {
|
||||
window_id.window as u64
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for WindowId {
|
||||
fn from(raw_id: u64) -> Self {
|
||||
Self {
|
||||
window: raw_id as _,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for WindowId {}
|
||||
unsafe impl Sync for WindowId {}
|
||||
|
||||
impl From<&AnyObject> for WindowId {
|
||||
fn from(window: &AnyObject) -> WindowId {
|
||||
WindowId {
|
||||
window: window as *const _ as _,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PlatformSpecificWindowBuilderAttributes {
|
||||
pub struct PlatformSpecificWindowAttributes {
|
||||
pub scale_factor: Option<f64>,
|
||||
pub valid_orientations: ValidOrientations,
|
||||
pub prefers_home_indicator_hidden: bool,
|
||||
1
src/platform_impl/linux/common/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod xkb;
|
||||
124
src/platform_impl/linux/common/xkb/compose.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
//! XKB compose handling.
|
||||
|
||||
use std::env;
|
||||
use std::ffi::CString;
|
||||
use std::ops::Deref;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use super::XkbContext;
|
||||
use super::XKBCH;
|
||||
use smol_str::SmolStr;
|
||||
use xkbcommon_dl::{
|
||||
xkb_compose_compile_flags, xkb_compose_feed_result, xkb_compose_state, xkb_compose_state_flags,
|
||||
xkb_compose_status, xkb_compose_table, xkb_keysym_t,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbComposeTable {
|
||||
table: NonNull<xkb_compose_table>,
|
||||
}
|
||||
|
||||
impl XkbComposeTable {
|
||||
pub fn new(context: &XkbContext) -> Option<Self> {
|
||||
let locale = env::var_os("LC_ALL")
|
||||
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||
.or_else(|| env::var_os("LC_CTYPE"))
|
||||
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||
.or_else(|| env::var_os("LANG"))
|
||||
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||
.unwrap_or_else(|| "C".into());
|
||||
let locale = CString::new(locale.into_vec()).unwrap();
|
||||
|
||||
let table = unsafe {
|
||||
(XKBCH.xkb_compose_table_new_from_locale)(
|
||||
context.as_ptr(),
|
||||
locale.as_ptr(),
|
||||
xkb_compose_compile_flags::XKB_COMPOSE_COMPILE_NO_FLAGS,
|
||||
)
|
||||
};
|
||||
|
||||
let table = NonNull::new(table)?;
|
||||
Some(Self { table })
|
||||
}
|
||||
|
||||
/// Create new state with the given compose table.
|
||||
pub fn new_state(&self) -> Option<XkbComposeState> {
|
||||
let state = unsafe {
|
||||
(XKBCH.xkb_compose_state_new)(
|
||||
self.table.as_ptr(),
|
||||
xkb_compose_state_flags::XKB_COMPOSE_STATE_NO_FLAGS,
|
||||
)
|
||||
};
|
||||
|
||||
let state = NonNull::new(state)?;
|
||||
Some(XkbComposeState { state })
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for XkbComposeTable {
|
||||
type Target = NonNull<xkb_compose_table>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.table
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbComposeTable {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(XKBCH.xkb_compose_table_unref)(self.table.as_ptr());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbComposeState {
|
||||
state: NonNull<xkb_compose_state>,
|
||||
}
|
||||
|
||||
impl XkbComposeState {
|
||||
pub fn get_string(&mut self, scratch_buffer: &mut Vec<u8>) -> Option<SmolStr> {
|
||||
super::make_string_with(scratch_buffer, |ptr, len| unsafe {
|
||||
(XKBCH.xkb_compose_state_get_utf8)(self.state.as_ptr(), ptr, len)
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn feed(&mut self, keysym: xkb_keysym_t) -> ComposeStatus {
|
||||
let feed_result = unsafe { (XKBCH.xkb_compose_state_feed)(self.state.as_ptr(), keysym) };
|
||||
match feed_result {
|
||||
xkb_compose_feed_result::XKB_COMPOSE_FEED_IGNORED => ComposeStatus::Ignored,
|
||||
xkb_compose_feed_result::XKB_COMPOSE_FEED_ACCEPTED => {
|
||||
ComposeStatus::Accepted(self.status())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn reset(&mut self) {
|
||||
unsafe {
|
||||
(XKBCH.xkb_compose_state_reset)(self.state.as_ptr());
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn status(&mut self) -> xkb_compose_status {
|
||||
unsafe { (XKBCH.xkb_compose_state_get_status)(self.state.as_ptr()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbComposeState {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(XKBCH.xkb_compose_state_unref)(self.state.as_ptr());
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum ComposeStatus {
|
||||
Accepted(xkb_compose_status),
|
||||
Ignored,
|
||||
None,
|
||||
}
|
||||
@@ -1,6 +1,24 @@
|
||||
//! Convert XKB keys to Winit keys.
|
||||
//! XKB keymap.
|
||||
|
||||
use std::ffi::c_char;
|
||||
use std::ops::Deref;
|
||||
use std::ptr::{self, NonNull};
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
use x11_dl::xlib_xcb::xcb_connection_t;
|
||||
#[cfg(wayland_platform)]
|
||||
use {memmap2::MmapOptions, std::os::unix::io::OwnedFd};
|
||||
|
||||
use xkb::XKB_MOD_INVALID;
|
||||
use xkbcommon_dl::{
|
||||
self as xkb, xkb_keycode_t, xkb_keymap, xkb_keymap_compile_flags, xkb_keysym_t,
|
||||
xkb_layout_index_t, xkb_mod_index_t,
|
||||
};
|
||||
|
||||
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
||||
#[cfg(x11_platform)]
|
||||
use crate::platform_impl::common::xkb::XKBXH;
|
||||
use crate::platform_impl::common::xkb::{XkbContext, XKBH};
|
||||
|
||||
/// Map the raw X11-style keycode to the `KeyCode` enum.
|
||||
///
|
||||
@@ -894,3 +912,140 @@ pub fn keysym_location(keysym: u32) -> KeyLocation {
|
||||
_ => KeyLocation::Standard,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbKeymap {
|
||||
keymap: NonNull<xkb_keymap>,
|
||||
_mods_indices: ModsIndices,
|
||||
pub _core_keyboard_id: i32,
|
||||
}
|
||||
|
||||
impl XkbKeymap {
|
||||
#[cfg(wayland_platform)]
|
||||
pub fn from_fd(context: &XkbContext, fd: OwnedFd, size: usize) -> Option<Self> {
|
||||
let map = unsafe { MmapOptions::new().len(size).map_copy_read_only(&fd).ok()? };
|
||||
|
||||
let keymap = unsafe {
|
||||
let keymap = (XKBH.xkb_keymap_new_from_string)(
|
||||
(*context).as_ptr(),
|
||||
map.as_ptr() as *const _,
|
||||
xkb::xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1,
|
||||
xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
|
||||
);
|
||||
NonNull::new(keymap)?
|
||||
};
|
||||
|
||||
Some(Self::new_inner(keymap, 0))
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn from_x11_keymap(
|
||||
context: &XkbContext,
|
||||
xcb: *mut xcb_connection_t,
|
||||
core_keyboard_id: i32,
|
||||
) -> Option<Self> {
|
||||
let keymap = unsafe {
|
||||
(XKBXH.xkb_x11_keymap_new_from_device)(
|
||||
context.as_ptr(),
|
||||
xcb,
|
||||
core_keyboard_id,
|
||||
xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
|
||||
)
|
||||
};
|
||||
let keymap = NonNull::new(keymap)?;
|
||||
Some(Self::new_inner(keymap, core_keyboard_id))
|
||||
}
|
||||
|
||||
fn new_inner(keymap: NonNull<xkb_keymap>, _core_keyboard_id: i32) -> Self {
|
||||
let mods_indices = ModsIndices {
|
||||
shift: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_SHIFT),
|
||||
caps: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_CAPS),
|
||||
ctrl: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_CTRL),
|
||||
alt: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_ALT),
|
||||
num: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_NUM),
|
||||
mod3: mod_index_for_name(keymap, b"Mod3\0"),
|
||||
logo: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_LOGO),
|
||||
mod5: mod_index_for_name(keymap, b"Mod5\0"),
|
||||
};
|
||||
|
||||
Self {
|
||||
keymap,
|
||||
_mods_indices: mods_indices,
|
||||
_core_keyboard_id,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn mods_indices(&self) -> ModsIndices {
|
||||
self._mods_indices
|
||||
}
|
||||
|
||||
pub fn first_keysym_by_level(
|
||||
&mut self,
|
||||
layout: xkb_layout_index_t,
|
||||
keycode: xkb_keycode_t,
|
||||
) -> xkb_keysym_t {
|
||||
unsafe {
|
||||
let mut keysyms = ptr::null();
|
||||
let count = (XKBH.xkb_keymap_key_get_syms_by_level)(
|
||||
self.keymap.as_ptr(),
|
||||
keycode,
|
||||
layout,
|
||||
// NOTE: The level should be zero to ignore modifiers.
|
||||
0,
|
||||
&mut keysyms,
|
||||
);
|
||||
|
||||
if count == 1 {
|
||||
*keysyms
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check whether the given key repeats.
|
||||
pub fn key_repeats(&mut self, keycode: xkb_keycode_t) -> bool {
|
||||
unsafe { (XKBH.xkb_keymap_key_repeats)(self.keymap.as_ptr(), keycode) == 1 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbKeymap {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(XKBH.xkb_keymap_unref)(self.keymap.as_ptr());
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for XkbKeymap {
|
||||
type Target = NonNull<xkb_keymap>;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.keymap
|
||||
}
|
||||
}
|
||||
|
||||
/// Modifier index in the keymap.
|
||||
#[derive(Default, Debug, Clone, Copy)]
|
||||
pub struct ModsIndices {
|
||||
pub shift: Option<xkb_mod_index_t>,
|
||||
pub caps: Option<xkb_mod_index_t>,
|
||||
pub ctrl: Option<xkb_mod_index_t>,
|
||||
pub alt: Option<xkb_mod_index_t>,
|
||||
pub num: Option<xkb_mod_index_t>,
|
||||
pub mod3: Option<xkb_mod_index_t>,
|
||||
pub logo: Option<xkb_mod_index_t>,
|
||||
pub mod5: Option<xkb_mod_index_t>,
|
||||
}
|
||||
|
||||
fn mod_index_for_name(keymap: NonNull<xkb_keymap>, name: &[u8]) -> Option<xkb_mod_index_t> {
|
||||
unsafe {
|
||||
let mod_index =
|
||||
(XKBH.xkb_keymap_mod_get_index)(keymap.as_ptr(), name.as_ptr() as *const c_char);
|
||||
if mod_index == XKB_MOD_INVALID {
|
||||
None
|
||||
} else {
|
||||
Some(mod_index)
|
||||
}
|
||||
}
|
||||
}
|
||||
465
src/platform_impl/linux/common/xkb/mod.rs
Normal file
@@ -0,0 +1,465 @@
|
||||
use std::ops::Deref;
|
||||
use std::os::raw::c_char;
|
||||
use std::ptr::{self, NonNull};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use crate::utils::Lazy;
|
||||
use smol_str::SmolStr;
|
||||
#[cfg(wayland_platform)]
|
||||
use std::os::unix::io::OwnedFd;
|
||||
use tracing::warn;
|
||||
use xkbcommon_dl::{
|
||||
self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle,
|
||||
xkbcommon_handle, XkbCommon, XkbCommonCompose,
|
||||
};
|
||||
#[cfg(x11_platform)]
|
||||
use {x11_dl::xlib_xcb::xcb_connection_t, xkbcommon_dl::x11::xkbcommon_x11_handle};
|
||||
|
||||
use crate::event::ElementState;
|
||||
use crate::event::KeyEvent;
|
||||
use crate::keyboard::{Key, KeyLocation};
|
||||
use crate::platform_impl::KeyEventExtra;
|
||||
|
||||
mod compose;
|
||||
mod keymap;
|
||||
mod state;
|
||||
|
||||
use compose::{ComposeStatus, XkbComposeState, XkbComposeTable};
|
||||
use keymap::XkbKeymap;
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub use keymap::raw_keycode_to_physicalkey;
|
||||
pub use keymap::{physicalkey_to_scancode, scancode_to_physicalkey};
|
||||
pub use state::XkbState;
|
||||
|
||||
// TODO: Wire this up without using a static `AtomicBool`.
|
||||
static RESET_DEAD_KEYS: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
static XKBH: Lazy<&'static XkbCommon> = Lazy::new(xkbcommon_handle);
|
||||
static XKBCH: Lazy<&'static XkbCommonCompose> = Lazy::new(xkbcommon_compose_handle);
|
||||
#[cfg(feature = "x11")]
|
||||
static XKBXH: Lazy<&'static xkb::x11::XkbCommonX11> = Lazy::new(xkbcommon_x11_handle);
|
||||
|
||||
#[inline(always)]
|
||||
pub fn reset_dead_keys() {
|
||||
RESET_DEAD_KEYS.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
/// libxkbcommon is not available
|
||||
XKBNotFound,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Context {
|
||||
// NOTE: field order matters.
|
||||
#[cfg(x11_platform)]
|
||||
pub core_keyboard_id: i32,
|
||||
state: Option<XkbState>,
|
||||
keymap: Option<XkbKeymap>,
|
||||
compose_state1: Option<XkbComposeState>,
|
||||
compose_state2: Option<XkbComposeState>,
|
||||
_compose_table: Option<XkbComposeTable>,
|
||||
context: XkbContext,
|
||||
scratch_buffer: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new() -> Result<Self, Error> {
|
||||
if xkb::xkbcommon_option().is_none() {
|
||||
return Err(Error::XKBNotFound);
|
||||
}
|
||||
|
||||
let context = XkbContext::new()?;
|
||||
let mut compose_table = XkbComposeTable::new(&context);
|
||||
let mut compose_state1 = compose_table.as_ref().and_then(|table| table.new_state());
|
||||
let mut compose_state2 = compose_table.as_ref().and_then(|table| table.new_state());
|
||||
|
||||
// Disable compose if anything compose related failed to initialize.
|
||||
if compose_table.is_none() || compose_state1.is_none() || compose_state2.is_none() {
|
||||
compose_state2 = None;
|
||||
compose_state1 = None;
|
||||
compose_table = None;
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
state: None,
|
||||
keymap: None,
|
||||
compose_state1,
|
||||
compose_state2,
|
||||
#[cfg(x11_platform)]
|
||||
core_keyboard_id: 0,
|
||||
_compose_table: compose_table,
|
||||
context,
|
||||
scratch_buffer: Vec::with_capacity(8),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
pub fn from_x11_xkb(xcb: *mut xcb_connection_t) -> Result<Self, Error> {
|
||||
let result = unsafe {
|
||||
(XKBXH.xkb_x11_setup_xkb_extension)(
|
||||
xcb,
|
||||
1,
|
||||
2,
|
||||
xkbcommon_dl::x11::xkb_x11_setup_xkb_extension_flags::XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS,
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
|
||||
if result != 1 {
|
||||
return Err(Error::XKBNotFound);
|
||||
}
|
||||
|
||||
let mut this = Self::new()?;
|
||||
this.core_keyboard_id = unsafe { (XKBXH.xkb_x11_get_core_keyboard_device_id)(xcb) };
|
||||
this.set_keymap_from_x11(xcb);
|
||||
Ok(this)
|
||||
}
|
||||
|
||||
pub fn state_mut(&mut self) -> Option<&mut XkbState> {
|
||||
self.state.as_mut()
|
||||
}
|
||||
|
||||
pub fn keymap_mut(&mut self) -> Option<&mut XkbKeymap> {
|
||||
self.keymap.as_mut()
|
||||
}
|
||||
|
||||
#[cfg(wayland_platform)]
|
||||
pub fn set_keymap_from_fd(&mut self, fd: OwnedFd, size: usize) {
|
||||
let keymap = XkbKeymap::from_fd(&self.context, fd, size);
|
||||
let state = keymap.as_ref().and_then(XkbState::new_wayland);
|
||||
if keymap.is_none() || state.is_none() {
|
||||
warn!("failed to update xkb keymap");
|
||||
}
|
||||
self.state = state;
|
||||
self.keymap = keymap;
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn set_keymap_from_x11(&mut self, xcb: *mut xcb_connection_t) {
|
||||
let keymap = XkbKeymap::from_x11_keymap(&self.context, xcb, self.core_keyboard_id);
|
||||
let state = keymap
|
||||
.as_ref()
|
||||
.and_then(|keymap| XkbState::new_x11(xcb, keymap));
|
||||
if keymap.is_none() || state.is_none() {
|
||||
warn!("failed to update xkb keymap");
|
||||
}
|
||||
self.state = state;
|
||||
self.keymap = keymap;
|
||||
}
|
||||
|
||||
/// Key builder context with the user provided xkb state.
|
||||
pub fn key_context(&mut self) -> Option<KeyContext<'_>> {
|
||||
let state = self.state.as_mut()?;
|
||||
let keymap = self.keymap.as_mut()?;
|
||||
let compose_state1 = self.compose_state1.as_mut();
|
||||
let compose_state2 = self.compose_state2.as_mut();
|
||||
let scratch_buffer = &mut self.scratch_buffer;
|
||||
Some(KeyContext {
|
||||
state,
|
||||
keymap,
|
||||
compose_state1,
|
||||
compose_state2,
|
||||
scratch_buffer,
|
||||
})
|
||||
}
|
||||
|
||||
/// Key builder context with the user provided xkb state.
|
||||
///
|
||||
/// Should be used when the original context must not be altered.
|
||||
#[cfg(x11_platform)]
|
||||
pub fn key_context_with_state<'a>(
|
||||
&'a mut self,
|
||||
state: &'a mut XkbState,
|
||||
) -> Option<KeyContext<'a>> {
|
||||
let keymap = self.keymap.as_mut()?;
|
||||
let compose_state1 = self.compose_state1.as_mut();
|
||||
let compose_state2 = self.compose_state2.as_mut();
|
||||
let scratch_buffer = &mut self.scratch_buffer;
|
||||
Some(KeyContext {
|
||||
state,
|
||||
keymap,
|
||||
compose_state1,
|
||||
compose_state2,
|
||||
scratch_buffer,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct KeyContext<'a> {
|
||||
pub state: &'a mut XkbState,
|
||||
pub keymap: &'a mut XkbKeymap,
|
||||
compose_state1: Option<&'a mut XkbComposeState>,
|
||||
compose_state2: Option<&'a mut XkbComposeState>,
|
||||
scratch_buffer: &'a mut Vec<u8>,
|
||||
}
|
||||
|
||||
impl<'a> KeyContext<'a> {
|
||||
pub fn process_key_event(
|
||||
&mut self,
|
||||
keycode: u32,
|
||||
state: ElementState,
|
||||
repeat: bool,
|
||||
) -> KeyEvent {
|
||||
let mut event =
|
||||
KeyEventResults::new(self, keycode, !repeat && state == ElementState::Pressed);
|
||||
let physical_key = keymap::raw_keycode_to_physicalkey(keycode);
|
||||
let (logical_key, location) = event.key();
|
||||
let text = event.text();
|
||||
let (key_without_modifiers, _) = event.key_without_modifiers();
|
||||
let text_with_all_modifiers = event.text_with_all_modifiers();
|
||||
|
||||
let platform_specific = KeyEventExtra {
|
||||
text_with_all_modifiers,
|
||||
key_without_modifiers,
|
||||
};
|
||||
|
||||
KeyEvent {
|
||||
physical_key,
|
||||
logical_key,
|
||||
text,
|
||||
location,
|
||||
state,
|
||||
repeat,
|
||||
platform_specific,
|
||||
}
|
||||
}
|
||||
|
||||
fn keysym_to_utf8_raw(&mut self, keysym: u32) -> Option<SmolStr> {
|
||||
self.scratch_buffer.clear();
|
||||
self.scratch_buffer.reserve(8);
|
||||
loop {
|
||||
let bytes_written = unsafe {
|
||||
(XKBH.xkb_keysym_to_utf8)(
|
||||
keysym,
|
||||
self.scratch_buffer.as_mut_ptr().cast(),
|
||||
self.scratch_buffer.capacity(),
|
||||
)
|
||||
};
|
||||
if bytes_written == 0 {
|
||||
return None;
|
||||
} else if bytes_written == -1 {
|
||||
self.scratch_buffer.reserve(8);
|
||||
} else {
|
||||
unsafe {
|
||||
self.scratch_buffer
|
||||
.set_len(bytes_written.try_into().unwrap())
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the null-terminator
|
||||
self.scratch_buffer.pop();
|
||||
byte_slice_to_smol_str(self.scratch_buffer)
|
||||
}
|
||||
}
|
||||
|
||||
struct KeyEventResults<'a, 'b> {
|
||||
context: &'a mut KeyContext<'b>,
|
||||
keycode: u32,
|
||||
keysym: u32,
|
||||
compose: ComposeStatus,
|
||||
}
|
||||
|
||||
impl<'a, 'b> KeyEventResults<'a, 'b> {
|
||||
fn new(context: &'a mut KeyContext<'b>, keycode: u32, compose: bool) -> Self {
|
||||
let keysym = context.state.get_one_sym_raw(keycode);
|
||||
|
||||
let compose = if let Some(state) = context.compose_state1.as_mut().filter(|_| compose) {
|
||||
if RESET_DEAD_KEYS.swap(false, Ordering::SeqCst) {
|
||||
state.reset();
|
||||
context.compose_state2.as_mut().unwrap().reset();
|
||||
}
|
||||
state.feed(keysym)
|
||||
} else {
|
||||
ComposeStatus::None
|
||||
};
|
||||
|
||||
KeyEventResults {
|
||||
context,
|
||||
keycode,
|
||||
keysym,
|
||||
compose,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key(&mut self) -> (Key, KeyLocation) {
|
||||
let (key, location) = match self.keysym_to_key(self.keysym) {
|
||||
Ok(known) => return known,
|
||||
Err(undefined) => undefined,
|
||||
};
|
||||
|
||||
if let ComposeStatus::Accepted(xkb_compose_status::XKB_COMPOSE_COMPOSING) = self.compose {
|
||||
let compose_state = self.context.compose_state2.as_mut().unwrap();
|
||||
// When pressing a dead key twice, the non-combining variant of that character will
|
||||
// be produced. Since this function only concerns itself with a single keypress, we
|
||||
// simulate this double press here by feeding the keysym to the compose state
|
||||
// twice.
|
||||
|
||||
compose_state.feed(self.keysym);
|
||||
if matches!(compose_state.feed(self.keysym), ComposeStatus::Accepted(_)) {
|
||||
// Extracting only a single `char` here *should* be fine, assuming that no
|
||||
// dead key's non-combining variant ever occupies more than one `char`.
|
||||
let text = compose_state.get_string(self.context.scratch_buffer);
|
||||
let key = Key::Dead(text.and_then(|s| s.chars().next()));
|
||||
(key, location)
|
||||
} else {
|
||||
(key, location)
|
||||
}
|
||||
} else {
|
||||
let key = self
|
||||
.composed_text()
|
||||
.unwrap_or_else(|_| self.context.keysym_to_utf8_raw(self.keysym))
|
||||
.map(Key::Character)
|
||||
.unwrap_or(key);
|
||||
(key, location)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key_without_modifiers(&mut self) -> (Key, KeyLocation) {
|
||||
// This will become a pointer to an array which libxkbcommon owns, so we don't need to deallocate it.
|
||||
let layout = self.context.state.layout(self.keycode);
|
||||
let keysym = self
|
||||
.context
|
||||
.keymap
|
||||
.first_keysym_by_level(layout, self.keycode);
|
||||
|
||||
match self.keysym_to_key(keysym) {
|
||||
Ok((key, location)) => (key, location),
|
||||
Err((key, location)) => {
|
||||
let key = self
|
||||
.context
|
||||
.keysym_to_utf8_raw(keysym)
|
||||
.map(Key::Character)
|
||||
.unwrap_or(key);
|
||||
(key, location)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn keysym_to_key(&self, keysym: u32) -> Result<(Key, KeyLocation), (Key, KeyLocation)> {
|
||||
let location = keymap::keysym_location(keysym);
|
||||
let key = keymap::keysym_to_key(keysym);
|
||||
if matches!(key, Key::Unidentified(_)) {
|
||||
Err((key, location))
|
||||
} else {
|
||||
Ok((key, location))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text(&mut self) -> Option<SmolStr> {
|
||||
self.composed_text()
|
||||
.unwrap_or_else(|_| self.context.keysym_to_utf8_raw(self.keysym))
|
||||
}
|
||||
|
||||
// The current behaviour makes it so composing a character overrides attempts to input a
|
||||
// control character with the `Ctrl` key. We can potentially add a configuration option
|
||||
// if someone specifically wants the oppsite behaviour.
|
||||
pub fn text_with_all_modifiers(&mut self) -> Option<SmolStr> {
|
||||
match self.composed_text() {
|
||||
Ok(text) => text,
|
||||
Err(_) => self
|
||||
.context
|
||||
.state
|
||||
.get_utf8_raw(self.keycode, self.context.scratch_buffer),
|
||||
}
|
||||
}
|
||||
|
||||
fn composed_text(&mut self) -> Result<Option<SmolStr>, ()> {
|
||||
match self.compose {
|
||||
ComposeStatus::Accepted(status) => match status {
|
||||
xkb_compose_status::XKB_COMPOSE_COMPOSED => {
|
||||
let state = self.context.compose_state1.as_mut().unwrap();
|
||||
Ok(state.get_string(self.context.scratch_buffer))
|
||||
}
|
||||
xkb_compose_status::XKB_COMPOSE_COMPOSING
|
||||
| xkb_compose_status::XKB_COMPOSE_CANCELLED => Ok(None),
|
||||
xkb_compose_status::XKB_COMPOSE_NOTHING => Err(()),
|
||||
},
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbContext {
|
||||
context: NonNull<xkb_context>,
|
||||
}
|
||||
|
||||
impl XkbContext {
|
||||
pub fn new() -> Result<Self, Error> {
|
||||
let context = unsafe { (XKBH.xkb_context_new)(xkb_context_flags::XKB_CONTEXT_NO_FLAGS) };
|
||||
|
||||
let context = match NonNull::new(context) {
|
||||
Some(context) => context,
|
||||
None => return Err(Error::XKBNotFound),
|
||||
};
|
||||
|
||||
Ok(Self { context })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbContext {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(XKBH.xkb_context_unref)(self.context.as_ptr());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for XkbContext {
|
||||
type Target = NonNull<xkb_context>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.context
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared logic for constructing a string with `xkb_compose_state_get_utf8` and
|
||||
/// `xkb_state_key_get_utf8`.
|
||||
fn make_string_with<F>(scratch_buffer: &mut Vec<u8>, mut f: F) -> Option<SmolStr>
|
||||
where
|
||||
F: FnMut(*mut c_char, usize) -> i32,
|
||||
{
|
||||
let size = f(ptr::null_mut(), 0);
|
||||
if size == 0 {
|
||||
return None;
|
||||
}
|
||||
let size = usize::try_from(size).unwrap();
|
||||
scratch_buffer.clear();
|
||||
// The allocated buffer must include space for the null-terminator.
|
||||
scratch_buffer.reserve(size + 1);
|
||||
unsafe {
|
||||
let written = f(
|
||||
scratch_buffer.as_mut_ptr().cast(),
|
||||
scratch_buffer.capacity(),
|
||||
);
|
||||
if usize::try_from(written).unwrap() != size {
|
||||
// This will likely never happen.
|
||||
return None;
|
||||
}
|
||||
scratch_buffer.set_len(size);
|
||||
};
|
||||
|
||||
byte_slice_to_smol_str(scratch_buffer)
|
||||
}
|
||||
|
||||
// NOTE: This is track_caller so we can have more informative line numbers when logging
|
||||
#[track_caller]
|
||||
fn byte_slice_to_smol_str(bytes: &[u8]) -> Option<SmolStr> {
|
||||
std::str::from_utf8(bytes)
|
||||
.map(SmolStr::new)
|
||||
.map_err(|e| {
|
||||
tracing::warn!(
|
||||
"UTF-8 received from libxkbcommon ({:?}) was invalid: {e}",
|
||||
bytes
|
||||
)
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
189
src/platform_impl/linux/common/xkb/state.rs
Normal file
@@ -0,0 +1,189 @@
|
||||
//! XKB state.
|
||||
|
||||
use std::os::raw::c_char;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use smol_str::SmolStr;
|
||||
#[cfg(x11_platform)]
|
||||
use x11_dl::xlib_xcb::xcb_connection_t;
|
||||
use xkbcommon_dl::{
|
||||
self as xkb, xkb_keycode_t, xkb_keysym_t, xkb_layout_index_t, xkb_state, xkb_state_component,
|
||||
};
|
||||
|
||||
use crate::platform_impl::common::xkb::keymap::XkbKeymap;
|
||||
#[cfg(x11_platform)]
|
||||
use crate::platform_impl::common::xkb::XKBXH;
|
||||
use crate::platform_impl::common::xkb::{make_string_with, XKBH};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbState {
|
||||
state: NonNull<xkb_state>,
|
||||
modifiers: ModifiersState,
|
||||
}
|
||||
|
||||
impl XkbState {
|
||||
#[cfg(wayland_platform)]
|
||||
pub fn new_wayland(keymap: &XkbKeymap) -> Option<Self> {
|
||||
let state = NonNull::new(unsafe { (XKBH.xkb_state_new)(keymap.as_ptr()) })?;
|
||||
Some(Self::new_inner(state))
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn new_x11(xcb: *mut xcb_connection_t, keymap: &XkbKeymap) -> Option<Self> {
|
||||
let state = unsafe {
|
||||
(XKBXH.xkb_x11_state_new_from_device)(keymap.as_ptr(), xcb, keymap._core_keyboard_id)
|
||||
};
|
||||
let state = NonNull::new(state)?;
|
||||
Some(Self::new_inner(state))
|
||||
}
|
||||
|
||||
fn new_inner(state: NonNull<xkb_state>) -> Self {
|
||||
let modifiers = ModifiersState::default();
|
||||
let mut this = Self { state, modifiers };
|
||||
this.reload_modifiers();
|
||||
this
|
||||
}
|
||||
|
||||
pub fn get_one_sym_raw(&mut self, keycode: xkb_keycode_t) -> xkb_keysym_t {
|
||||
unsafe { (XKBH.xkb_state_key_get_one_sym)(self.state.as_ptr(), keycode) }
|
||||
}
|
||||
|
||||
pub fn layout(&mut self, key: xkb_keycode_t) -> xkb_layout_index_t {
|
||||
unsafe { (XKBH.xkb_state_key_get_layout)(self.state.as_ptr(), key) }
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn depressed_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||
unsafe {
|
||||
(XKBH.xkb_state_serialize_mods)(
|
||||
self.state.as_ptr(),
|
||||
xkb_state_component::XKB_STATE_MODS_DEPRESSED,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn latched_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||
unsafe {
|
||||
(XKBH.xkb_state_serialize_mods)(
|
||||
self.state.as_ptr(),
|
||||
xkb_state_component::XKB_STATE_MODS_LATCHED,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn locked_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||
unsafe {
|
||||
(XKBH.xkb_state_serialize_mods)(
|
||||
self.state.as_ptr(),
|
||||
xkb_state_component::XKB_STATE_MODS_LOCKED,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_utf8_raw(
|
||||
&mut self,
|
||||
keycode: xkb_keycode_t,
|
||||
scratch_buffer: &mut Vec<u8>,
|
||||
) -> Option<SmolStr> {
|
||||
make_string_with(scratch_buffer, |ptr, len| unsafe {
|
||||
(XKBH.xkb_state_key_get_utf8)(self.state.as_ptr(), keycode, ptr, len)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn modifiers(&self) -> ModifiersState {
|
||||
self.modifiers
|
||||
}
|
||||
|
||||
pub fn update_modifiers(
|
||||
&mut self,
|
||||
mods_depressed: u32,
|
||||
mods_latched: u32,
|
||||
mods_locked: u32,
|
||||
depressed_group: u32,
|
||||
latched_group: u32,
|
||||
locked_group: u32,
|
||||
) {
|
||||
let mask = unsafe {
|
||||
(XKBH.xkb_state_update_mask)(
|
||||
self.state.as_ptr(),
|
||||
mods_depressed,
|
||||
mods_latched,
|
||||
mods_locked,
|
||||
depressed_group,
|
||||
latched_group,
|
||||
locked_group,
|
||||
)
|
||||
};
|
||||
|
||||
if mask.contains(xkb_state_component::XKB_STATE_MODS_EFFECTIVE) {
|
||||
// Effective value of mods have changed, we need to update our state.
|
||||
self.reload_modifiers();
|
||||
}
|
||||
}
|
||||
|
||||
/// Reload the modifiers.
|
||||
fn reload_modifiers(&mut self) {
|
||||
self.modifiers.ctrl = self.mod_name_is_active(xkb::XKB_MOD_NAME_CTRL);
|
||||
self.modifiers.alt = self.mod_name_is_active(xkb::XKB_MOD_NAME_ALT);
|
||||
self.modifiers.shift = self.mod_name_is_active(xkb::XKB_MOD_NAME_SHIFT);
|
||||
self.modifiers.caps_lock = self.mod_name_is_active(xkb::XKB_MOD_NAME_CAPS);
|
||||
self.modifiers.logo = self.mod_name_is_active(xkb::XKB_MOD_NAME_LOGO);
|
||||
self.modifiers.num_lock = self.mod_name_is_active(xkb::XKB_MOD_NAME_NUM);
|
||||
}
|
||||
|
||||
/// Check if the modifier is active within xkb.
|
||||
fn mod_name_is_active(&mut self, name: &[u8]) -> bool {
|
||||
unsafe {
|
||||
(XKBH.xkb_state_mod_name_is_active)(
|
||||
self.state.as_ptr(),
|
||||
name.as_ptr() as *const c_char,
|
||||
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
|
||||
) > 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbState {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(XKBH.xkb_state_unref)(self.state.as_ptr());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the current state of the keyboard modifiers
|
||||
///
|
||||
/// Each field of this struct represents a modifier and is `true` if this modifier is active.
|
||||
///
|
||||
/// For some modifiers, this means that the key is currently pressed, others are toggled
|
||||
/// (like caps lock).
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ModifiersState {
|
||||
/// The "control" key
|
||||
pub ctrl: bool,
|
||||
/// The "alt" key
|
||||
pub alt: bool,
|
||||
/// The "shift" key
|
||||
pub shift: bool,
|
||||
/// The "Caps lock" key
|
||||
pub caps_lock: bool,
|
||||
/// The "logo" key
|
||||
///
|
||||
/// Also known as the "windows" key on most keyboards
|
||||
pub logo: bool,
|
||||
/// The "Num lock" key
|
||||
pub num_lock: bool,
|
||||
}
|
||||
|
||||
impl From<ModifiersState> for crate::keyboard::ModifiersState {
|
||||
fn from(mods: ModifiersState) -> crate::keyboard::ModifiersState {
|
||||
let mut to_mods = crate::keyboard::ModifiersState::empty();
|
||||
to_mods.set(crate::keyboard::ModifiersState::SHIFT, mods.shift);
|
||||
to_mods.set(crate::keyboard::ModifiersState::CONTROL, mods.ctrl);
|
||||
to_mods.set(crate::keyboard::ModifiersState::ALT, mods.alt);
|
||||
to_mods.set(crate::keyboard::ModifiersState::SUPER, mods.logo);
|
||||
to_mods
|
||||
}
|
||||
}
|
||||
@@ -11,19 +11,19 @@ use std::{collections::VecDeque, env, fmt};
|
||||
use std::{ffi::CStr, mem::MaybeUninit, os::raw::*, sync::Mutex};
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
use once_cell::sync::Lazy;
|
||||
use crate::utils::Lazy;
|
||||
use smol_str::SmolStr;
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
use self::x11::{X11Error, XConnection, XError, XNotSupported};
|
||||
#[cfg(x11_platform)]
|
||||
use crate::platform::x11::{WindowType as XWindowType, XlibErrorHook};
|
||||
use crate::window::{CustomCursor, CustomCursorSource};
|
||||
use crate::{
|
||||
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
|
||||
error::{EventLoopError, ExternalError, NotSupportedError, OsError as RootOsError},
|
||||
event_loop::{
|
||||
AsyncRequestSerial, ControlFlow, DeviceEvents, EventLoopClosed,
|
||||
EventLoopWindowTarget as RootELW,
|
||||
ActiveEventLoop as RootELW, AsyncRequestSerial, ControlFlow, DeviceEvents, EventLoopClosed,
|
||||
},
|
||||
icon::Icon,
|
||||
keyboard::Key,
|
||||
@@ -34,8 +34,8 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
pub(crate) use self::common::keymap::{physicalkey_to_scancode, scancode_to_physicalkey};
|
||||
pub(crate) use crate::cursor::OnlyCursorImageBuilder as PlatformCustomCursorBuilder;
|
||||
pub(crate) use self::common::xkb::{physicalkey_to_scancode, scancode_to_physicalkey};
|
||||
pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource;
|
||||
pub(crate) use crate::icon::RgbaIcon as PlatformIcon;
|
||||
pub(crate) use crate::platform_impl::Fullscreen;
|
||||
|
||||
@@ -72,16 +72,16 @@ impl ApplicationName {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PlatformSpecificWindowBuilderAttributes {
|
||||
pub struct PlatformSpecificWindowAttributes {
|
||||
pub name: Option<ApplicationName>,
|
||||
pub activation_token: Option<ActivationToken>,
|
||||
#[cfg(x11_platform)]
|
||||
pub x11: X11WindowBuilderAttributes,
|
||||
pub x11: X11WindowAttributes,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[cfg(x11_platform)]
|
||||
pub struct X11WindowBuilderAttributes {
|
||||
pub struct X11WindowAttributes {
|
||||
pub visual_id: Option<x11rb::protocol::xproto::Visualid>,
|
||||
pub screen_id: Option<i32>,
|
||||
pub base_size: Option<Size>,
|
||||
@@ -92,13 +92,13 @@ pub struct X11WindowBuilderAttributes {
|
||||
pub embed_window: Option<x11rb::protocol::xproto::Window>,
|
||||
}
|
||||
|
||||
impl Default for PlatformSpecificWindowBuilderAttributes {
|
||||
impl Default for PlatformSpecificWindowAttributes {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: None,
|
||||
activation_token: None,
|
||||
#[cfg(x11_platform)]
|
||||
x11: X11WindowBuilderAttributes {
|
||||
x11: X11WindowAttributes {
|
||||
visual_id: None,
|
||||
screen_id: None,
|
||||
base_size: None,
|
||||
@@ -142,6 +142,44 @@ pub(crate) enum Window {
|
||||
Wayland(wayland::Window),
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct WindowId(u64);
|
||||
|
||||
impl From<WindowId> for u64 {
|
||||
fn from(window_id: WindowId) -> Self {
|
||||
window_id.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for WindowId {
|
||||
fn from(raw_id: u64) -> Self {
|
||||
Self(raw_id)
|
||||
}
|
||||
}
|
||||
|
||||
impl WindowId {
|
||||
pub const unsafe fn dummy() -> Self {
|
||||
Self(0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum DeviceId {
|
||||
#[cfg(x11_platform)]
|
||||
X(x11::DeviceId),
|
||||
#[cfg(wayland_platform)]
|
||||
Wayland(wayland::DeviceId),
|
||||
}
|
||||
|
||||
impl DeviceId {
|
||||
pub const unsafe fn dummy() -> Self {
|
||||
#[cfg(wayland_platform)]
|
||||
return DeviceId::Wayland(unsafe { wayland::DeviceId::dummy() });
|
||||
#[cfg(all(not(wayland_platform), x11_platform))]
|
||||
return DeviceId::X(unsafe { x11::DeviceId::dummy() });
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum MonitorHandle {
|
||||
#[cfg(x11_platform)]
|
||||
@@ -248,16 +286,16 @@ impl VideoModeHandle {
|
||||
impl Window {
|
||||
#[inline]
|
||||
pub(crate) fn new(
|
||||
window_target: &EventLoopWindowTarget,
|
||||
window_target: &ActiveEventLoop,
|
||||
attribs: WindowAttributes,
|
||||
) -> Result<Self, RootOsError> {
|
||||
match *window_target {
|
||||
#[cfg(wayland_platform)]
|
||||
EventLoopWindowTarget::Wayland(ref window_target) => {
|
||||
ActiveEventLoop::Wayland(ref window_target) => {
|
||||
wayland::Window::new(window_target, attribs).map(Window::Wayland)
|
||||
}
|
||||
#[cfg(x11_platform)]
|
||||
EventLoopWindowTarget::X(ref window_target) => {
|
||||
ActiveEventLoop::X(ref window_target) => {
|
||||
x11::Window::new(window_target, attribs).map(Window::X)
|
||||
}
|
||||
}
|
||||
@@ -272,7 +310,7 @@ impl Window {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn id(&self) -> crate::window::WindowId {
|
||||
pub fn id(&self) -> WindowId {
|
||||
x11_or_wayland!(match self; Window(w) => w.id())
|
||||
}
|
||||
|
||||
@@ -478,7 +516,7 @@ impl Window {
|
||||
|
||||
#[inline]
|
||||
pub fn reset_dead_keys(&self) {
|
||||
common::xkb_state::reset_dead_keys()
|
||||
common::xkb::reset_dead_keys()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -606,26 +644,10 @@ pub(crate) enum PlatformCustomCursor {
|
||||
#[cfg(x11_platform)]
|
||||
X(x11::CustomCursor),
|
||||
}
|
||||
impl PlatformCustomCursor {
|
||||
pub(crate) fn build(
|
||||
builder: PlatformCustomCursorBuilder,
|
||||
p: &EventLoopWindowTarget,
|
||||
) -> PlatformCustomCursor {
|
||||
match p {
|
||||
#[cfg(wayland_platform)]
|
||||
EventLoopWindowTarget::Wayland(_) => {
|
||||
Self::Wayland(wayland::CustomCursor::build(builder, p))
|
||||
}
|
||||
#[cfg(x11_platform)]
|
||||
EventLoopWindowTarget::X(p) => Self::X(x11::CustomCursor::build(builder, p)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hooks for X11 errors.
|
||||
#[cfg(x11_platform)]
|
||||
pub(crate) static mut XLIB_ERROR_HOOKS: Lazy<Mutex<Vec<XlibErrorHook>>> =
|
||||
Lazy::new(|| Mutex::new(Vec::new()));
|
||||
pub(crate) static mut XLIB_ERROR_HOOKS: Mutex<Vec<XlibErrorHook>> = Mutex::new(Vec::new());
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
unsafe extern "C" fn x_error_callback(
|
||||
@@ -665,7 +687,7 @@ unsafe extern "C" fn x_error_callback(
|
||||
|
||||
// Don't log error.
|
||||
if !error_handled {
|
||||
log::error!("X11 error: {:#?}", error);
|
||||
tracing::error!("X11 error: {:#?}", error);
|
||||
// XXX only update the error, if it wasn't handled by any of the hooks.
|
||||
*xconn.latest_error.lock().unwrap() = Some(error);
|
||||
}
|
||||
@@ -791,7 +813,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.pump_events(timeout, callback))
|
||||
}
|
||||
|
||||
pub fn window_target(&self) -> &crate::event_loop::EventLoopWindowTarget {
|
||||
pub fn window_target(&self) -> &crate::event_loop::ActiveEventLoop {
|
||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.window_target())
|
||||
}
|
||||
}
|
||||
@@ -814,34 +836,38 @@ impl<T: 'static> EventLoopProxy<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub enum EventLoopWindowTarget {
|
||||
pub enum ActiveEventLoop {
|
||||
#[cfg(wayland_platform)]
|
||||
Wayland(wayland::EventLoopWindowTarget),
|
||||
Wayland(wayland::ActiveEventLoop),
|
||||
#[cfg(x11_platform)]
|
||||
X(x11::EventLoopWindowTarget),
|
||||
X(x11::ActiveEventLoop),
|
||||
}
|
||||
|
||||
impl EventLoopWindowTarget {
|
||||
impl ActiveEventLoop {
|
||||
#[inline]
|
||||
pub fn is_wayland(&self) -> bool {
|
||||
match *self {
|
||||
#[cfg(wayland_platform)]
|
||||
EventLoopWindowTarget::Wayland(_) => true,
|
||||
ActiveEventLoop::Wayland(_) => true,
|
||||
#[cfg(x11_platform)]
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_custom_cursor(&self, cursor: CustomCursorSource) -> CustomCursor {
|
||||
x11_or_wayland!(match self; ActiveEventLoop(evlp) => evlp.create_custom_cursor(cursor))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
match *self {
|
||||
#[cfg(wayland_platform)]
|
||||
EventLoopWindowTarget::Wayland(ref evlp) => evlp
|
||||
ActiveEventLoop::Wayland(ref evlp) => evlp
|
||||
.available_monitors()
|
||||
.map(MonitorHandle::Wayland)
|
||||
.collect(),
|
||||
#[cfg(x11_platform)]
|
||||
EventLoopWindowTarget::X(ref evlp) => {
|
||||
ActiveEventLoop::X(ref evlp) => {
|
||||
evlp.available_monitors().map(MonitorHandle::X).collect()
|
||||
}
|
||||
}
|
||||
@@ -850,7 +876,7 @@ impl EventLoopWindowTarget {
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
Some(
|
||||
x11_or_wayland!(match self; EventLoopWindowTarget(evlp) => evlp.primary_monitor()?; as MonitorHandle),
|
||||
x11_or_wayland!(match self; ActiveEventLoop(evlp) => evlp.primary_monitor()?; as MonitorHandle),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -902,10 +928,12 @@ impl EventLoopWindowTarget {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn set_exit_code(&self, code: i32) {
|
||||
x11_or_wayland!(match self; Self(evlp) => evlp.set_exit_code(code))
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn exit_code(&self) -> Option<i32> {
|
||||
x11_or_wayland!(match self; Self(evlp) => evlp.exit_code())
|
||||
}
|
||||
@@ -10,21 +10,22 @@ use std::sync::atomic::Ordering;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use sctk::reexports::calloop;
|
||||
use sctk::reexports::calloop::Error as CalloopError;
|
||||
use sctk::reexports::calloop_wayland_source::WaylandSource;
|
||||
use sctk::reexports::client::globals;
|
||||
use sctk::reexports::client::{Connection, QueueHandle};
|
||||
|
||||
use crate::cursor::OnlyCursorImage;
|
||||
use crate::dpi::LogicalSize;
|
||||
use crate::error::{EventLoopError, OsError as RootOsError};
|
||||
use crate::event::{Event, InnerSizeWriter, StartCause, WindowEvent};
|
||||
use crate::event_loop::{
|
||||
ControlFlow, DeviceEvents, EventLoopWindowTarget as RootEventLoopWindowTarget,
|
||||
};
|
||||
use crate::event_loop::{ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents};
|
||||
use crate::platform::pump_events::PumpStatus;
|
||||
use crate::platform_impl::platform::min_timeout;
|
||||
use crate::platform_impl::{EventLoopWindowTarget as PlatformEventLoopWindowTarget, OsError};
|
||||
use crate::platform_impl::{
|
||||
ActiveEventLoop as PlatformActiveEventLoop, OsError, PlatformCustomCursor,
|
||||
};
|
||||
use crate::window::{CustomCursor as RootCustomCursor, CustomCursorSource};
|
||||
|
||||
mod proxy;
|
||||
pub mod sink;
|
||||
@@ -34,7 +35,7 @@ use sink::EventSink;
|
||||
|
||||
use super::state::{WindowCompositorUpdate, WinitState};
|
||||
use super::window::state::FrameCallbackState;
|
||||
use super::{logical_to_physical_rounded, WaylandError, WindowId};
|
||||
use super::{logical_to_physical_rounded, DeviceId, WaylandError, WindowId};
|
||||
|
||||
type WaylandDispatcher = calloop::Dispatcher<'static, WaylandSource<WinitState>, WinitState>;
|
||||
|
||||
@@ -63,7 +64,7 @@ pub struct EventLoop<T: 'static> {
|
||||
connection: Connection,
|
||||
|
||||
/// Event loop window target.
|
||||
window_target: RootEventLoopWindowTarget,
|
||||
window_target: RootActiveEventLoop,
|
||||
|
||||
// XXX drop after everything else, just to be safe.
|
||||
/// Calloop's event loop.
|
||||
@@ -159,7 +160,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
.map_err(|error| error.error);
|
||||
map_err!(result, WaylandError::Calloop)?;
|
||||
|
||||
let window_target = EventLoopWindowTarget {
|
||||
let window_target = ActiveEventLoop {
|
||||
connection: connection.clone(),
|
||||
wayland_dispatcher: wayland_dispatcher.clone(),
|
||||
event_loop_awakener,
|
||||
@@ -179,8 +180,8 @@ impl<T: 'static> EventLoop<T> {
|
||||
user_events_sender,
|
||||
pending_user_events,
|
||||
event_loop,
|
||||
window_target: RootEventLoopWindowTarget {
|
||||
p: PlatformEventLoopWindowTarget::Wayland(window_target),
|
||||
window_target: RootActiveEventLoop {
|
||||
p: PlatformActiveEventLoop::Wayland(window_target),
|
||||
_marker: PhantomData,
|
||||
},
|
||||
};
|
||||
@@ -190,7 +191,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
pub fn run_on_demand<F>(&mut self, mut event_handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(Event<T>, &RootEventLoopWindowTarget),
|
||||
F: FnMut(Event<T>, &RootActiveEventLoop),
|
||||
{
|
||||
let exit = loop {
|
||||
match self.pump_events(None, &mut event_handler) {
|
||||
@@ -217,7 +218,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
pub fn pump_events<F>(&mut self, timeout: Option<Duration>, mut callback: F) -> PumpStatus
|
||||
where
|
||||
F: FnMut(Event<T>, &RootEventLoopWindowTarget),
|
||||
F: FnMut(Event<T>, &RootActiveEventLoop),
|
||||
{
|
||||
if !self.loop_running {
|
||||
self.loop_running = true;
|
||||
@@ -244,7 +245,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
pub fn poll_events_with_timeout<F>(&mut self, mut timeout: Option<Duration>, mut callback: F)
|
||||
where
|
||||
F: FnMut(Event<T>, &RootEventLoopWindowTarget),
|
||||
F: FnMut(Event<T>, &RootActiveEventLoop),
|
||||
{
|
||||
let cause = loop {
|
||||
let start = Instant::now();
|
||||
@@ -320,7 +321,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
fn single_iteration<F>(&mut self, callback: &mut F, cause: StartCause)
|
||||
where
|
||||
F: FnMut(Event<T>, &RootEventLoopWindowTarget),
|
||||
F: FnMut(Event<T>, &RootActiveEventLoop),
|
||||
{
|
||||
// NOTE currently just indented to simplify the diff
|
||||
|
||||
@@ -366,7 +367,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
let new_inner_size = Arc::new(Mutex::new(physical_size));
|
||||
callback(
|
||||
Event::WindowEvent {
|
||||
window_id,
|
||||
window_id: crate::window::WindowId(window_id),
|
||||
event: WindowEvent::ScaleFactorChanged {
|
||||
scale_factor,
|
||||
inner_size_writer: InnerSizeWriter::new(Arc::downgrade(
|
||||
@@ -420,7 +421,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
callback(
|
||||
Event::WindowEvent {
|
||||
window_id,
|
||||
window_id: crate::window::WindowId(window_id),
|
||||
event: WindowEvent::Resized(physical_size),
|
||||
},
|
||||
&self.window_target,
|
||||
@@ -430,7 +431,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
if compositor_update.close_window {
|
||||
callback(
|
||||
Event::WindowEvent {
|
||||
window_id,
|
||||
window_id: crate::window::WindowId(window_id),
|
||||
event: WindowEvent::CloseRequested,
|
||||
},
|
||||
&self.window_target,
|
||||
@@ -461,19 +462,19 @@ impl<T: 'static> EventLoop<T> {
|
||||
window_ids.extend(state.window_requests.get_mut().keys());
|
||||
});
|
||||
|
||||
for window_id in window_ids.drain(..) {
|
||||
for window_id in window_ids.iter() {
|
||||
let event = self.with_state(|state| {
|
||||
let window_requests = state.window_requests.get_mut();
|
||||
if window_requests.get(&window_id).unwrap().take_closed() {
|
||||
mem::drop(window_requests.remove(&window_id));
|
||||
mem::drop(state.windows.get_mut().remove(&window_id));
|
||||
if window_requests.get(window_id).unwrap().take_closed() {
|
||||
mem::drop(window_requests.remove(window_id));
|
||||
mem::drop(state.windows.get_mut().remove(window_id));
|
||||
return Some(WindowEvent::Destroyed);
|
||||
}
|
||||
|
||||
let mut window = state
|
||||
.windows
|
||||
.get_mut()
|
||||
.get_mut(&window_id)
|
||||
.get_mut(window_id)
|
||||
.unwrap()
|
||||
.lock()
|
||||
.unwrap();
|
||||
@@ -485,7 +486,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
// Reset the frame callbacks state.
|
||||
window.frame_callback_reset();
|
||||
let mut redraw_requested = window_requests
|
||||
.get(&window_id)
|
||||
.get(window_id)
|
||||
.unwrap()
|
||||
.take_redraw_requested();
|
||||
|
||||
@@ -496,7 +497,13 @@ impl<T: 'static> EventLoop<T> {
|
||||
});
|
||||
|
||||
if let Some(event) = event {
|
||||
callback(Event::WindowEvent { window_id, event }, &self.window_target);
|
||||
callback(
|
||||
Event::WindowEvent {
|
||||
window_id: crate::window::WindowId(*window_id),
|
||||
event,
|
||||
},
|
||||
&self.window_target,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -508,6 +515,42 @@ impl<T: 'static> EventLoop<T> {
|
||||
// This is always the last event we dispatch before poll again
|
||||
callback(Event::AboutToWait, &self.window_target);
|
||||
|
||||
// Update the window frames and schedule redraws.
|
||||
let mut wake_up = false;
|
||||
for window_id in window_ids.drain(..) {
|
||||
wake_up |= self.with_state(|state| match state.windows.get_mut().get_mut(&window_id) {
|
||||
Some(window) => {
|
||||
let refresh = window.lock().unwrap().refresh_frame();
|
||||
if refresh {
|
||||
state
|
||||
.window_requests
|
||||
.get_mut()
|
||||
.get_mut(&window_id)
|
||||
.unwrap()
|
||||
.redraw_requested
|
||||
.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
refresh
|
||||
}
|
||||
None => false,
|
||||
});
|
||||
}
|
||||
|
||||
// Wakeup event loop if needed.
|
||||
//
|
||||
// If the user draws from the `AboutToWait` this is likely not required, however
|
||||
// we can't do much about it.
|
||||
if wake_up {
|
||||
match &self.window_target.p {
|
||||
PlatformActiveEventLoop::Wayland(window_target) => {
|
||||
window_target.event_loop_awakener.ping();
|
||||
}
|
||||
#[cfg(x11_platform)]
|
||||
PlatformActiveEventLoop::X(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
std::mem::swap(&mut self.compositor_updates, &mut compositor_updates);
|
||||
std::mem::swap(&mut self.buffer_sink, &mut buffer_sink);
|
||||
std::mem::swap(&mut self.window_ids, &mut window_ids);
|
||||
@@ -519,13 +562,13 @@ impl<T: 'static> EventLoop<T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn window_target(&self) -> &RootEventLoopWindowTarget {
|
||||
pub fn window_target(&self) -> &RootActiveEventLoop {
|
||||
&self.window_target
|
||||
}
|
||||
|
||||
fn with_state<'a, U: 'a, F: FnOnce(&'a mut WinitState) -> U>(&'a mut self, callback: F) -> U {
|
||||
let state = match &mut self.window_target.p {
|
||||
PlatformEventLoopWindowTarget::Wayland(window_target) => window_target.state.get_mut(),
|
||||
PlatformActiveEventLoop::Wayland(window_target) => window_target.state.get_mut(),
|
||||
#[cfg(x11_platform)]
|
||||
_ => unreachable!(),
|
||||
};
|
||||
@@ -535,20 +578,20 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
fn loop_dispatch<D: Into<Option<std::time::Duration>>>(&mut self, timeout: D) -> IOResult<()> {
|
||||
let state = match &mut self.window_target.p {
|
||||
PlatformEventLoopWindowTarget::Wayland(window_target) => window_target.state.get_mut(),
|
||||
PlatformActiveEventLoop::Wayland(window_target) => window_target.state.get_mut(),
|
||||
#[cfg(feature = "x11")]
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
self.event_loop.dispatch(timeout, state).map_err(|error| {
|
||||
log::error!("Error dispatching event loop: {}", error);
|
||||
tracing::error!("Error dispatching event loop: {}", error);
|
||||
error.into()
|
||||
})
|
||||
}
|
||||
|
||||
fn roundtrip(&mut self) -> Result<usize, RootOsError> {
|
||||
let state = match &mut self.window_target.p {
|
||||
PlatformEventLoopWindowTarget::Wayland(window_target) => window_target.state.get_mut(),
|
||||
PlatformActiveEventLoop::Wayland(window_target) => window_target.state.get_mut(),
|
||||
#[cfg(feature = "x11")]
|
||||
_ => unreachable!(),
|
||||
};
|
||||
@@ -591,7 +634,7 @@ impl<T> AsRawFd for EventLoop<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoopWindowTarget {
|
||||
pub struct ActiveEventLoop {
|
||||
/// The event loop wakeup source.
|
||||
pub event_loop_awakener: calloop::ping::Ping,
|
||||
|
||||
@@ -615,7 +658,7 @@ pub struct EventLoopWindowTarget {
|
||||
pub connection: Connection,
|
||||
}
|
||||
|
||||
impl EventLoopWindowTarget {
|
||||
impl ActiveEventLoop {
|
||||
pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||
self.control_flow.set(control_flow)
|
||||
}
|
||||
@@ -647,6 +690,12 @@ impl EventLoopWindowTarget {
|
||||
#[inline]
|
||||
pub fn listen_device_events(&self, _allowed: DeviceEvents) {}
|
||||
|
||||
pub(crate) fn create_custom_cursor(&self, cursor: CustomCursorSource) -> RootCustomCursor {
|
||||
RootCustomCursor {
|
||||
inner: PlatformCustomCursor::Wayland(OnlyCursorImage(Arc::from(cursor.inner.0))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||
@@ -2,8 +2,11 @@
|
||||
|
||||
use std::vec::Drain;
|
||||
|
||||
use crate::event::{DeviceEvent, DeviceId, Event, WindowEvent};
|
||||
use crate::window::WindowId;
|
||||
use crate::event::{DeviceEvent, DeviceId as RootDeviceId, Event, WindowEvent};
|
||||
use crate::platform_impl::platform::DeviceId as PlatformDeviceId;
|
||||
use crate::window::WindowId as RootWindowId;
|
||||
|
||||
use super::{DeviceId, WindowId};
|
||||
|
||||
/// An event loop's sink to deliver events from the Wayland event callbacks
|
||||
/// to the winit's user.
|
||||
@@ -26,15 +29,19 @@ impl EventSink {
|
||||
/// Add new device event to a queue.
|
||||
#[inline]
|
||||
pub fn push_device_event(&mut self, event: DeviceEvent, device_id: DeviceId) {
|
||||
self.window_events
|
||||
.push(Event::DeviceEvent { event, device_id });
|
||||
self.window_events.push(Event::DeviceEvent {
|
||||
event,
|
||||
device_id: RootDeviceId(PlatformDeviceId::Wayland(device_id)),
|
||||
});
|
||||
}
|
||||
|
||||
/// Add new window event to a queue.
|
||||
#[inline]
|
||||
pub fn push_window_event(&mut self, event: WindowEvent, window_id: WindowId) {
|
||||
self.window_events
|
||||
.push(Event::WindowEvent { event, window_id });
|
||||
self.window_events.push(Event::WindowEvent {
|
||||
event,
|
||||
window_id: RootWindowId(window_id),
|
||||
});
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -11,13 +11,11 @@ use sctk::reexports::client::{self, ConnectError, DispatchError, Proxy};
|
||||
|
||||
pub(super) use crate::cursor::OnlyCursorImage as CustomCursor;
|
||||
use crate::dpi::{LogicalSize, PhysicalSize};
|
||||
pub use crate::platform_impl::platform::OsError;
|
||||
pub use event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget};
|
||||
pub use crate::platform_impl::platform::{OsError, WindowId};
|
||||
pub use event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy};
|
||||
pub use output::{MonitorHandle, VideoModeHandle};
|
||||
pub use window::Window;
|
||||
|
||||
use crate::window::WindowId;
|
||||
|
||||
mod event_loop;
|
||||
mod output;
|
||||
mod seat;
|
||||
@@ -65,10 +63,20 @@ impl From<WaylandError> for OsError {
|
||||
}
|
||||
}
|
||||
|
||||
/// Dummy device id, since Wayland doesn't have device events.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId;
|
||||
|
||||
impl DeviceId {
|
||||
pub const unsafe fn dummy() -> Self {
|
||||
DeviceId
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the WindowId out of the surface.
|
||||
#[inline]
|
||||
fn make_wid(surface: &WlSurface) -> WindowId {
|
||||
WindowId::from(surface.id().as_ptr() as u64)
|
||||
WindowId(surface.id().as_ptr() as u64)
|
||||
}
|
||||
|
||||
/// The default routine does floor, but we need round on Wayland.
|
||||
@@ -6,9 +6,9 @@ use sctk::output::OutputData;
|
||||
use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
||||
use crate::platform_impl::platform::VideoModeHandle as PlatformVideoModeHandle;
|
||||
|
||||
use super::event_loop::EventLoopWindowTarget;
|
||||
use super::event_loop::ActiveEventLoop;
|
||||
|
||||
impl EventLoopWindowTarget {
|
||||
impl ActiveEventLoop {
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
||||
self.state
|
||||
@@ -5,7 +5,7 @@ use std::time::Duration;
|
||||
|
||||
use calloop::timer::{TimeoutAction, Timer};
|
||||
use calloop::{LoopHandle, RegistrationToken};
|
||||
use log::warn;
|
||||
use tracing::warn;
|
||||
|
||||
use sctk::reexports::client::protocol::wl_keyboard::WlKeyboard;
|
||||
use sctk::reexports::client::protocol::wl_keyboard::{
|
||||
@@ -17,11 +17,11 @@ use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
|
||||
use crate::event::{ElementState, WindowEvent};
|
||||
use crate::keyboard::ModifiersState;
|
||||
|
||||
use crate::platform_impl::common::xkb_state::KbdState;
|
||||
use crate::platform_impl::common::xkb::Context;
|
||||
use crate::platform_impl::wayland::event_loop::sink::EventSink;
|
||||
use crate::platform_impl::wayland::seat::WinitSeatState;
|
||||
use crate::platform_impl::wayland::state::WinitState;
|
||||
use crate::platform_impl::wayland::{self, WindowId};
|
||||
use crate::platform_impl::wayland::{self, DeviceId, WindowId};
|
||||
|
||||
impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
fn event(
|
||||
@@ -43,14 +43,10 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
WlKeymapFormat::NoKeymap => {
|
||||
warn!("non-xkb compatible keymap")
|
||||
}
|
||||
WlKeymapFormat::XkbV1 => unsafe {
|
||||
seat_state
|
||||
.keyboard_state
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.xkb_state
|
||||
.init_with_fd(fd, size as usize);
|
||||
},
|
||||
WlKeymapFormat::XkbV1 => {
|
||||
let context = &mut seat_state.keyboard_state.as_mut().unwrap().xkb_context;
|
||||
context.set_keymap_from_fd(fd, size as usize);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
},
|
||||
WEnum::Unknown(value) => {
|
||||
@@ -155,7 +151,12 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
RepeatInfo::Disable => return,
|
||||
};
|
||||
|
||||
if !keyboard_state.xkb_state.key_repeats(key) {
|
||||
if !keyboard_state
|
||||
.xkb_context
|
||||
.keymap_mut()
|
||||
.unwrap()
|
||||
.key_repeats(key)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -221,7 +222,11 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
|
||||
let keyboard_state = seat_state.keyboard_state.as_mut().unwrap();
|
||||
if keyboard_state.repeat_info != RepeatInfo::Disable
|
||||
&& keyboard_state.xkb_state.key_repeats(key)
|
||||
&& keyboard_state
|
||||
.xkb_context
|
||||
.keymap_mut()
|
||||
.unwrap()
|
||||
.key_repeats(key)
|
||||
&& Some(key) == keyboard_state.current_repeat
|
||||
{
|
||||
keyboard_state.current_repeat = None;
|
||||
@@ -237,9 +242,14 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
group,
|
||||
..
|
||||
} => {
|
||||
let xkb_state = &mut seat_state.keyboard_state.as_mut().unwrap().xkb_state;
|
||||
let xkb_context = &mut seat_state.keyboard_state.as_mut().unwrap().xkb_context;
|
||||
let xkb_state = match xkb_context.state_mut() {
|
||||
Some(state) => state,
|
||||
None => return,
|
||||
};
|
||||
|
||||
xkb_state.update_modifiers(mods_depressed, mods_latched, mods_locked, 0, 0, group);
|
||||
seat_state.modifiers = xkb_state.mods_state().into();
|
||||
seat_state.modifiers = xkb_state.modifiers().into();
|
||||
|
||||
// HACK: part of the workaround from `WlKeyboardEvent::Enter`.
|
||||
let window_id = match *data.window_id.lock().unwrap() {
|
||||
@@ -285,7 +295,7 @@ pub struct KeyboardState {
|
||||
pub loop_handle: LoopHandle<'static, WinitState>,
|
||||
|
||||
/// The state of the keyboard.
|
||||
pub xkb_state: KbdState,
|
||||
pub xkb_context: Context,
|
||||
|
||||
/// The information about the repeat rate obtained from the compositor.
|
||||
pub repeat_info: RepeatInfo,
|
||||
@@ -302,7 +312,7 @@ impl KeyboardState {
|
||||
Self {
|
||||
keyboard,
|
||||
loop_handle,
|
||||
xkb_state: KbdState::new().unwrap(),
|
||||
xkb_context: Context::new().unwrap(),
|
||||
repeat_info: RepeatInfo::default(),
|
||||
repeat_token: None,
|
||||
current_repeat: None,
|
||||
@@ -384,17 +394,14 @@ fn key_input(
|
||||
|
||||
let keyboard_state = seat_state.keyboard_state.as_mut().unwrap();
|
||||
|
||||
let device_id = crate::event::DeviceId::from(0);
|
||||
let event = keyboard_state
|
||||
.xkb_state
|
||||
.process_key_event(keycode, state, repeat);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::KeyboardInput {
|
||||
let device_id = crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(DeviceId));
|
||||
if let Some(mut key_context) = keyboard_state.xkb_context.key_context() {
|
||||
let event = key_context.process_key_event(keycode, state, repeat);
|
||||
let event = WindowEvent::KeyboardInput {
|
||||
device_id,
|
||||
event,
|
||||
is_synthetic: false,
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
};
|
||||
event_sink.push_window_event(event, window_id);
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ pub struct WinitSeatState {
|
||||
/// The current modifiers state on the seat.
|
||||
modifiers: ModifiersState,
|
||||
|
||||
/// Wether we have pending modifiers.
|
||||
/// Whether we have pending modifiers.
|
||||
modifiers_pending: bool,
|
||||
}
|
||||
|
||||
@@ -22,13 +22,12 @@ use sctk::globals::GlobalData;
|
||||
use sctk::seat::pointer::{PointerData, PointerDataExt};
|
||||
use sctk::seat::pointer::{PointerEvent, PointerEventKind, PointerHandler};
|
||||
use sctk::seat::SeatState;
|
||||
use winit_core::event::DeviceId;
|
||||
|
||||
use crate::dpi::{LogicalPosition, PhysicalPosition};
|
||||
use crate::event::{ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent};
|
||||
|
||||
use crate::platform_impl::wayland::state::WinitState;
|
||||
use crate::platform_impl::wayland::{self, WindowId};
|
||||
use crate::platform_impl::wayland::{self, DeviceId, WindowId};
|
||||
|
||||
pub mod relative_pointer;
|
||||
|
||||
@@ -43,7 +42,7 @@ impl PointerHandler for WinitState {
|
||||
let seat = pointer.winit_data().seat();
|
||||
let seat_state = self.seats.get(&seat.id()).unwrap();
|
||||
|
||||
let device_id = DeviceId::from(0);
|
||||
let device_id = crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(DeviceId));
|
||||
|
||||
for event in events {
|
||||
let surface = &event.surface;
|
||||
@@ -197,7 +196,7 @@ impl PointerHandler for WinitState {
|
||||
TouchPhase::Ended
|
||||
} else {
|
||||
match pointer_data.phase {
|
||||
// Descrete scroll only results in moved events.
|
||||
// Discrete scroll only results in moved events.
|
||||
_ if has_discrete_scroll => TouchPhase::Moved,
|
||||
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
|
||||
_ => TouchPhase::Started,
|
||||
@@ -60,19 +60,34 @@ impl Dispatch<ZwpRelativePointerV1, GlobalData, WinitState> for RelativePointerS
|
||||
_conn: &Connection,
|
||||
_qhandle: &QueueHandle<WinitState>,
|
||||
) {
|
||||
if let zwp_relative_pointer_v1::Event::RelativeMotion {
|
||||
dx_unaccel,
|
||||
dy_unaccel,
|
||||
..
|
||||
} = event
|
||||
{
|
||||
state.events_sink.push_device_event(
|
||||
DeviceEvent::MouseMotion {
|
||||
delta: (dx_unaccel, dy_unaccel),
|
||||
},
|
||||
crate::event::DeviceId::from(0),
|
||||
);
|
||||
}
|
||||
let (dx_unaccel, dy_unaccel) = match event {
|
||||
zwp_relative_pointer_v1::Event::RelativeMotion {
|
||||
dx_unaccel,
|
||||
dy_unaccel,
|
||||
..
|
||||
} => (dx_unaccel, dy_unaccel),
|
||||
_ => return,
|
||||
};
|
||||
state.events_sink.push_device_event(
|
||||
DeviceEvent::Motion {
|
||||
axis: 0,
|
||||
value: dx_unaccel,
|
||||
},
|
||||
super::DeviceId,
|
||||
);
|
||||
state.events_sink.push_device_event(
|
||||
DeviceEvent::Motion {
|
||||
axis: 1,
|
||||
value: dy_unaccel,
|
||||
},
|
||||
super::DeviceId,
|
||||
);
|
||||
state.events_sink.push_device_event(
|
||||
DeviceEvent::MouseMotion {
|
||||
delta: (dx_unaccel, dy_unaccel),
|
||||
},
|
||||
super::DeviceId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ impl Dispatch<ZwpTextInputV3, TextInputData, WinitState> for TextInputState {
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
|
||||
// XXX this check is essential, because `leave` could have a
|
||||
// refence to nil surface...
|
||||
// reference to nil surface...
|
||||
let mut window = match windows.get(&window_id) {
|
||||
Some(window) => window.lock().unwrap(),
|
||||
None => return,
|
||||
@@ -178,7 +178,6 @@ impl ZwpTextInputV3Ext for ZwpTextInputV3 {
|
||||
ImePurpose::Normal => (ContentHint::None, ContentPurpose::Normal),
|
||||
ImePurpose::Password => (ContentHint::SensitiveData, ContentPurpose::Password),
|
||||
ImePurpose::Terminal => (ContentHint::None, ContentPurpose::Terminal),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
self.set_content_type(hint, purpose);
|
||||
}
|
||||
@@ -6,13 +6,12 @@ use sctk::reexports::client::protocol::wl_touch::WlTouch;
|
||||
use sctk::reexports::client::{Connection, Proxy, QueueHandle};
|
||||
|
||||
use sctk::seat::touch::{TouchData, TouchHandler};
|
||||
use winit_core::event::DeviceId;
|
||||
|
||||
use crate::dpi::LogicalPosition;
|
||||
use crate::event::{Touch, TouchPhase, WindowEvent};
|
||||
|
||||
use crate::platform_impl::wayland;
|
||||
use crate::platform_impl::wayland::state::WinitState;
|
||||
use crate::platform_impl::wayland::{self, DeviceId};
|
||||
|
||||
impl TouchHandler for WinitState {
|
||||
fn down(
|
||||
@@ -43,7 +42,9 @@ impl TouchHandler for WinitState {
|
||||
|
||||
self.events_sink.push_window_event(
|
||||
WindowEvent::Touch(Touch {
|
||||
device_id: DeviceId::from(0),
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
phase: TouchPhase::Started,
|
||||
location: location.to_physical(scale_factor),
|
||||
force: None,
|
||||
@@ -78,7 +79,9 @@ impl TouchHandler for WinitState {
|
||||
|
||||
self.events_sink.push_window_event(
|
||||
WindowEvent::Touch(Touch {
|
||||
device_id: DeviceId::from(0),
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
phase: TouchPhase::Ended,
|
||||
location: touch_point.location.to_physical(scale_factor),
|
||||
force: None,
|
||||
@@ -115,7 +118,9 @@ impl TouchHandler for WinitState {
|
||||
|
||||
self.events_sink.push_window_event(
|
||||
WindowEvent::Touch(Touch {
|
||||
device_id: DeviceId::from(0),
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
phase: TouchPhase::Moved,
|
||||
location: touch_point.location.to_physical(scale_factor),
|
||||
force: None,
|
||||
@@ -139,7 +144,9 @@ impl TouchHandler for WinitState {
|
||||
|
||||
self.events_sink.push_window_event(
|
||||
WindowEvent::Touch(Touch {
|
||||
device_id: DeviceId::from(0),
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
phase: TouchPhase::Cancelled,
|
||||
location,
|
||||
force: None,
|
||||
@@ -60,7 +60,7 @@ pub struct WinitState {
|
||||
/// The pool where custom cursors are allocated.
|
||||
pub custom_cursor_pool: Arc<Mutex<SlotPool>>,
|
||||
|
||||
/// The XDG shell that is used for widnows.
|
||||
/// The XDG shell that is used for windows.
|
||||
pub xdg_shell: XdgShell,
|
||||
|
||||
/// The currently present windows.
|
||||
@@ -72,7 +72,7 @@ pub struct WinitState {
|
||||
/// The events that were generated directly from the window.
|
||||
pub window_events_sink: Arc<Mutex<EventSink>>,
|
||||
|
||||
/// The update for the `windows` comming from the compositor.
|
||||
/// The update for the `windows` coming from the compositor.
|
||||
pub window_compositor_updates: Vec<WindowCompositorUpdate>,
|
||||
|
||||
/// Currently handled seats.
|
||||
@@ -133,7 +133,7 @@ impl WinitState {
|
||||
) {
|
||||
Ok(c) => Some(c),
|
||||
Err(e) => {
|
||||
log::warn!("Subcompositor protocol not available, ignoring CSD: {e:?}");
|
||||
tracing::warn!("Subcompositor protocol not available, ignoring CSD: {e:?}");
|
||||
None
|
||||
}
|
||||
};
|
||||
@@ -395,7 +395,7 @@ impl ProvidesRegistryState for WinitState {
|
||||
sctk::registry_handlers![OutputState, SeatState];
|
||||
}
|
||||
|
||||
// The window update comming from the compositor.
|
||||
// The window update coming from the compositor.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct WindowCompositorUpdate {
|
||||
/// The id of the window this updates belongs to.
|
||||
@@ -18,7 +18,8 @@ use sctk::globals::GlobalData;
|
||||
|
||||
use crate::event_loop::AsyncRequestSerial;
|
||||
use crate::platform_impl::wayland::state::WinitState;
|
||||
use crate::window::{ActivationToken, WindowId};
|
||||
use crate::platform_impl::WindowId;
|
||||
use crate::window::ActivationToken;
|
||||
|
||||
pub struct XdgActivationState {
|
||||
xdg_activation: XdgActivationV1,
|
||||
@@ -82,7 +83,7 @@ impl Dispatch<XdgActivationTokenV1, XdgActivationTokenData, WinitState> for XdgA
|
||||
state.events_sink.push_window_event(
|
||||
crate::event::WindowEvent::ActivationTokenDone {
|
||||
serial: *serial,
|
||||
token: ActivationToken::new(token),
|
||||
token: ActivationToken::_new(token),
|
||||
},
|
||||
*window_id,
|
||||
);
|
||||
@@ -3,7 +3,6 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use sctk::reexports::calloop;
|
||||
use sctk::reexports::client::protocol::wl_display::WlDisplay;
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use sctk::reexports::client::Proxy;
|
||||
@@ -15,7 +14,7 @@ use sctk::shell::xdg::window::Window as SctkWindow;
|
||||
use sctk::shell::xdg::window::WindowDecorations;
|
||||
use sctk::shell::WaylandSurface;
|
||||
|
||||
use log::warn;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size};
|
||||
use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError};
|
||||
@@ -33,7 +32,7 @@ use super::event_loop::sink::EventSink;
|
||||
use super::output::MonitorHandle;
|
||||
use super::state::WinitState;
|
||||
use super::types::xdg_activation::XdgActivationTokenData;
|
||||
use super::{EventLoopWindowTarget, WaylandError, WindowId};
|
||||
use super::{ActiveEventLoop, WaylandError, WindowId};
|
||||
|
||||
pub(crate) mod state;
|
||||
|
||||
@@ -81,7 +80,7 @@ pub struct Window {
|
||||
|
||||
impl Window {
|
||||
pub(crate) fn new(
|
||||
event_loop_window_target: &EventLoopWindowTarget,
|
||||
event_loop_window_target: &ActiveEventLoop,
|
||||
attributes: WindowAttributes,
|
||||
) -> Result<Self, RootOsError> {
|
||||
let queue_handle = event_loop_window_target.queue_handle.clone();
|
||||
@@ -177,7 +176,7 @@ impl Window {
|
||||
xdg_activation.as_ref(),
|
||||
attributes.platform_specific.activation_token,
|
||||
) {
|
||||
xdg_activation.activate(token.into_token(), &surface);
|
||||
xdg_activation.activate(token._token, &surface);
|
||||
}
|
||||
|
||||
// XXX Do initial commit.
|
||||
@@ -758,3 +757,23 @@ impl WindowRequests {
|
||||
self.redraw_requested.swap(false, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for Theme {
|
||||
type Error = ();
|
||||
|
||||
/// ```
|
||||
/// use winit::window::Theme;
|
||||
///
|
||||
/// assert_eq!("dark".try_into(), Ok(Theme::Dark));
|
||||
/// assert_eq!("lIghT".try_into(), Ok(Theme::Light));
|
||||
/// ```
|
||||
fn try_from(theme: &str) -> Result<Self, Self::Error> {
|
||||
if theme.eq_ignore_ascii_case("dark") {
|
||||
Ok(Self::Dark)
|
||||
} else if theme.eq_ignore_ascii_case("light") {
|
||||
Ok(Self::Light)
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||