mirror of
https://github.com/rust-windowing/winit.git
synced 2026-06-26 22:53:15 -04:00
Compare commits
101 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d18afb4a50 | ||
|
|
fc336a76bf | ||
|
|
b9f3d333e4 | ||
|
|
3d85af04be | ||
|
|
471b1e003a | ||
|
|
be2e17d605 | ||
|
|
9d6b9797c0 | ||
|
|
3cd6a18048 | ||
|
|
c9558c5f0e | ||
|
|
71e3d25422 | ||
|
|
644dc13e00 | ||
|
|
47e7aa4209 | ||
|
|
1c97a310b1 | ||
|
|
d612a1b5a1 | ||
|
|
386ead15a3 | ||
|
|
83c95e774d | ||
|
|
e4754999b7 | ||
|
|
c66489dbb1 | ||
|
|
21f9aefc7e | ||
|
|
d103dc2631 | ||
|
|
cac627ed05 | ||
|
|
e2cf2a5754 | ||
|
|
658a9a4ea8 | ||
|
|
a2db4c0a32 | ||
|
|
02a34a167a | ||
|
|
bea60930b6 | ||
|
|
0f7c82d38f | ||
|
|
6ba583d198 | ||
|
|
89d4c06dec | ||
|
|
9c72cc2a98 | ||
|
|
412bd94ea4 | ||
|
|
514ab043f2 | ||
|
|
68100102be | ||
|
|
05fdcb5b27 | ||
|
|
7a49c88200 | ||
|
|
40232d48ba | ||
|
|
55dff53a98 | ||
|
|
6919c2fb2d | ||
|
|
3d5d05eac7 | ||
|
|
dd866a74a6 | ||
|
|
b1e22aa559 | ||
|
|
2191e9ecd5 | ||
|
|
bf62103417 | ||
|
|
4b1b314ce2 | ||
|
|
c1ea0dde92 | ||
|
|
5a6cfc314e | ||
|
|
a4121a2c2e | ||
|
|
03335cef85 | ||
|
|
ff66bdda7c | ||
|
|
6cfddfea21 | ||
|
|
49bcec1d27 | ||
|
|
878c179761 | ||
|
|
bc19c04339 | ||
|
|
c7a33f926b | ||
|
|
3c38afdb47 | ||
|
|
b8828105cf | ||
|
|
007b195a5e | ||
|
|
b4c6cdf9a3 | ||
|
|
26775fa0b6 | ||
|
|
114fe9d502 | ||
|
|
54bc41f68b | ||
|
|
47ff8d61d1 | ||
|
|
849b8f5dce | ||
|
|
aabe42d252 | ||
|
|
78a62ec547 | ||
|
|
6dae994bb4 | ||
|
|
4c4d0916fd | ||
|
|
d5609729cc | ||
|
|
1f24a09570 | ||
|
|
a8e777a5df | ||
|
|
0bc58f695b | ||
|
|
28023d9f5b | ||
|
|
c2aed1979d | ||
|
|
7e04273719 | ||
|
|
0683bdcd42 | ||
|
|
29ab0bb629 | ||
|
|
7a9c17a520 | ||
|
|
b208daa271 | ||
|
|
e85a80dd65 | ||
|
|
b1d8ce24e9 | ||
|
|
098fd5d602 | ||
|
|
2f27f64cdb | ||
|
|
cbb60d29a2 | ||
|
|
e707052f66 | ||
|
|
71bd6e73ca | ||
|
|
b8326f6452 | ||
|
|
ece2e70a53 | ||
|
|
2b14ec23d5 | ||
|
|
9999f53329 | ||
|
|
522a6e3298 | ||
|
|
76d0dd7ec3 | ||
|
|
d1073dcecb | ||
|
|
e88e8bc194 | ||
|
|
bc29931434 | ||
|
|
505f312d5f | ||
|
|
f0093d3c54 | ||
|
|
83b60beba6 | ||
|
|
5f52d7c9d0 | ||
|
|
a1b65f7080 | ||
|
|
96df858961 | ||
|
|
4eddd1e5bc |
41
.github/workflows/ci.yml
vendored
41
.github/workflows/ci.yml
vendored
@@ -17,7 +17,7 @@ jobs:
|
||||
Check_Formatting:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v2
|
||||
- uses: hecrj/setup-rust-action@v1
|
||||
with:
|
||||
rust-version: stable
|
||||
@@ -37,24 +37,28 @@ jobs:
|
||||
- { target: i686-pc-windows-gnu, os: windows-latest, host: -i686-pc-windows-gnu }
|
||||
- { target: i686-unknown-linux-gnu, os: ubuntu-latest, }
|
||||
- { target: x86_64-unknown-linux-gnu, os: ubuntu-latest, }
|
||||
- { target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: --no-default-features, features: x11 }
|
||||
- { target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: --no-default-features, features: wayland }
|
||||
- { target: aarch64-linux-android, os: ubuntu-latest, cmd: 'apk --' }
|
||||
- { target: x86_64-apple-darwin, os: macos-latest, }
|
||||
- { target: x86_64-apple-ios, os: macos-latest, }
|
||||
- { target: aarch64-apple-ios, os: macos-latest, }
|
||||
# We're using Windows rather than Ubuntu to run the wasm tests because caching cargo-web
|
||||
# doesn't currently work on Linux.
|
||||
- { target: wasm32-unknown-unknown, os: windows-latest, features: stdweb, web: web }
|
||||
- { target: wasm32-unknown-unknown, os: windows-latest, features: web-sys, web: web }
|
||||
- { target: wasm32-unknown-unknown, os: windows-latest, features: stdweb, cmd: web }
|
||||
- { target: wasm32-unknown-unknown, os: windows-latest, features: web-sys, cmd: web }
|
||||
|
||||
env:
|
||||
RUST_BACKTRACE: 1
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUSTFLAGS: "-C debuginfo=0"
|
||||
OPTIONS: ${{ matrix.platform.options }}
|
||||
FEATURES: ${{ format(',{0}', matrix.platform.features ) }}
|
||||
WEB: ${{ matrix.platform.web }}
|
||||
CMD: ${{ matrix.platform.cmd }}
|
||||
|
||||
runs-on: ${{ matrix.platform.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v2
|
||||
# Used to cache cargo-web
|
||||
- name: Cache cargo folder
|
||||
uses: actions/cache@v1
|
||||
@@ -70,6 +74,9 @@ jobs:
|
||||
- name: Install GCC Multilib
|
||||
if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
|
||||
run: sudo apt-get update && sudo apt-get install gcc-multilib
|
||||
- name: Install cargo-apk
|
||||
if: contains(matrix.platform.target, 'android')
|
||||
run: cargo install cargo-apk
|
||||
- name: Install cargo-web
|
||||
continue-on-error: true
|
||||
if: contains(matrix.platform.target, 'wasm32')
|
||||
@@ -78,29 +85,35 @@ jobs:
|
||||
- name: Check documentation
|
||||
shell: bash
|
||||
if: matrix.platform.target != 'wasm32-unknown-unknown'
|
||||
run: cargo doc --no-deps --target ${{ matrix.platform.target }} --features $FEATURES
|
||||
run: cargo $CMD doc --no-deps --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
run: cargo $WEB build --verbose --target ${{ matrix.platform.target }} --features $FEATURES
|
||||
run: cargo $CMD build --verbose --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES
|
||||
|
||||
- name: Build tests
|
||||
shell: bash
|
||||
run: cargo $WEB test --no-run --verbose --target ${{ matrix.platform.target }} --features $FEATURES
|
||||
run: cargo $CMD test --no-run --verbose --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES
|
||||
- name: Run tests
|
||||
shell: bash
|
||||
if: (!contains(matrix.platform.target, 'ios') && !contains(matrix.platform.target, 'wasm32'))
|
||||
run: cargo $WEB test --verbose --target ${{ matrix.platform.target }} --features $FEATURES
|
||||
if: (
|
||||
!contains(matrix.platform.target, 'android') &&
|
||||
!contains(matrix.platform.target, 'ios') &&
|
||||
!contains(matrix.platform.target, 'wasm32'))
|
||||
run: cargo $CMD test --verbose --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES
|
||||
|
||||
|
||||
- name: Build with serde enabled
|
||||
shell: bash
|
||||
run: cargo $WEB build --verbose --target ${{ matrix.platform.target }} --features serde,$FEATURES
|
||||
run: cargo $CMD build --verbose --target ${{ matrix.platform.target }} $OPTIONS --features serde,$FEATURES
|
||||
|
||||
- name: Build tests with serde enabled
|
||||
shell: bash
|
||||
run: cargo $WEB test --no-run --verbose --target ${{ matrix.platform.target }} --features serde,$FEATURES
|
||||
run: cargo $CMD test --no-run --verbose --target ${{ matrix.platform.target }} $OPTIONS --features serde,$FEATURES
|
||||
- name: Run tests with serde enabled
|
||||
shell: bash
|
||||
if: (!contains(matrix.platform.target, 'ios') && !contains(matrix.platform.target, 'wasm32'))
|
||||
run: cargo $WEB test --verbose --target ${{ matrix.platform.target }} --features serde,$FEATURES
|
||||
if: (
|
||||
!contains(matrix.platform.target, 'android') &&
|
||||
!contains(matrix.platform.target, 'ios') &&
|
||||
!contains(matrix.platform.target, 'wasm32'))
|
||||
run: cargo $CMD test --verbose --target ${{ matrix.platform.target }} $OPTIONS --features serde,$FEATURES
|
||||
|
||||
2
.github/workflows/publish.yml
vendored
2
.github/workflows/publish.yml
vendored
@@ -9,7 +9,7 @@ jobs:
|
||||
Publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v2
|
||||
- uses: hecrj/setup-rust-action@v1
|
||||
with:
|
||||
rust-version: stable
|
||||
|
||||
106
CHANGELOG.md
106
CHANGELOG.md
@@ -1,5 +1,110 @@
|
||||
# Unreleased
|
||||
|
||||
# 0.23.0 (2020-10-02)
|
||||
|
||||
- On iOS, fixed support for the "Debug View Heirarchy" feature in Xcode.
|
||||
- On all platforms, `available_monitors` and `primary_monitor` are now on `EventLoopWindowTarget` rather than `EventLoop` to list monitors event in the event loop.
|
||||
- On Unix, X11 and Wayland are now optional features (enabled by default)
|
||||
- On X11, fix deadlock when calling `set_fullscreen_inner`.
|
||||
- On Web, prevent the webpage from scrolling when the user is focused on a winit canvas
|
||||
- On Web, calling `window.set_cursor_icon` no longer breaks HiDPI scaling
|
||||
- On Windows, drag and drop is now optional and must be enabled with `WindowBuilderExtWindows::with_drag_and_drop(true)`.
|
||||
- On Wayland, fix deadlock when calling to `set_inner_size` from a callback.
|
||||
- On macOS, add `hide__other_applications` to `EventLoopWindowTarget` via existing `EventLoopWindowTargetExtMacOS` trait. `hide_other_applications` will hide other applications by calling `-[NSApplication hideOtherApplications: nil]`.
|
||||
- On android added support for `run_return`.
|
||||
- On MacOS, Fixed fullscreen and dialog support for `run_return`.
|
||||
- On Windows, fix bug where we'd try to emit `MainEventsCleared` events during nested win32 event loops.
|
||||
- On Web, use mouse events if pointer events aren't supported. This affects Safari.
|
||||
- On Windows, `set_ime_position` is now a no-op instead of a runtime crash.
|
||||
- On Android, `set_fullscreen` is now a no-op instead of a runtime crash.
|
||||
- On iOS and Android, `set_inner_size` is now a no-op instead of a runtime crash.
|
||||
- On Android, fix `ControlFlow::Poll` not polling the Android event queue.
|
||||
- On macOS, add `NSWindow.hasShadow` support.
|
||||
- On Web, fix vertical mouse wheel scrolling being inverted.
|
||||
- On Web, implement mouse capturing for click-dragging out of the canvas.
|
||||
- On Web, fix `ControlFlow::Exit` not properly handled.
|
||||
- On Web (web-sys only), send `WindowEvent::ScaleFactorChanged` event when `window.devicePixelRatio` is changed.
|
||||
- **Breaking:** On Web, `set_cursor_position` and `set_cursor_grab` will now always return an error.
|
||||
- **Breaking:** `PixelDelta` scroll events now return a `PhysicalPosition`.
|
||||
- On NetBSD, fixed crash due to incorrect detection of the main thread.
|
||||
- **Breaking:** On X11, `-` key is mapped to the `Minus` virtual key code, instead of `Subtract`.
|
||||
- On macOS, fix inverted horizontal scroll.
|
||||
- **Breaking:** `current_monitor` now returns `Option<MonitorHandle>`.
|
||||
- **Breaking:** `primary_monitor` now returns `Option<MonitorHandle>`.
|
||||
- On macOS, updated core-* dependencies and cocoa.
|
||||
- Bump `parking_lot` to 0.11
|
||||
- On Android, bump `ndk`, `ndk-sys` and `ndk-glue` to 0.2. Checkout the new ndk-glue main proc attribute.
|
||||
- On iOS, fixed starting the app in landscape where the view still had portrait dimensions.
|
||||
- Deprecate the stdweb backend, to be removed in a future release
|
||||
- **Breaking:** Prefixed virtual key codes `Add`, `Multiply`, `Divide`, `Decimal`, and `Subtract` with `Numpad`.
|
||||
- Added `Asterisk` and `Plus` virtual key codes.
|
||||
- On Web (web-sys only), the `Event::LoopDestroyed` event is correctly emitted when leaving the page.
|
||||
- On Web, the `WindowEvent::Destroyed` event now gets emitted when a `Window` is dropped.
|
||||
- On Web (web-sys only), the event listeners are now removed when a `Window` is dropped or when the event loop is destroyed.
|
||||
- On Web, the event handler closure passed to `EventLoop::run` now gets dropped after the event loop is destroyed.
|
||||
- **Breaking:** On Web, the canvas element associated to a `Window` is no longer removed from the DOM when the `Window` is dropped.
|
||||
- On Web, `WindowEvent::Resized` is now emitted when `Window::set_inner_size` is called.
|
||||
- **Breaking:** `Fullscreen` enum now uses `Borderless(Option<MonitorHandle>)` instead of `Borderless(MonitorHandle)` to allow picking the current monitor.
|
||||
- On MacOS, fix `WindowEvent::Moved` ignoring the scale factor.
|
||||
- On Wayland, add missing virtual keycodes.
|
||||
- On Wayland, implement proper `set_cursor_grab`.
|
||||
- On Wayland, the cursor will use similar icons if the requested one isn't available.
|
||||
- On Wayland, right clicking on client side decorations will request application menu.
|
||||
- On Wayland, fix tracking of window size after state changes.
|
||||
- On Wayland, fix client side decorations not being hidden properly in fullscreen.
|
||||
- On Wayland, fix incorrect size event when entering fullscreen with client side decorations.
|
||||
- On Wayland, fix `resizable` attribute not being applied properly on startup.
|
||||
- On Wayland, fix disabled repeat rate not being handled.
|
||||
- On Wayland, fix decoration buttons not working after tty switch.
|
||||
- On Wayland, fix scaling not being applied on output re-enable.
|
||||
- On Wayland, fix crash when `XCURSOR_SIZE` is `0`.
|
||||
- On Wayland, fix pointer getting created in some cases without pointer capability.
|
||||
- On Wayland, on kwin, fix space between window and decorations on startup.
|
||||
- **Breaking:** On Wayland, `Theme` trait was reworked.
|
||||
- On Wayland, disable maximize button for non-resizable window.
|
||||
- On Wayland, added support for `set_ime_position`.
|
||||
- On Wayland, fix crash on startup since GNOME 3.37.90.
|
||||
- On X11, fix incorrect modifiers state on startup.
|
||||
|
||||
# 0.22.2 (2020-05-16)
|
||||
|
||||
- Added Clone implementation for 'static events.
|
||||
- On Windows, fix window intermittently hanging when `ControlFlow` was set to `Poll`.
|
||||
- On Windows, fix `WindowBuilder::with_maximized` being ignored.
|
||||
- On Android, minimal platform support.
|
||||
- On iOS, touch positions are now properly converted to physical pixels.
|
||||
- On macOS, updated core-* dependencies and cocoa
|
||||
|
||||
# 0.22.1 (2020-04-16)
|
||||
|
||||
- On X11, fix `ResumeTimeReached` being fired too early.
|
||||
- On Web, replaced zero timeout for `ControlFlow::Poll` with `requestAnimationFrame`
|
||||
- On Web, fix a possible panic during event handling
|
||||
- On macOS, fix `EventLoopProxy` leaking memory for every instance.
|
||||
- On Windows, drag and drop can now be disabled with `WindowBuilderExtWindows::with_drag_and_drop(false)`.
|
||||
|
||||
# 0.22.0 (2020-03-09)
|
||||
|
||||
- On Windows, fix minor timing issue in wait_until_time_or_msg
|
||||
- On Windows, rework handling of request_redraw() to address panics.
|
||||
- On macOS, fix `set_simple_screen` to remember frame excluding title bar.
|
||||
- On Wayland, fix coordinates in touch events when scale factor isn't 1.
|
||||
- On Wayland, fix color from `close_button_icon_color` not applying.
|
||||
- Ignore locale if unsupported by X11 backend
|
||||
- On Wayland, Add HiDPI cursor support
|
||||
- On Web, add the ability to query "Light" or "Dark" system theme send `ThemeChanged` on change.
|
||||
- Fix `Event::to_static` returning `None` for user events.
|
||||
- On Wayland, Hide CSD for fullscreen windows.
|
||||
- On Windows, ignore spurious mouse move messages.
|
||||
- **Breaking:** Move `ModifiersChanged` variant from `DeviceEvent` to `WindowEvent`.
|
||||
- On Windows, add `IconExtWindows` trait which exposes creating an `Icon` from an external file or embedded resource
|
||||
- Add `BadIcon::OsError` variant for when OS icon functionality fails
|
||||
- On Windows, fix crash at startup on systems that do not properly support Windows' Dark Mode
|
||||
- Revert On macOS, fix not sending ReceivedCharacter event for specific keys combinations.
|
||||
- on macOS, fix incorrect ReceivedCharacter events for some key combinations.
|
||||
- **Breaking:** Use `i32` instead of `u32` for position type in `WindowEvent::Moved`.
|
||||
- On macOS, a mouse motion event is now generated before every mouse click.
|
||||
|
||||
# 0.21.0 (2020-02-04)
|
||||
|
||||
- On Windows, fixed "error: linking with `link.exe` failed: exit code: 1120" error on older versions of windows.
|
||||
@@ -20,7 +125,6 @@
|
||||
# 0.20.0 (2020-01-05)
|
||||
|
||||
- On X11, fix `ModifiersChanged` emitting incorrect modifier change events
|
||||
|
||||
- **Breaking**: Overhaul how Winit handles DPI:
|
||||
+ Window functions and events now return `PhysicalSize` instead of `LogicalSize`.
|
||||
+ Functions that take `Size` or `Position` types can now take either `Logical` or `Physical` types.
|
||||
|
||||
40
Cargo.toml
40
Cargo.toml
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "winit"
|
||||
version = "0.21.0"
|
||||
version = "0.23.0"
|
||||
authors = ["The winit contributors", "Pierre Krieger <pierre.krieger1708@gmail.com>"]
|
||||
description = "Cross-platform window creation library."
|
||||
edition = "2018"
|
||||
@@ -12,11 +12,16 @@ documentation = "https://docs.rs/winit"
|
||||
categories = ["gui"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["serde"]
|
||||
features = ["serde", "web-sys"]
|
||||
default-target = "x86_64-unknown-linux-gnu"
|
||||
targets = ["i686-pc-windows-msvc", "x86_64-pc-windows-msvc", "i686-unknown-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-apple-darwin", "wasm32-unknown-unknown"]
|
||||
|
||||
[features]
|
||||
default = ["x11", "wayland"]
|
||||
web-sys = ["web_sys", "wasm-bindgen", "instant/wasm-bindgen"]
|
||||
stdweb = ["std_web", "instant/stdweb"]
|
||||
x11 = ["x11-dl"]
|
||||
wayland = ["wayland-client", "sctk"]
|
||||
|
||||
[dependencies]
|
||||
instant = "0.1"
|
||||
@@ -28,24 +33,26 @@ raw-window-handle = "0.3"
|
||||
bitflags = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
image = "0.21"
|
||||
simple_logger = "1"
|
||||
image = "0.23"
|
||||
simple_logger = "1.9"
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies.android_glue]
|
||||
version = "0.2"
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
ndk = "0.2.0"
|
||||
ndk-sys = "0.2.0"
|
||||
ndk-glue = "0.2.0"
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
objc = "0.2.3"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
cocoa = "0.19.1"
|
||||
core-foundation = "0.6"
|
||||
core-graphics = "0.17.3"
|
||||
cocoa = "0.23"
|
||||
core-foundation = "0.9"
|
||||
core-graphics = "0.22"
|
||||
dispatch = "0.2.0"
|
||||
objc = "0.2.6"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies.core-video-sys]
|
||||
version = "0.1.3"
|
||||
version = "0.1.4"
|
||||
default_features = false
|
||||
features = ["display_link"]
|
||||
|
||||
@@ -74,15 +81,15 @@ features = [
|
||||
]
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies]
|
||||
wayland-client = { version = "0.23.0", features = [ "dlopen", "egl", "cursor", "eventloop"] }
|
||||
wayland-client = { version = "0.28", features = [ "dlopen"] , optional = true }
|
||||
sctk = { package = "smithay-client-toolkit", version = "0.12", optional = true }
|
||||
mio = "0.6"
|
||||
mio-extras = "2.0"
|
||||
smithay-client-toolkit = "0.6"
|
||||
x11-dl = "2.18.3"
|
||||
x11-dl = { version = "2.18.5", optional = true }
|
||||
percent-encoding = "2.0"
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "windows"))'.dependencies.parking_lot]
|
||||
version = "0.10"
|
||||
version = "0.11"
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies.web_sys]
|
||||
package = "web-sys"
|
||||
@@ -90,6 +97,7 @@ version = "0.3.22"
|
||||
optional = true
|
||||
features = [
|
||||
'console',
|
||||
"AddEventListenerOptions",
|
||||
'CssStyleDeclaration',
|
||||
'BeforeUnloadEvent',
|
||||
'Document',
|
||||
@@ -101,6 +109,8 @@ features = [
|
||||
'HtmlCanvasElement',
|
||||
'HtmlElement',
|
||||
'KeyboardEvent',
|
||||
'MediaQueryList',
|
||||
'MediaQueryListEvent',
|
||||
'MouseEvent',
|
||||
'Node',
|
||||
'PointerEvent',
|
||||
@@ -119,4 +129,4 @@ optional = true
|
||||
features = ["experimental_features_which_may_break_on_minor_version_bumps"]
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
|
||||
console_log = "0.1"
|
||||
console_log = "0.2"
|
||||
|
||||
17
FEATURES.md
17
FEATURES.md
@@ -109,8 +109,8 @@ If your PR makes notable changes to Winit's features, please update this section
|
||||
translating keypresses into UTF-8 characters, handling dead keys and IMEs.
|
||||
- **Drag & Drop**: Dragging content into winit, detecting when content enters, drops, or if the drop is cancelled.
|
||||
- **Raw Device Events**: Capturing input from input devices without any OS filtering.
|
||||
- **Gamepad/Joystick events**: Capturing input from gampads and joysticks.
|
||||
- **Device movement events:**: Capturing input from the device gyroscope and accelerometer.
|
||||
- **Gamepad/Joystick events**: Capturing input from gamepads and joysticks.
|
||||
- **Device movement events**: Capturing input from the device gyroscope and accelerometer.
|
||||
|
||||
## Platform
|
||||
### Windows
|
||||
@@ -149,6 +149,9 @@ If your PR makes notable changes to Winit's features, please update this section
|
||||
* Getting the device idiom
|
||||
* Getting the preferred video mode
|
||||
|
||||
### Web
|
||||
* Get if systems preferred color scheme is "dark"
|
||||
|
||||
## Usability
|
||||
* `serde`: Enables serialization/deserialization of certain types with Serde. (Maintainer: @Osspial)
|
||||
|
||||
@@ -179,9 +182,11 @@ Legend:
|
||||
|Fullscreen |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |
|
||||
|Fullscreen toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |
|
||||
|Exclusive fullscreen |✔️ |✔️ |✔️ |**N/A** |❌ |✔️ |**N/A**|
|
||||
|HiDPI support |✔️ |✔️ |✔️ |✔️ |▢[#721]|✔️ |**N/A**|
|
||||
|HiDPI support |✔️ |✔️ |✔️ |✔️ |▢[#721]|✔️ |✔️ \*1|
|
||||
|Popup windows |❌ |❌ |❌ |❌ |❌ |❌ |**N/A**|
|
||||
|
||||
\*1: `WindowEvent::ScaleFactorChanged` is not sent on `stdweb` backend.
|
||||
|
||||
### System information
|
||||
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |WASM |
|
||||
|---------------- | ----- | ---- | ------- | ----------- | ----- | ------- | -------- |
|
||||
@@ -195,9 +200,9 @@ Legend:
|
||||
|Mouse set location |✔️ |✔️ |✔️ |❓ |**N/A**|**N/A**|**N/A**|
|
||||
|Cursor grab |✔️ |▢[#165] |▢[#242] |✔️ |**N/A**|**N/A**|❓ |
|
||||
|Cursor icon |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |
|
||||
|Touch events |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |✔️ |
|
||||
|Touch pressure |✔️ |❌ |❌ |❌ |❌ |✔️ |✔️ |
|
||||
|Multitouch |✔️ |❌ |✔️ |✔️ |❓ |✔️ |✔️ |
|
||||
|Touch events |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |❌ |
|
||||
|Touch pressure |✔️ |❌ |❌ |❌ |❌ |✔️ |❌ |
|
||||
|Multitouch |✔️ |❌ |✔️ |✔️ |❓ |✔️ |❌ |
|
||||
|Keyboard events |✔️ |✔️ |✔️ |✔️ |❓ |❌ |✔️ |
|
||||
|Drag & Drop |▢[#720] |▢[#720] |▢[#720] |❌[#306] |**N/A**|**N/A**|❓ |
|
||||
|Raw Device Events |▢[#750] |▢[#750] |▢[#750] |❌ |❌ |❌ |❓ |
|
||||
|
||||
51
README.md
51
README.md
@@ -2,12 +2,11 @@
|
||||
|
||||
[](https://crates.io/crates/winit)
|
||||
[](https://docs.rs/winit)
|
||||
[](https://travis-ci.org/rust-windowing/winit)
|
||||
[](https://ci.appveyor.com/project/Osspial/winit/branch/master)
|
||||
[](https://github.com/rust-windowing/winit/actions)
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
winit = "0.21.0"
|
||||
winit = "0.23.0"
|
||||
```
|
||||
|
||||
## [Documentation](https://docs.rs/winit)
|
||||
@@ -65,15 +64,49 @@ Winit is only officially supported on the latest stable version of the Rust comp
|
||||
|
||||
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
|
||||
|
||||
### Platform-specific usage
|
||||
|
||||
#### WebAssembly
|
||||
|
||||
Building a binary will yield a `.js` file. In order to use it in an HTML file, you need to:
|
||||
Winit supports compiling to the `wasm32-unknown-unknown` target with either a
|
||||
`stdweb` or a `web-sys` backend for use on web browsers. However, please note
|
||||
that **the `stdweb` backend is being deprecated and may be removed in a future
|
||||
release of Winit**. The `web-sys` backend is also more feature complete.
|
||||
|
||||
- Put a `<canvas id="my_id"></canvas>` element somewhere. A canvas corresponds to a winit "window".
|
||||
- Write a Javascript code that creates a global variable named `Module`. Set `Module.canvas` to
|
||||
the element of the `<canvas>` element (in the example you would retrieve it via `document.getElementById("my_id")`).
|
||||
More information [here](https://kripken.github.io/emscripten-site/docs/api_reference/module.html).
|
||||
- Make sure that you insert the `.js` file generated by Rust after the `Module` variable is created.
|
||||
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 example code using Winit with WebAssembly, 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
|
||||
|
||||
This library makes use of the [ndk-rs](https://github.com/rust-windowing/android-ndk-rs) crates, refer to that repo for more documentation.
|
||||
|
||||
Running on an Android device needs a dynamic system library, add this to Cargo.toml:
|
||||
```toml
|
||||
[[example]]
|
||||
name = "request_redraw_threaded"
|
||||
crate-type = ["cdylib"]
|
||||
```
|
||||
|
||||
And add this to the example file to add the native activity glue:
|
||||
```rust
|
||||
#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "on"))]
|
||||
fn main() {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
And run the application with `cargo apk run --example request_redraw_threaded`
|
||||
|
||||
21
build.rs
Normal file
21
build.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
#[cfg(all(
|
||||
any(
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
),
|
||||
not(feature = "x11"),
|
||||
not(feature = "wayland")
|
||||
))]
|
||||
compile_error!("at least one of the \"x11\"/\"wayland\" features must be enabled");
|
||||
|
||||
#[cfg(all(
|
||||
target_arch = "wasm32",
|
||||
not(feature = "web-sys"),
|
||||
not(feature = "stdweb")
|
||||
))]
|
||||
compile_error!("at least one of the \"web-sys\"/\"stdweb\" features must be enabled");
|
||||
|
||||
fn main() {}
|
||||
114
examples/control_flow.rs
Normal file
114
examples/control_flow.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
use std::{thread, time};
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, KeyboardInput, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
window::WindowBuilder,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
Wait,
|
||||
WaitUntil,
|
||||
Poll,
|
||||
}
|
||||
|
||||
const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
|
||||
const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);
|
||||
|
||||
fn main() {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
|
||||
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();
|
||||
let window = WindowBuilder::new()
|
||||
.with_title("Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut mode = Mode::Wait;
|
||||
let mut request_redraw = false;
|
||||
let mut wait_cancelled = false;
|
||||
let mut close_requested = false;
|
||||
|
||||
event_loop.run(move |event, _, control_flow| {
|
||||
use winit::event::{ElementState, StartCause, VirtualKeyCode};
|
||||
println!("{:?}", event);
|
||||
match event {
|
||||
Event::NewEvents(start_cause) => {
|
||||
wait_cancelled = match start_cause {
|
||||
StartCause::WaitCancelled { .. } => mode == Mode::WaitUntil,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
Event::WindowEvent { event, .. } => match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
close_requested = true;
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
input:
|
||||
KeyboardInput {
|
||||
virtual_keycode: Some(virtual_code),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => match virtual_code {
|
||||
VirtualKeyCode::Key1 => {
|
||||
mode = Mode::Wait;
|
||||
println!("\nmode: {:?}\n", mode);
|
||||
}
|
||||
VirtualKeyCode::Key2 => {
|
||||
mode = Mode::WaitUntil;
|
||||
println!("\nmode: {:?}\n", mode);
|
||||
}
|
||||
VirtualKeyCode::Key3 => {
|
||||
mode = Mode::Poll;
|
||||
println!("\nmode: {:?}\n", mode);
|
||||
}
|
||||
VirtualKeyCode::R => {
|
||||
request_redraw = !request_redraw;
|
||||
println!("\nrequest_redraw: {}\n", request_redraw);
|
||||
}
|
||||
VirtualKeyCode::Escape => {
|
||||
close_requested = true;
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
_ => (),
|
||||
},
|
||||
Event::MainEventsCleared => {
|
||||
if request_redraw && !wait_cancelled && !close_requested {
|
||||
window.request_redraw();
|
||||
}
|
||||
if close_requested {
|
||||
*control_flow = ControlFlow::Exit;
|
||||
}
|
||||
}
|
||||
Event::RedrawRequested(_window_id) => {}
|
||||
Event::RedrawEventsCleared => {
|
||||
*control_flow = match mode {
|
||||
Mode::Wait => ControlFlow::Wait,
|
||||
Mode::WaitUntil => {
|
||||
if wait_cancelled {
|
||||
*control_flow
|
||||
} else {
|
||||
ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME)
|
||||
}
|
||||
}
|
||||
Mode::Poll => {
|
||||
thread::sleep(POLL_SLEEP_TIME);
|
||||
ControlFlow::Poll
|
||||
}
|
||||
};
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyboardInput, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -5,7 +6,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let window = WindowBuilder::new().build(&event_loop).unwrap();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{DeviceEvent, ElementState, Event, KeyboardInput, ModifiersState, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -5,7 +6,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let window = WindowBuilder::new()
|
||||
@@ -38,6 +39,7 @@ fn main() {
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
WindowEvent::ModifiersChanged(m) => modifiers = m,
|
||||
_ => (),
|
||||
},
|
||||
Event::DeviceEvent { event, .. } => match event {
|
||||
@@ -46,7 +48,6 @@ fn main() {
|
||||
ElementState::Pressed => println!("mouse button {} pressed", button),
|
||||
ElementState::Released => println!("mouse button {} released", button),
|
||||
},
|
||||
DeviceEvent::ModifiersChanged(m) => modifiers = m,
|
||||
_ => (),
|
||||
},
|
||||
_ => (),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() {
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -11,7 +12,7 @@ fn main() {
|
||||
Timer,
|
||||
}
|
||||
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::<CustomEvent>::with_user_event();
|
||||
|
||||
let _window = WindowBuilder::new()
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use std::io::{stdin, stdout, Write};
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
|
||||
use winit::event_loop::{ControlFlow, EventLoop};
|
||||
use winit::monitor::{MonitorHandle, VideoMode};
|
||||
use winit::window::{Fullscreen, WindowBuilder};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
print!("Please choose the fullscreen mode: (1) exclusive, (2) borderless: ");
|
||||
@@ -17,7 +19,7 @@ fn main() {
|
||||
|
||||
let fullscreen = Some(match num {
|
||||
1 => Fullscreen::Exclusive(prompt_for_video_mode(&prompt_for_monitor(&event_loop))),
|
||||
2 => Fullscreen::Borderless(prompt_for_monitor(&event_loop)),
|
||||
2 => Fullscreen::Borderless(Some(prompt_for_monitor(&event_loop))),
|
||||
_ => panic!("Please enter a valid number"),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, KeyboardInput, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -5,7 +6,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let _window = WindowBuilder::new()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
dpi::LogicalSize,
|
||||
event::{Event, WindowEvent},
|
||||
@@ -6,7 +7,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let window = WindowBuilder::new().build(&event_loop).unwrap();
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
extern crate winit;
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::event::{Event, VirtualKeyCode, WindowEvent};
|
||||
use winit::event_loop::{ControlFlow, EventLoop};
|
||||
use winit::window::WindowBuilder;
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let window = WindowBuilder::new()
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{event_loop::EventLoop, window::WindowBuilder};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
let window = WindowBuilder::new().build(&event_loop).unwrap();
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
fn main() {
|
||||
use std::{collections::HashMap, sync::mpsc, thread, time::Duration};
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
|
||||
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
||||
@@ -12,7 +13,7 @@ fn main() {
|
||||
const WINDOW_COUNT: usize = 3;
|
||||
const WINDOW_SIZE: PhysicalSize<u32> = PhysicalSize::new(600, 400);
|
||||
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
let mut window_senders = HashMap::with_capacity(WINDOW_COUNT);
|
||||
for _ in 0..WINDOW_COUNT {
|
||||
@@ -21,7 +22,7 @@ fn main() {
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut video_modes: Vec<_> = window.current_monitor().video_modes().collect();
|
||||
let mut video_modes: Vec<_> = window.current_monitor().unwrap().video_modes().collect();
|
||||
let mut video_mode_id = 0usize;
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
@@ -34,7 +35,7 @@ fn main() {
|
||||
// was moved to an another monitor, so that the window
|
||||
// appears on this monitor instead when we go fullscreen
|
||||
let previous_video_mode = video_modes.iter().cloned().nth(video_mode_id);
|
||||
video_modes = window.current_monitor().video_modes().collect();
|
||||
video_modes = window.current_monitor().unwrap().video_modes().collect();
|
||||
video_mode_id = video_mode_id.min(video_modes.len());
|
||||
let video_mode = video_modes.iter().nth(video_mode_id);
|
||||
|
||||
@@ -82,9 +83,7 @@ fn main() {
|
||||
);
|
||||
}
|
||||
F => window.set_fullscreen(match (state, modifiers.alt()) {
|
||||
(true, false) => {
|
||||
Some(Fullscreen::Borderless(window.current_monitor()))
|
||||
}
|
||||
(true, false) => Some(Fullscreen::Borderless(None)),
|
||||
(true, true) => Some(Fullscreen::Exclusive(
|
||||
video_modes.iter().nth(video_mode_id).unwrap().clone(),
|
||||
)),
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyboardInput, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -6,7 +8,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let mut windows = HashMap::new();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -5,7 +6,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let window = WindowBuilder::new()
|
||||
|
||||
40
examples/request_redraw_threaded.rs
Normal file
40
examples/request_redraw_threaded.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
use std::{thread, time};
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
window::WindowBuilder,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let window = WindowBuilder::new()
|
||||
.with_title("A fantastic window!")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
thread::spawn(move || loop {
|
||||
thread::sleep(time::Duration::from_secs(1));
|
||||
window.request_redraw();
|
||||
});
|
||||
|
||||
event_loop.run(move |event, _, control_flow| {
|
||||
println!("{:?}", event);
|
||||
|
||||
*control_flow = ControlFlow::Wait;
|
||||
|
||||
match event {
|
||||
Event::WindowEvent { event, .. } => match event {
|
||||
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
|
||||
_ => (),
|
||||
},
|
||||
Event::RedrawRequested(_) => {
|
||||
println!("\nredrawing!\n");
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
dpi::LogicalSize,
|
||||
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
||||
@@ -6,7 +7,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let mut resizable = false;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use instant::Instant;
|
||||
use std::time::Duration;
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, StartCause, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -7,7 +9,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let _window = WindowBuilder::new()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -5,7 +6,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let window = WindowBuilder::new()
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
let monitor = event_loop.primary_monitor();
|
||||
let monitor = match event_loop.primary_monitor() {
|
||||
Some(monitor) => monitor,
|
||||
None => {
|
||||
println!("No primary monitor detected.");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
println!("Listing available video modes:");
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -5,7 +6,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let window = WindowBuilder::new()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// This example is used by developers to test various window functions.
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
dpi::{LogicalSize, PhysicalSize},
|
||||
event::{DeviceEvent, ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
||||
@@ -8,7 +9,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let window = WindowBuilder::new()
|
||||
@@ -20,6 +21,7 @@ fn main() {
|
||||
eprintln!("debugging keys:");
|
||||
eprintln!(" (E) Enter exclusive fullscreen");
|
||||
eprintln!(" (F) Toggle borderless fullscreen");
|
||||
eprintln!(" (P) Toggle borderless fullscreen on system's preffered monitor");
|
||||
eprintln!(" (M) Toggle minimized");
|
||||
eprintln!(" (Q) Quit event loop");
|
||||
eprintln!(" (V) Toggle visibility");
|
||||
@@ -70,7 +72,7 @@ fn main() {
|
||||
size.width * size.height
|
||||
}
|
||||
|
||||
let monitor = window.current_monitor();
|
||||
let monitor = window.current_monitor().unwrap();
|
||||
if let Some(mode) = monitor
|
||||
.video_modes()
|
||||
.max_by(|a, b| area(a.size()).cmp(&area(b.size())))
|
||||
@@ -88,6 +90,13 @@ fn main() {
|
||||
window.set_fullscreen(Some(Fullscreen::Borderless(monitor)));
|
||||
}
|
||||
}
|
||||
VirtualKeyCode::P => {
|
||||
if window.fullscreen().is_some() {
|
||||
window.set_fullscreen(None);
|
||||
} else {
|
||||
window.set_fullscreen(Some(Fullscreen::Borderless(None)));
|
||||
}
|
||||
}
|
||||
VirtualKeyCode::M => {
|
||||
minimized = !minimized;
|
||||
window.set_minimized(minimized);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
extern crate image;
|
||||
use std::path::Path;
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::Event,
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -7,7 +9,7 @@ use winit::{
|
||||
};
|
||||
|
||||
fn main() {
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().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,
|
||||
@@ -45,13 +47,11 @@ fn main() {
|
||||
|
||||
fn load_icon(path: &Path) -> Icon {
|
||||
let (icon_rgba, icon_width, icon_height) = {
|
||||
let image = image::open(path).expect("Failed to open icon path");
|
||||
use image::{GenericImageView, Pixel};
|
||||
let image = image::open(path)
|
||||
.expect("Failed to open icon path")
|
||||
.into_rgba();
|
||||
let (width, height) = image.dimensions();
|
||||
let mut rgba = Vec::with_capacity((width * height) as usize * 4);
|
||||
for (_, _, pixel) in image.pixels() {
|
||||
rgba.extend_from_slice(&pixel.to_rgba().data);
|
||||
}
|
||||
let rgba = image.into_raw();
|
||||
(rgba, width, height)
|
||||
};
|
||||
Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon")
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
))]
|
||||
fn main() {
|
||||
use std::{thread::sleep, time::Duration};
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
@@ -18,7 +20,7 @@ fn main() {
|
||||
};
|
||||
let mut event_loop = EventLoop::new();
|
||||
|
||||
simple_logger::init().unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let _window = WindowBuilder::new()
|
||||
.with_title("A fantastic window!")
|
||||
.build(&event_loop)
|
||||
|
||||
74
src/dpi.rs
74
src/dpi.rs
@@ -89,6 +89,8 @@
|
||||
//! - **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`.
|
||||
//!
|
||||
//! [points]: https://en.wikipedia.org/wiki/Point_(typography)
|
||||
//! [picas]: https://en.wikipedia.org/wiki/Pica_(typography)
|
||||
@@ -96,6 +98,7 @@
|
||||
//! [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
|
||||
|
||||
pub trait Pixel: Copy + Into<f64> {
|
||||
fn from_f64(f: f64) -> Self;
|
||||
@@ -151,8 +154,8 @@ impl Pixel for f64 {
|
||||
/// anywhere other than winit, it's recommended to validate them using this function before passing them to winit;
|
||||
/// otherwise, you risk panics.
|
||||
#[inline]
|
||||
pub fn validate_scale_factor(dpi_factor: f64) -> bool {
|
||||
dpi_factor.is_sign_positive() && dpi_factor.is_normal()
|
||||
pub fn validate_scale_factor(scale_factor: f64) -> bool {
|
||||
scale_factor.is_sign_positive() && scale_factor.is_normal()
|
||||
}
|
||||
|
||||
/// A position represented in logical pixels.
|
||||
@@ -178,16 +181,16 @@ impl<P: Pixel> LogicalPosition<P> {
|
||||
#[inline]
|
||||
pub fn from_physical<T: Into<PhysicalPosition<X>>, X: Pixel>(
|
||||
physical: T,
|
||||
dpi_factor: f64,
|
||||
scale_factor: f64,
|
||||
) -> Self {
|
||||
physical.into().to_logical(dpi_factor)
|
||||
physical.into().to_logical(scale_factor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_physical<X: Pixel>(&self, dpi_factor: f64) -> PhysicalPosition<X> {
|
||||
assert!(validate_scale_factor(dpi_factor));
|
||||
let x = self.x.into() * dpi_factor;
|
||||
let y = self.y.into() * dpi_factor;
|
||||
pub fn to_physical<X: Pixel>(&self, scale_factor: f64) -> PhysicalPosition<X> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let x = self.x.into() * scale_factor;
|
||||
let y = self.y.into() * scale_factor;
|
||||
PhysicalPosition::new(x, y).cast()
|
||||
}
|
||||
|
||||
@@ -243,16 +246,16 @@ impl<P: Pixel> PhysicalPosition<P> {
|
||||
#[inline]
|
||||
pub fn from_logical<T: Into<LogicalPosition<X>>, X: Pixel>(
|
||||
logical: T,
|
||||
dpi_factor: f64,
|
||||
scale_factor: f64,
|
||||
) -> Self {
|
||||
logical.into().to_physical(dpi_factor)
|
||||
logical.into().to_physical(scale_factor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_logical<X: Pixel>(&self, dpi_factor: f64) -> LogicalPosition<X> {
|
||||
assert!(validate_scale_factor(dpi_factor));
|
||||
let x = self.x.into() / dpi_factor;
|
||||
let y = self.y.into() / dpi_factor;
|
||||
pub fn to_logical<X: Pixel>(&self, scale_factor: f64) -> LogicalPosition<X> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let x = self.x.into() / scale_factor;
|
||||
let y = self.y.into() / scale_factor;
|
||||
LogicalPosition::new(x, y).cast()
|
||||
}
|
||||
|
||||
@@ -306,15 +309,18 @@ impl<P> LogicalSize<P> {
|
||||
|
||||
impl<P: Pixel> LogicalSize<P> {
|
||||
#[inline]
|
||||
pub fn from_physical<T: Into<PhysicalSize<X>>, X: Pixel>(physical: T, dpi_factor: f64) -> Self {
|
||||
physical.into().to_logical(dpi_factor)
|
||||
pub fn from_physical<T: Into<PhysicalSize<X>>, X: Pixel>(
|
||||
physical: T,
|
||||
scale_factor: f64,
|
||||
) -> Self {
|
||||
physical.into().to_logical(scale_factor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_physical<X: Pixel>(&self, dpi_factor: f64) -> PhysicalSize<X> {
|
||||
assert!(validate_scale_factor(dpi_factor));
|
||||
let width = self.width.into() * dpi_factor;
|
||||
let height = self.height.into() * dpi_factor;
|
||||
pub fn to_physical<X: Pixel>(&self, scale_factor: f64) -> PhysicalSize<X> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let width = self.width.into() * scale_factor;
|
||||
let height = self.height.into() * scale_factor;
|
||||
PhysicalSize::new(width, height).cast()
|
||||
}
|
||||
|
||||
@@ -368,15 +374,15 @@ impl<P> PhysicalSize<P> {
|
||||
|
||||
impl<P: Pixel> PhysicalSize<P> {
|
||||
#[inline]
|
||||
pub fn from_logical<T: Into<LogicalSize<X>>, X: Pixel>(logical: T, dpi_factor: f64) -> Self {
|
||||
logical.into().to_physical(dpi_factor)
|
||||
pub fn from_logical<T: Into<LogicalSize<X>>, X: Pixel>(logical: T, scale_factor: f64) -> Self {
|
||||
logical.into().to_physical(scale_factor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_logical<X: Pixel>(&self, dpi_factor: f64) -> LogicalSize<X> {
|
||||
assert!(validate_scale_factor(dpi_factor));
|
||||
let width = self.width.into() / dpi_factor;
|
||||
let height = self.height.into() / dpi_factor;
|
||||
pub fn to_logical<X: Pixel>(&self, scale_factor: f64) -> LogicalSize<X> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let width = self.width.into() / scale_factor;
|
||||
let height = self.height.into() / scale_factor;
|
||||
LogicalSize::new(width, height).cast()
|
||||
}
|
||||
|
||||
@@ -426,17 +432,17 @@ impl Size {
|
||||
size.into()
|
||||
}
|
||||
|
||||
pub fn to_logical<P: Pixel>(&self, dpi_factor: f64) -> LogicalSize<P> {
|
||||
pub fn to_logical<P: Pixel>(&self, scale_factor: f64) -> LogicalSize<P> {
|
||||
match *self {
|
||||
Size::Physical(size) => size.to_logical(dpi_factor),
|
||||
Size::Physical(size) => size.to_logical(scale_factor),
|
||||
Size::Logical(size) => size.cast(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_physical<P: Pixel>(&self, dpi_factor: f64) -> PhysicalSize<P> {
|
||||
pub fn to_physical<P: Pixel>(&self, scale_factor: f64) -> PhysicalSize<P> {
|
||||
match *self {
|
||||
Size::Physical(size) => size.cast(),
|
||||
Size::Logical(size) => size.to_physical(dpi_factor),
|
||||
Size::Logical(size) => size.to_physical(scale_factor),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -468,17 +474,17 @@ impl Position {
|
||||
position.into()
|
||||
}
|
||||
|
||||
pub fn to_logical<P: Pixel>(&self, dpi_factor: f64) -> LogicalPosition<P> {
|
||||
pub fn to_logical<P: Pixel>(&self, scale_factor: f64) -> LogicalPosition<P> {
|
||||
match *self {
|
||||
Position::Physical(position) => position.to_logical(dpi_factor),
|
||||
Position::Physical(position) => position.to_logical(scale_factor),
|
||||
Position::Logical(position) => position.cast(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_physical<P: Pixel>(&self, dpi_factor: f64) -> PhysicalPosition<P> {
|
||||
pub fn to_physical<P: Pixel>(&self, scale_factor: f64) -> PhysicalPosition<P> {
|
||||
match *self {
|
||||
Position::Physical(position) => position.cast(),
|
||||
Position::Logical(position) => position.to_physical(dpi_factor),
|
||||
Position::Logical(position) => position.to_physical(scale_factor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
183
src/event.rs
183
src/event.rs
@@ -37,7 +37,7 @@ use instant::Instant;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::{
|
||||
dpi::{LogicalPosition, PhysicalPosition, PhysicalSize},
|
||||
dpi::{PhysicalPosition, PhysicalSize},
|
||||
platform_impl,
|
||||
window::{Theme, WindowId},
|
||||
};
|
||||
@@ -81,10 +81,11 @@ pub enum Event<'a, T: 'static> {
|
||||
///
|
||||
/// This event is useful as a place to put your code that should be run after all
|
||||
/// state-changing events have been handled and you want to do stuff (updating state, performing
|
||||
/// calculations, etc) that happens as the "main body" of your event loop. If your program draws
|
||||
/// graphics, it's usually better to do it in response to
|
||||
/// calculations, etc) that happens as the "main body" of your event loop. If your program only draws
|
||||
/// graphics when something changes, it's usually better to do it in response to
|
||||
/// [`Event::RedrawRequested`](crate::event::Event::RedrawRequested), which gets emitted
|
||||
/// immediately after this event.
|
||||
/// immediately after this event. Programs that draw graphics continuously, like most games,
|
||||
/// can render here unconditionally for simplicity.
|
||||
MainEventsCleared,
|
||||
|
||||
/// Emitted after `MainEventsCleared` when a window should be redrawn.
|
||||
@@ -97,6 +98,9 @@ pub enum Event<'a, T: 'static> {
|
||||
///
|
||||
/// During each iteration of the event loop, Winit will aggregate duplicate redraw requests
|
||||
/// into a single event, to help avoid duplicating rendering work.
|
||||
///
|
||||
/// Mainly of interest to applications with mostly-static graphics that avoid redrawing unless
|
||||
/// something changes, like most non-game GUIs.
|
||||
RedrawRequested(WindowId),
|
||||
|
||||
/// Emitted after all `RedrawRequested` events have been processed and control flow is about to
|
||||
@@ -114,6 +118,30 @@ pub enum Event<'a, T: 'static> {
|
||||
LoopDestroyed,
|
||||
}
|
||||
|
||||
impl<T: Clone> Clone for Event<'static, T> {
|
||||
fn clone(&self) -> Self {
|
||||
use self::Event::*;
|
||||
match self {
|
||||
WindowEvent { window_id, event } => WindowEvent {
|
||||
window_id: *window_id,
|
||||
event: event.clone(),
|
||||
},
|
||||
UserEvent(event) => UserEvent(event.clone()),
|
||||
DeviceEvent { device_id, event } => DeviceEvent {
|
||||
device_id: *device_id,
|
||||
event: event.clone(),
|
||||
},
|
||||
NewEvents(cause) => NewEvents(cause.clone()),
|
||||
MainEventsCleared => MainEventsCleared,
|
||||
RedrawRequested(wid) => RedrawRequested(*wid),
|
||||
RedrawEventsCleared => RedrawEventsCleared,
|
||||
LoopDestroyed => LoopDestroyed,
|
||||
Suspended => Suspended,
|
||||
Resumed => Resumed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Event<'a, T> {
|
||||
pub fn map_nonuser_event<U>(self) -> Result<Event<'a, U>, Event<'a, T>> {
|
||||
use self::Event::*;
|
||||
@@ -139,7 +167,7 @@ impl<'a, T> Event<'a, T> {
|
||||
WindowEvent { window_id, event } => event
|
||||
.to_static()
|
||||
.map(|event| WindowEvent { window_id, event }),
|
||||
UserEvent(_) => None,
|
||||
UserEvent(event) => Some(UserEvent(event)),
|
||||
DeviceEvent { device_id, event } => Some(DeviceEvent { device_id, event }),
|
||||
NewEvents(cause) => Some(NewEvents(cause)),
|
||||
MainEventsCleared => Some(MainEventsCleared),
|
||||
@@ -185,7 +213,7 @@ pub enum WindowEvent<'a> {
|
||||
Resized(PhysicalSize<u32>),
|
||||
|
||||
/// The position of the window has changed. Contains the window's new position.
|
||||
Moved(PhysicalPosition<u32>),
|
||||
Moved(PhysicalPosition<i32>),
|
||||
|
||||
/// The window has been requested to close.
|
||||
CloseRequested,
|
||||
@@ -235,6 +263,13 @@ pub enum WindowEvent<'a> {
|
||||
is_synthetic: bool,
|
||||
},
|
||||
|
||||
/// The keyboard modifiers have changed.
|
||||
///
|
||||
/// Platform-specific behavior:
|
||||
/// - **Web**: This API is currently unimplemented on the web. This isn't by design - it's an
|
||||
/// issue, and it should get fixed - but it's the current state of the API.
|
||||
ModifiersChanged(ModifiersState),
|
||||
|
||||
/// The cursor has moved on the window.
|
||||
CursorMoved {
|
||||
device_id: DeviceId,
|
||||
@@ -243,7 +278,7 @@ pub enum WindowEvent<'a> {
|
||||
/// limited by the display area and it may have been transformed by the OS to implement effects such as cursor
|
||||
/// acceleration, it should not be used to implement non-cursor-like interactions such as 3D camera control.
|
||||
position: PhysicalPosition<f64>,
|
||||
#[deprecated = "Deprecated in favor of DeviceEvent::ModifiersChanged"]
|
||||
#[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"]
|
||||
modifiers: ModifiersState,
|
||||
},
|
||||
|
||||
@@ -258,7 +293,7 @@ pub enum WindowEvent<'a> {
|
||||
device_id: DeviceId,
|
||||
delta: MouseScrollDelta,
|
||||
phase: TouchPhase,
|
||||
#[deprecated = "Deprecated in favor of DeviceEvent::ModifiersChanged"]
|
||||
#[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"]
|
||||
modifiers: ModifiersState,
|
||||
},
|
||||
|
||||
@@ -267,7 +302,7 @@ pub enum WindowEvent<'a> {
|
||||
device_id: DeviceId,
|
||||
state: ElementState,
|
||||
button: MouseButton,
|
||||
#[deprecated = "Deprecated in favor of DeviceEvent::ModifiersChanged"]
|
||||
#[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"]
|
||||
modifiers: ModifiersState,
|
||||
},
|
||||
|
||||
@@ -319,6 +354,97 @@ pub enum WindowEvent<'a> {
|
||||
ThemeChanged(Theme),
|
||||
}
|
||||
|
||||
impl Clone for WindowEvent<'static> {
|
||||
fn clone(&self) -> Self {
|
||||
use self::WindowEvent::*;
|
||||
return match self {
|
||||
Resized(size) => Resized(size.clone()),
|
||||
Moved(pos) => Moved(pos.clone()),
|
||||
CloseRequested => CloseRequested,
|
||||
Destroyed => Destroyed,
|
||||
DroppedFile(file) => DroppedFile(file.clone()),
|
||||
HoveredFile(file) => HoveredFile(file.clone()),
|
||||
HoveredFileCancelled => HoveredFileCancelled,
|
||||
ReceivedCharacter(c) => ReceivedCharacter(*c),
|
||||
Focused(f) => Focused(*f),
|
||||
KeyboardInput {
|
||||
device_id,
|
||||
input,
|
||||
is_synthetic,
|
||||
} => KeyboardInput {
|
||||
device_id: *device_id,
|
||||
input: *input,
|
||||
is_synthetic: *is_synthetic,
|
||||
},
|
||||
|
||||
ModifiersChanged(modifiers) => ModifiersChanged(modifiers.clone()),
|
||||
#[allow(deprecated)]
|
||||
CursorMoved {
|
||||
device_id,
|
||||
position,
|
||||
modifiers,
|
||||
} => CursorMoved {
|
||||
device_id: *device_id,
|
||||
position: *position,
|
||||
modifiers: *modifiers,
|
||||
},
|
||||
CursorEntered { device_id } => CursorEntered {
|
||||
device_id: *device_id,
|
||||
},
|
||||
CursorLeft { device_id } => CursorLeft {
|
||||
device_id: *device_id,
|
||||
},
|
||||
#[allow(deprecated)]
|
||||
MouseWheel {
|
||||
device_id,
|
||||
delta,
|
||||
phase,
|
||||
modifiers,
|
||||
} => MouseWheel {
|
||||
device_id: *device_id,
|
||||
delta: *delta,
|
||||
phase: *phase,
|
||||
modifiers: *modifiers,
|
||||
},
|
||||
#[allow(deprecated)]
|
||||
MouseInput {
|
||||
device_id,
|
||||
state,
|
||||
button,
|
||||
modifiers,
|
||||
} => MouseInput {
|
||||
device_id: *device_id,
|
||||
state: *state,
|
||||
button: *button,
|
||||
modifiers: *modifiers,
|
||||
},
|
||||
TouchpadPressure {
|
||||
device_id,
|
||||
pressure,
|
||||
stage,
|
||||
} => TouchpadPressure {
|
||||
device_id: *device_id,
|
||||
pressure: *pressure,
|
||||
stage: *stage,
|
||||
},
|
||||
AxisMotion {
|
||||
device_id,
|
||||
axis,
|
||||
value,
|
||||
} => AxisMotion {
|
||||
device_id: *device_id,
|
||||
axis: *axis,
|
||||
value: *value,
|
||||
},
|
||||
Touch(touch) => Touch(*touch),
|
||||
ThemeChanged(theme) => ThemeChanged(theme.clone()),
|
||||
ScaleFactorChanged { .. } => {
|
||||
unreachable!("Static event can't be about scale factor changing")
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> WindowEvent<'a> {
|
||||
pub fn to_static(self) -> Option<WindowEvent<'static>> {
|
||||
use self::WindowEvent::*;
|
||||
@@ -341,6 +467,7 @@ impl<'a> WindowEvent<'a> {
|
||||
input,
|
||||
is_synthetic,
|
||||
}),
|
||||
ModifiersChanged(modifiers) => Some(ModifiersChanged(modifiers)),
|
||||
#[allow(deprecated)]
|
||||
CursorMoved {
|
||||
device_id,
|
||||
@@ -464,16 +591,6 @@ pub enum DeviceEvent {
|
||||
|
||||
Key(KeyboardInput),
|
||||
|
||||
/// The keyboard modifiers have changed.
|
||||
///
|
||||
/// This is tracked internally to avoid tracking errors arising from modifier key state changes when events from
|
||||
/// this device are not being delivered to the application, e.g. due to keyboard focus being elsewhere.
|
||||
///
|
||||
/// Platform-specific behavior:
|
||||
/// - **Web**: This API is currently unimplemented on the web. This isn't by design - it's an
|
||||
/// issue, and it should get fixed - but it's the current state of the API.
|
||||
ModifiersChanged(ModifiersState),
|
||||
|
||||
Text {
|
||||
codepoint: char,
|
||||
},
|
||||
@@ -502,7 +619,7 @@ pub struct KeyboardInput {
|
||||
///
|
||||
/// This is tracked internally to avoid tracking errors arising from modifier key state changes when events from
|
||||
/// this device are not being delivered to the application, e.g. due to keyboard focus being elsewhere.
|
||||
#[deprecated = "Deprecated in favor of DeviceEvent::ModifiersChanged"]
|
||||
#[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"]
|
||||
pub modifiers: ModifiersState,
|
||||
}
|
||||
|
||||
@@ -647,7 +764,7 @@ pub enum MouseScrollDelta {
|
||||
/// Scroll events are expressed as a PixelDelta if
|
||||
/// supported by the device (eg. a touchpad) and
|
||||
/// platform.
|
||||
PixelDelta(LogicalPosition<f64>),
|
||||
PixelDelta(PhysicalPosition<f64>),
|
||||
}
|
||||
|
||||
/// Symbolic name for a keyboard key.
|
||||
@@ -775,12 +892,20 @@ pub enum VirtualKeyCode {
|
||||
Numpad7,
|
||||
Numpad8,
|
||||
Numpad9,
|
||||
NumpadAdd,
|
||||
NumpadDivide,
|
||||
NumpadDecimal,
|
||||
NumpadComma,
|
||||
NumpadEnter,
|
||||
NumpadEquals,
|
||||
NumpadMultiply,
|
||||
NumpadSubtract,
|
||||
|
||||
AbntC1,
|
||||
AbntC2,
|
||||
Add,
|
||||
Apostrophe,
|
||||
Apps,
|
||||
Asterisk,
|
||||
At,
|
||||
Ax,
|
||||
Backslash,
|
||||
@@ -789,8 +914,6 @@ pub enum VirtualKeyCode {
|
||||
Colon,
|
||||
Comma,
|
||||
Convert,
|
||||
Decimal,
|
||||
Divide,
|
||||
Equals,
|
||||
Grave,
|
||||
Kana,
|
||||
@@ -804,19 +927,18 @@ pub enum VirtualKeyCode {
|
||||
MediaSelect,
|
||||
MediaStop,
|
||||
Minus,
|
||||
Multiply,
|
||||
Mute,
|
||||
MyComputer,
|
||||
NavigateForward, // also called "Prior"
|
||||
NavigateBackward, // also called "Next"
|
||||
// also called "Next"
|
||||
NavigateForward,
|
||||
// also called "Prior"
|
||||
NavigateBackward,
|
||||
NextTrack,
|
||||
NoConvert,
|
||||
NumpadComma,
|
||||
NumpadEnter,
|
||||
NumpadEquals,
|
||||
OEM102,
|
||||
Period,
|
||||
PlayPause,
|
||||
Plus,
|
||||
Power,
|
||||
PrevTrack,
|
||||
RAlt,
|
||||
@@ -828,7 +950,6 @@ pub enum VirtualKeyCode {
|
||||
Slash,
|
||||
Sleep,
|
||||
Stop,
|
||||
Subtract,
|
||||
Sysrq,
|
||||
Tab,
|
||||
Underline,
|
||||
|
||||
@@ -73,6 +73,12 @@ impl<T> fmt::Debug for EventLoopWindowTarget<T> {
|
||||
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.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
/// - **Web:** Events are queued and usually sent when `requestAnimationFrame` fires but sometimes
|
||||
/// the events in the queue may be sent before the next `requestAnimationFrame` callback, for
|
||||
/// example when the scaling of the page has changed. This should be treated as an implementation
|
||||
/// detail which should not be relied on.
|
||||
Poll,
|
||||
/// When the current loop iteration finishes, suspend the thread until another event arrives.
|
||||
Wait,
|
||||
@@ -154,23 +160,6 @@ impl<T> EventLoop<T> {
|
||||
event_loop_proxy: self.event_loop.create_proxy(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the list of all the monitors available on the system.
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
||||
self.event_loop
|
||||
.available_monitors()
|
||||
.into_iter()
|
||||
.map(|inner| MonitorHandle { inner })
|
||||
}
|
||||
|
||||
/// Returns the primary monitor of the system.
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> MonitorHandle {
|
||||
MonitorHandle {
|
||||
inner: self.event_loop.primary_monitor(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for EventLoop<T> {
|
||||
@@ -180,6 +169,29 @@ impl<T> Deref for EventLoop<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventLoopWindowTarget<T> {
|
||||
/// Returns the list of all the monitors available on the system.
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
||||
self.p
|
||||
.available_monitors()
|
||||
.into_iter()
|
||||
.map(|inner| MonitorHandle { inner })
|
||||
}
|
||||
|
||||
/// Returns the primary monitor of the system.
|
||||
///
|
||||
/// Returns `None` if it can't identify any monitor as a primary one.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// **Wayland:** Always returns `None`.
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
self.p.primary_monitor()
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to send custom events to `EventLoop`.
|
||||
pub struct EventLoopProxy<T: 'static> {
|
||||
event_loop_proxy: platform_impl::EventLoopProxy<T>,
|
||||
|
||||
92
src/icon.rs
92
src/icon.rs
@@ -1,4 +1,5 @@
|
||||
use std::{error::Error, fmt, mem};
|
||||
use crate::platform_impl::PlatformIcon;
|
||||
use std::{error::Error, fmt, io, mem};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
@@ -11,7 +12,7 @@ pub(crate) struct Pixel {
|
||||
|
||||
pub(crate) const PIXEL_SIZE: usize = mem::size_of::<Pixel>();
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Debug)]
|
||||
/// An error produced when using `Icon::from_rgba` with invalid arguments.
|
||||
pub enum BadIcon {
|
||||
/// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
|
||||
@@ -25,6 +26,8 @@ pub enum BadIcon {
|
||||
width_x_height: usize,
|
||||
pixel_count: usize,
|
||||
},
|
||||
/// Produced when underlying OS functionality failed to create the icon
|
||||
OsError(io::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for BadIcon {
|
||||
@@ -43,6 +46,7 @@ impl fmt::Display for BadIcon {
|
||||
"The specified dimensions ({:?}x{:?}) don't match the number of pixels supplied by the `rgba` argument ({:?}). For those dimensions, the expected pixel count is {:?}.",
|
||||
width, height, pixel_count, width_x_height,
|
||||
),
|
||||
BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {:?}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,38 +58,78 @@ impl Error for BadIcon {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
/// An icon used for the window titlebar, taskbar, etc.
|
||||
pub struct Icon {
|
||||
pub(crate) struct RgbaIcon {
|
||||
pub(crate) rgba: Vec<u8>,
|
||||
pub(crate) width: u32,
|
||||
pub(crate) height: u32,
|
||||
}
|
||||
|
||||
/// For platforms which don't have window icons (e.g. web)
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct NoIcon;
|
||||
|
||||
#[allow(dead_code)] // These are not used on every platform
|
||||
mod constructors {
|
||||
use super::*;
|
||||
|
||||
impl RgbaIcon {
|
||||
/// Creates an `Icon` from 32bpp RGBA data.
|
||||
///
|
||||
/// 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> {
|
||||
if rgba.len() % PIXEL_SIZE != 0 {
|
||||
return Err(BadIcon::ByteCountNotDivisibleBy4 {
|
||||
byte_count: rgba.len(),
|
||||
});
|
||||
}
|
||||
let pixel_count = rgba.len() / PIXEL_SIZE;
|
||||
if pixel_count != (width * height) as usize {
|
||||
Err(BadIcon::DimensionsVsPixelCount {
|
||||
width,
|
||||
height,
|
||||
width_x_height: (width * height) as usize,
|
||||
pixel_count,
|
||||
})
|
||||
} else {
|
||||
Ok(RgbaIcon {
|
||||
rgba,
|
||||
width,
|
||||
height,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NoIcon {
|
||||
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||
// Create the rgba icon anyway to validate the input
|
||||
let _ = RgbaIcon::from_rgba(rgba, width, height)?;
|
||||
Ok(NoIcon)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An icon used for the window titlebar, taskbar, etc.
|
||||
#[derive(Clone)]
|
||||
pub struct Icon {
|
||||
pub(crate) inner: PlatformIcon,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Icon {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
fmt::Debug::fmt(&self.inner, formatter)
|
||||
}
|
||||
}
|
||||
|
||||
impl Icon {
|
||||
/// Creates an `Icon` from 32bpp RGBA data.
|
||||
///
|
||||
/// 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> {
|
||||
if rgba.len() % PIXEL_SIZE != 0 {
|
||||
return Err(BadIcon::ByteCountNotDivisibleBy4 {
|
||||
byte_count: rgba.len(),
|
||||
});
|
||||
}
|
||||
let pixel_count = rgba.len() / PIXEL_SIZE;
|
||||
if pixel_count != (width * height) as usize {
|
||||
Err(BadIcon::DimensionsVsPixelCount {
|
||||
width,
|
||||
height,
|
||||
width_x_height: (width * height) as usize,
|
||||
pixel_count,
|
||||
})
|
||||
} else {
|
||||
Ok(Icon {
|
||||
rgba,
|
||||
width,
|
||||
height,
|
||||
})
|
||||
}
|
||||
Ok(Icon {
|
||||
inner: PlatformIcon::from_rgba(rgba, width, height)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
24
src/lib.rs
24
src/lib.rs
@@ -28,7 +28,7 @@
|
||||
//! Some user activity, like mouse movement, can generate both a [`WindowEvent`] *and* a
|
||||
//! [`DeviceEvent`]. You can also create and handle your own custom [`UserEvent`]s, if desired.
|
||||
//!
|
||||
//! You can retreive events by calling [`EventLoop::run`][event_loop_run]. This function will
|
||||
//! You can retrieve events by calling [`EventLoop::run`][event_loop_run]. This function will
|
||||
//! dispatch events for every [`Window`] that was created with that particular [`EventLoop`], and
|
||||
//! will run until the `control_flow` argument given to the closure is set to
|
||||
//! [`ControlFlow`]`::`[`Exit`], at which point [`Event`]`::`[`LoopDestroyed`] is emitted and the
|
||||
@@ -73,14 +73,18 @@
|
||||
//! // Application update code.
|
||||
//!
|
||||
//! // 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 just render here instead.
|
||||
//! window.request_redraw();
|
||||
//! },
|
||||
//! Event::RedrawRequested(_) => {
|
||||
//! // Redraw the application.
|
||||
//! //
|
||||
//! // It's preferrable to render in this event rather than in MainEventsCleared, since
|
||||
//! // rendering in here allows the program to gracefully handle redraws requested
|
||||
//! // by the OS.
|
||||
//! // It's preferable for applications that do not render continuously to render in
|
||||
//! // this event rather than in MainEventsCleared, since rendering in here allows
|
||||
//! // the program to gracefully handle redraws requested by the OS.
|
||||
//! },
|
||||
//! _ => ()
|
||||
//! }
|
||||
@@ -94,8 +98,15 @@
|
||||
//! # 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 (see the [`platform`] module), which in turn allows you
|
||||
//! to create an OpenGL/Vulkan/DirectX/Metal/etc. context that can be used to render graphics.
|
||||
//! retrieve the raw handle of the window (see the [`platform`] module and/or the
|
||||
//! [`raw_window_handle`] method), 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::WindowBuilder::with_visible) and explicitly make the
|
||||
//! window visible only once you're ready to render into it.
|
||||
//!
|
||||
//! [`EventLoop`]: event_loop::EventLoop
|
||||
//! [`EventLoopExtDesktop::run_return`]: ./platform/desktop/trait.EventLoopExtDesktop.html#tymethod.run_return
|
||||
@@ -116,6 +127,7 @@
|
||||
//! [`UserEvent`]: event::Event::UserEvent
|
||||
//! [`LoopDestroyed`]: event::Event::LoopDestroyed
|
||||
//! [`platform`]: platform
|
||||
//! [`raw_window_handle`]: ./window/struct.Window.html#method.raw_window_handle
|
||||
|
||||
#![deny(rust_2018_idioms)]
|
||||
#![deny(intra_doc_link_resolution_failure)]
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
//! Types useful for interacting with a user's monitors.
|
||||
//!
|
||||
//! If you want to get basic information about a monitor, you can use the [`MonitorHandle`][monitor_handle]
|
||||
//! type. This is retreived from one of the following methods, which return an iterator of
|
||||
//! type. This is retrieved from one of the following methods, which return an iterator of
|
||||
//! [`MonitorHandle`][monitor_handle]:
|
||||
//! - [`EventLoop::available_monitors`][loop_get]
|
||||
//! - [`EventLoopWindowTarget::available_monitors`][loop_get]
|
||||
//! - [`Window::available_monitors`][window_get].
|
||||
//!
|
||||
//! [monitor_handle]: crate::monitor::MonitorHandle
|
||||
//! [loop_get]: crate::event_loop::EventLoop::available_monitors
|
||||
//! [loop_get]: crate::event_loop::EventLoopWindowTarget::available_monitors
|
||||
//! [window_get]: crate::window::Window::available_monitors
|
||||
use crate::{
|
||||
dpi::{PhysicalPosition, PhysicalSize},
|
||||
|
||||
@@ -1,32 +1,39 @@
|
||||
#![cfg(any(target_os = "android"))]
|
||||
|
||||
use crate::{EventLoop, Window, WindowBuilder};
|
||||
use std::os::raw::c_void;
|
||||
use crate::{
|
||||
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||
window::{Window, WindowBuilder},
|
||||
};
|
||||
use ndk::configuration::Configuration;
|
||||
use ndk_glue::Rect;
|
||||
|
||||
/// Additional methods on `EventLoop` that are specific to Android.
|
||||
pub trait EventLoopExtAndroid {
|
||||
/// Makes it possible for glutin to register a callback when a suspend event happens on Android
|
||||
fn set_suspend_callback(&self, cb: Option<Box<dyn Fn(bool) -> ()>>);
|
||||
}
|
||||
pub trait EventLoopExtAndroid {}
|
||||
|
||||
impl EventLoopExtAndroid for EventLoop {
|
||||
fn set_suspend_callback(&self, cb: Option<Box<dyn Fn(bool) -> ()>>) {
|
||||
self.event_loop.set_suspend_callback(cb);
|
||||
}
|
||||
}
|
||||
impl<T> EventLoopExtAndroid for EventLoop<T> {}
|
||||
|
||||
/// Additional methods on `EventLoopWindowTarget` that are specific to Android.
|
||||
pub trait EventLoopWindowTargetExtAndroid {}
|
||||
|
||||
/// Additional methods on `Window` that are specific to Android.
|
||||
pub trait WindowExtAndroid {
|
||||
fn native_window(&self) -> *const c_void;
|
||||
fn content_rect(&self) -> Rect;
|
||||
|
||||
fn config(&self) -> Configuration;
|
||||
}
|
||||
|
||||
impl WindowExtAndroid for Window {
|
||||
#[inline]
|
||||
fn native_window(&self) -> *const c_void {
|
||||
self.window.native_window()
|
||||
fn content_rect(&self) -> Rect {
|
||||
self.window.content_rect()
|
||||
}
|
||||
|
||||
fn config(&self) -> Configuration {
|
||||
self.window.config()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventLoopWindowTargetExtAndroid for EventLoopWindowTarget<T> {}
|
||||
|
||||
/// Additional methods on `WindowBuilder` that are specific to Android.
|
||||
pub trait WindowBuilderExtAndroid {}
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
#![cfg(any(
|
||||
target_os = "windows",
|
||||
target_os = "macos",
|
||||
target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"
|
||||
target_os = "android",
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
|
||||
use crate::{
|
||||
|
||||
@@ -56,6 +56,12 @@ pub trait WindowExtMacOS {
|
||||
/// And allows the user to have a fullscreen window without using another
|
||||
/// space or taking control over the entire monitor.
|
||||
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool;
|
||||
|
||||
/// Returns whether or not the window has shadow.
|
||||
fn has_shadow(&self) -> bool;
|
||||
|
||||
/// Sets whether or not the window has shadow.
|
||||
fn set_has_shadow(&self, has_shadow: bool);
|
||||
}
|
||||
|
||||
impl WindowExtMacOS for Window {
|
||||
@@ -83,6 +89,16 @@ impl WindowExtMacOS for Window {
|
||||
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
|
||||
self.window.set_simple_fullscreen(fullscreen)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn has_shadow(&self) -> bool {
|
||||
self.window.has_shadow()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_has_shadow(&self, has_shadow: bool) {
|
||||
self.window.set_has_shadow(has_shadow)
|
||||
}
|
||||
}
|
||||
|
||||
/// Corresponds to `NSApplicationActivationPolicy`.
|
||||
@@ -131,6 +147,7 @@ pub trait WindowBuilderExtMacOS {
|
||||
/// Build window with `resizeIncrements` property. Values must not be 0.
|
||||
fn with_resize_increments(self, increments: LogicalSize<f64>) -> WindowBuilder;
|
||||
fn with_disallow_hidpi(self, disallow_hidpi: bool) -> WindowBuilder;
|
||||
fn with_has_shadow(self, has_shadow: bool) -> WindowBuilder;
|
||||
}
|
||||
|
||||
impl WindowBuilderExtMacOS for WindowBuilder {
|
||||
@@ -190,6 +207,12 @@ impl WindowBuilderExtMacOS for WindowBuilder {
|
||||
self.platform_specific.disallow_hidpi = disallow_hidpi;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_has_shadow(mut self, has_shadow: bool) -> WindowBuilder {
|
||||
self.platform_specific.has_shadow = has_shadow;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on `MonitorHandle` that are specific to MacOS.
|
||||
@@ -215,6 +238,8 @@ impl MonitorHandleExtMacOS for MonitorHandle {
|
||||
pub trait EventLoopWindowTargetExtMacOS {
|
||||
/// Hide the entire application. In most applications this is typically triggered with Command-H.
|
||||
fn hide_application(&self);
|
||||
/// Hide the other applications. In most applications this is typically triggered with Command+Option-H.
|
||||
fn hide_other_applications(&self);
|
||||
}
|
||||
|
||||
impl<T> EventLoopWindowTargetExtMacOS for EventLoopWindowTarget<T> {
|
||||
@@ -223,4 +248,10 @@ impl<T> EventLoopWindowTargetExtMacOS for EventLoopWindowTarget<T> {
|
||||
let app: cocoa::base::id = unsafe { msg_send![cls, sharedApplication] };
|
||||
unsafe { msg_send![app, hide: 0] }
|
||||
}
|
||||
|
||||
fn hide_other_applications(&self) {
|
||||
let cls = objc::runtime::Class::get("NSApplication").unwrap();
|
||||
let app: cocoa::base::id = unsafe { msg_send![cls, sharedApplication] };
|
||||
unsafe { msg_send![app, hideOtherApplications: 0] }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,37 +1,49 @@
|
||||
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#![cfg(any(
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
|
||||
use std::{os::raw, ptr, sync::Arc};
|
||||
|
||||
use smithay_client_toolkit::window::{ButtonState as SCTKButtonState, Theme as SCTKTheme};
|
||||
use std::os::raw;
|
||||
#[cfg(feature = "x11")]
|
||||
use std::{ptr, sync::Arc};
|
||||
|
||||
use crate::{
|
||||
dpi::Size,
|
||||
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||
monitor::MonitorHandle,
|
||||
window::{Window, WindowBuilder},
|
||||
};
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
use crate::dpi::Size;
|
||||
#[cfg(feature = "x11")]
|
||||
use crate::platform_impl::x11::{ffi::XVisualInfo, XConnection};
|
||||
use crate::platform_impl::{
|
||||
x11::{ffi::XVisualInfo, XConnection},
|
||||
EventLoop as LinuxEventLoop, EventLoopWindowTarget as LinuxEventLoopWindowTarget,
|
||||
Window as LinuxWindow,
|
||||
};
|
||||
|
||||
// TODO: stupid hack so that glutin can do its work
|
||||
#[doc(hidden)]
|
||||
#[cfg(feature = "x11")]
|
||||
pub use crate::platform_impl::x11;
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
pub use crate::platform_impl::{x11::util::WindowType as XWindowType, XNotSupported};
|
||||
|
||||
/// Additional methods on `EventLoopWindowTarget` that are specific to Unix.
|
||||
pub trait EventLoopWindowTargetExtUnix {
|
||||
/// True if the `EventLoopWindowTarget` uses Wayland.
|
||||
#[cfg(feature = "wayland")]
|
||||
fn is_wayland(&self) -> bool;
|
||||
///
|
||||
|
||||
/// True if the `EventLoopWindowTarget` uses X11.
|
||||
#[cfg(feature = "x11")]
|
||||
fn is_x11(&self) -> bool;
|
||||
|
||||
#[doc(hidden)]
|
||||
#[cfg(feature = "x11")]
|
||||
fn xlib_xconnection(&self) -> Option<Arc<XConnection>>;
|
||||
|
||||
/// Returns a pointer to the `wl_display` object of wayland that is used by this
|
||||
@@ -40,35 +52,42 @@ pub trait EventLoopWindowTargetExtUnix {
|
||||
/// Returns `None` if the `EventLoop` doesn't use wayland (if it uses xlib for example).
|
||||
///
|
||||
/// The pointer will become invalid when the winit `EventLoop` is destroyed.
|
||||
#[cfg(feature = "wayland")]
|
||||
fn wayland_display(&self) -> Option<*mut raw::c_void>;
|
||||
}
|
||||
|
||||
impl<T> EventLoopWindowTargetExtUnix for EventLoopWindowTarget<T> {
|
||||
#[inline]
|
||||
#[cfg(feature = "wayland")]
|
||||
fn is_wayland(&self) -> bool {
|
||||
self.p.is_wayland()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn is_x11(&self) -> bool {
|
||||
!self.p.is_wayland()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[doc(hidden)]
|
||||
#[cfg(feature = "x11")]
|
||||
fn xlib_xconnection(&self) -> Option<Arc<XConnection>> {
|
||||
match self.p {
|
||||
LinuxEventLoopWindowTarget::X(ref e) => Some(e.x_connection().clone()),
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "wayland")]
|
||||
fn wayland_display(&self) -> Option<*mut raw::c_void> {
|
||||
match self.p {
|
||||
LinuxEventLoopWindowTarget::Wayland(ref p) => {
|
||||
Some(p.display().get_display_ptr() as *mut _)
|
||||
}
|
||||
#[cfg(feature = "x11")]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -82,6 +101,7 @@ pub trait EventLoopExtUnix {
|
||||
///
|
||||
/// If called outside the main thread. To initialize an X11 event loop outside
|
||||
/// the main thread, use [`new_x11_any_thread`](#tymethod.new_x11_any_thread).
|
||||
#[cfg(feature = "x11")]
|
||||
fn new_x11() -> Result<Self, XNotSupported>
|
||||
where
|
||||
Self: Sized;
|
||||
@@ -92,6 +112,7 @@ pub trait EventLoopExtUnix {
|
||||
///
|
||||
/// If called outside the main thread. To initialize a Wayland event loop outside
|
||||
/// the main thread, use [`new_wayland_any_thread`](#tymethod.new_wayland_any_thread).
|
||||
#[cfg(feature = "wayland")]
|
||||
fn new_wayland() -> Self
|
||||
where
|
||||
Self: Sized;
|
||||
@@ -108,6 +129,7 @@ pub trait EventLoopExtUnix {
|
||||
///
|
||||
/// This method bypasses the cross-platform compatibility requirement
|
||||
/// that `EventLoop` be created on the main thread.
|
||||
#[cfg(feature = "x11")]
|
||||
fn new_x11_any_thread() -> Result<Self, XNotSupported>
|
||||
where
|
||||
Self: Sized;
|
||||
@@ -116,6 +138,7 @@ pub trait EventLoopExtUnix {
|
||||
///
|
||||
/// This method bypasses the cross-platform compatibility requirement
|
||||
/// that `EventLoop` be created on the main thread.
|
||||
#[cfg(feature = "wayland")]
|
||||
fn new_wayland_any_thread() -> Self
|
||||
where
|
||||
Self: Sized;
|
||||
@@ -135,11 +158,13 @@ impl<T> EventLoopExtUnix for EventLoop<T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn new_x11_any_thread() -> Result<Self, XNotSupported> {
|
||||
LinuxEventLoop::new_x11_any_thread().map(wrap_ev)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "wayland")]
|
||||
fn new_wayland_any_thread() -> Self {
|
||||
wrap_ev(
|
||||
LinuxEventLoop::new_wayland_any_thread()
|
||||
@@ -149,11 +174,13 @@ impl<T> EventLoopExtUnix for EventLoop<T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn new_x11() -> Result<Self, XNotSupported> {
|
||||
LinuxEventLoop::new_x11().map(wrap_ev)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "wayland")]
|
||||
fn new_wayland() -> Self {
|
||||
wrap_ev(
|
||||
LinuxEventLoop::new_wayland()
|
||||
@@ -168,6 +195,7 @@ pub trait WindowExtUnix {
|
||||
/// Returns the ID of the `Window` xlib object that is used by this window.
|
||||
///
|
||||
/// Returns `None` if the window doesn't use xlib (if it uses wayland for example).
|
||||
#[cfg(feature = "x11")]
|
||||
fn xlib_window(&self) -> Option<raw::c_ulong>;
|
||||
|
||||
/// Returns a pointer to the `Display` object of xlib that is used by this window.
|
||||
@@ -175,14 +203,18 @@ pub trait WindowExtUnix {
|
||||
/// Returns `None` if the window doesn't use xlib (if it uses wayland for example).
|
||||
///
|
||||
/// The pointer will become invalid when the glutin `Window` is destroyed.
|
||||
#[cfg(feature = "x11")]
|
||||
fn xlib_display(&self) -> Option<*mut raw::c_void>;
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
fn xlib_screen_id(&self) -> Option<raw::c_int>;
|
||||
|
||||
#[doc(hidden)]
|
||||
#[cfg(feature = "x11")]
|
||||
fn xlib_xconnection(&self) -> Option<Arc<XConnection>>;
|
||||
|
||||
/// Set window urgency hint (`XUrgencyHint`). Only relevant on X.
|
||||
#[cfg(feature = "x11")]
|
||||
fn set_urgent(&self, is_urgent: bool);
|
||||
|
||||
/// This function returns the underlying `xcb_connection_t` of an xlib `Display`.
|
||||
@@ -190,6 +222,7 @@ pub trait WindowExtUnix {
|
||||
/// Returns `None` if the window doesn't use xlib (if it uses wayland for example).
|
||||
///
|
||||
/// The pointer will become invalid when the glutin `Window` is destroyed.
|
||||
#[cfg(feature = "x11")]
|
||||
fn xcb_connection(&self) -> Option<*mut raw::c_void>;
|
||||
|
||||
/// Returns a pointer to the `wl_surface` object of wayland that is used by this window.
|
||||
@@ -197,6 +230,7 @@ pub trait WindowExtUnix {
|
||||
/// Returns `None` if the window doesn't use wayland (if it uses xlib for example).
|
||||
///
|
||||
/// The pointer will become invalid when the glutin `Window` is destroyed.
|
||||
#[cfg(feature = "wayland")]
|
||||
fn wayland_surface(&self) -> Option<*mut raw::c_void>;
|
||||
|
||||
/// Returns a pointer to the `wl_display` object of wayland that is used by this window.
|
||||
@@ -204,9 +238,11 @@ pub trait WindowExtUnix {
|
||||
/// Returns `None` if the window doesn't use wayland (if it uses xlib for example).
|
||||
///
|
||||
/// The pointer will become invalid when the glutin `Window` is destroyed.
|
||||
#[cfg(feature = "wayland")]
|
||||
fn wayland_display(&self) -> Option<*mut raw::c_void>;
|
||||
|
||||
/// Sets the color theme of the client side window decorations on wayland
|
||||
#[cfg(feature = "wayland")]
|
||||
fn set_wayland_theme<T: Theme>(&self, theme: T);
|
||||
|
||||
/// Check if the window is ready for drawing
|
||||
@@ -221,73 +257,92 @@ pub trait WindowExtUnix {
|
||||
|
||||
impl WindowExtUnix for Window {
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn xlib_window(&self) -> Option<raw::c_ulong> {
|
||||
match self.window {
|
||||
LinuxWindow::X(ref w) => Some(w.xlib_window()),
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn xlib_display(&self) -> Option<*mut raw::c_void> {
|
||||
match self.window {
|
||||
LinuxWindow::X(ref w) => Some(w.xlib_display()),
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn xlib_screen_id(&self) -> Option<raw::c_int> {
|
||||
match self.window {
|
||||
LinuxWindow::X(ref w) => Some(w.xlib_screen_id()),
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[doc(hidden)]
|
||||
#[cfg(feature = "x11")]
|
||||
fn xlib_xconnection(&self) -> Option<Arc<XConnection>> {
|
||||
match self.window {
|
||||
LinuxWindow::X(ref w) => Some(w.xlib_xconnection()),
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn set_urgent(&self, is_urgent: bool) {
|
||||
if let LinuxWindow::X(ref w) = self.window {
|
||||
w.set_urgent(is_urgent);
|
||||
match self.window {
|
||||
LinuxWindow::X(ref w) => w.set_urgent(is_urgent),
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn xcb_connection(&self) -> Option<*mut raw::c_void> {
|
||||
match self.window {
|
||||
LinuxWindow::X(ref w) => Some(w.xcb_connection()),
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "wayland")]
|
||||
fn wayland_surface(&self) -> Option<*mut raw::c_void> {
|
||||
match self.window {
|
||||
LinuxWindow::Wayland(ref w) => Some(w.surface().as_ref().c_ptr() as *mut _),
|
||||
#[cfg(feature = "x11")]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "wayland")]
|
||||
fn wayland_display(&self) -> Option<*mut raw::c_void> {
|
||||
match self.window {
|
||||
LinuxWindow::Wayland(ref w) => Some(w.display().as_ref().c_ptr() as *mut _),
|
||||
LinuxWindow::Wayland(ref w) => Some(w.display().get_display_ptr() as *mut _),
|
||||
#[cfg(feature = "x11")]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "wayland")]
|
||||
fn set_wayland_theme<T: Theme>(&self, theme: T) {
|
||||
match self.window {
|
||||
LinuxWindow::Wayland(ref w) => w.set_theme(WaylandTheme(theme)),
|
||||
LinuxWindow::Wayland(ref w) => w.set_theme(theme),
|
||||
#[cfg(feature = "x11")]
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -300,20 +355,28 @@ impl WindowExtUnix for Window {
|
||||
|
||||
/// Additional methods on `WindowBuilder` that are specific to Unix.
|
||||
pub trait WindowBuilderExtUnix {
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_x11_visual<T>(self, visual_infos: *const T) -> Self;
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_x11_screen(self, screen_id: i32) -> Self;
|
||||
|
||||
/// Build window with `WM_CLASS` hint; defaults to the name of the binary. Only relevant on X11.
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_class(self, class: String, instance: String) -> Self;
|
||||
/// Build window with override-redirect flag; defaults to false. Only relevant on X11.
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_override_redirect(self, override_redirect: bool) -> Self;
|
||||
/// Build window with `_NET_WM_WINDOW_TYPE` hints; defaults to `Normal`. Only relevant on X11.
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_x11_window_type(self, x11_window_type: Vec<XWindowType>) -> Self;
|
||||
/// Build window with `_GTK_THEME_VARIANT` hint set to the specified value. Currently only relevant on X11.
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_gtk_theme_variant(self, variant: String) -> Self;
|
||||
/// Build window with resize increment hint. Only implemented on X11.
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_resize_increments<S: Into<Size>>(self, increments: S) -> Self;
|
||||
/// Build window with base size hint. Only implemented on X11.
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_base_size<S: Into<Size>>(self, base_size: S) -> Self;
|
||||
|
||||
/// Build window with a given application ID. It should match the `.desktop` file distributed with
|
||||
@@ -321,60 +384,72 @@ pub trait WindowBuilderExtUnix {
|
||||
///
|
||||
/// 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)
|
||||
#[cfg(feature = "wayland")]
|
||||
fn with_app_id(self, app_id: String) -> Self;
|
||||
}
|
||||
|
||||
impl WindowBuilderExtUnix for WindowBuilder {
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_x11_visual<T>(mut self, visual_infos: *const T) -> Self {
|
||||
self.platform_specific.visual_infos =
|
||||
Some(unsafe { ptr::read(visual_infos as *const XVisualInfo) });
|
||||
{
|
||||
self.platform_specific.visual_infos =
|
||||
Some(unsafe { ptr::read(visual_infos as *const XVisualInfo) });
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_x11_screen(mut self, screen_id: i32) -> Self {
|
||||
self.platform_specific.screen_id = Some(screen_id);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_class(mut self, instance: String, class: String) -> Self {
|
||||
self.platform_specific.class = Some((instance, class));
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_override_redirect(mut self, override_redirect: bool) -> Self {
|
||||
self.platform_specific.override_redirect = override_redirect;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_x11_window_type(mut self, x11_window_types: Vec<XWindowType>) -> Self {
|
||||
self.platform_specific.x11_window_types = x11_window_types;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_gtk_theme_variant(mut self, variant: String) -> Self {
|
||||
self.platform_specific.gtk_theme_variant = Some(variant);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_resize_increments<S: Into<Size>>(mut self, increments: S) -> Self {
|
||||
self.platform_specific.resize_increments = Some(increments.into());
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "x11")]
|
||||
fn with_base_size<S: Into<Size>>(mut self, base_size: S) -> Self {
|
||||
self.platform_specific.base_size = Some(base_size.into());
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "wayland")]
|
||||
fn with_app_id(mut self, app_id: String) -> Self {
|
||||
self.platform_specific.app_id = Some(app_id);
|
||||
self
|
||||
@@ -394,80 +469,50 @@ impl MonitorHandleExtUnix for MonitorHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper for implementing SCTK's theme trait.
|
||||
struct WaylandTheme<T: Theme>(T);
|
||||
|
||||
/// A theme for a Wayland's client side decorations.
|
||||
#[cfg(feature = "wayland")]
|
||||
pub trait Theme: Send + 'static {
|
||||
/// Primary color of the scheme.
|
||||
fn primary_color(&self, window_active: bool) -> [u8; 4];
|
||||
/// Title bar color.
|
||||
fn element_color(&self, element: Element, window_active: bool) -> ARGBColor;
|
||||
|
||||
/// Secondary color of the scheme.
|
||||
fn secondary_color(&self, window_active: bool) -> [u8; 4];
|
||||
/// Color for a given button part.
|
||||
fn button_color(
|
||||
&self,
|
||||
button: Button,
|
||||
state: ButtonState,
|
||||
foreground: bool,
|
||||
window_active: bool,
|
||||
) -> ARGBColor;
|
||||
|
||||
/// Color for the close button.
|
||||
fn close_button_color(&self, status: ButtonState) -> [u8; 4];
|
||||
|
||||
/// Icon color for the close button, defaults to the secondary color.
|
||||
#[allow(unused_variables)]
|
||||
fn close_button_icon_color(&self, status: ButtonState) -> [u8; 4] {
|
||||
self.secondary_color(true)
|
||||
}
|
||||
|
||||
/// Background color for the maximize button.
|
||||
fn maximize_button_color(&self, status: ButtonState) -> [u8; 4];
|
||||
|
||||
/// Icon color for the maximize button, defaults to the secondary color.
|
||||
#[allow(unused_variables)]
|
||||
fn maximize_button_icon_color(&self, status: ButtonState) -> [u8; 4] {
|
||||
self.secondary_color(true)
|
||||
}
|
||||
|
||||
/// Background color for the minimize button.
|
||||
fn minimize_button_color(&self, status: ButtonState) -> [u8; 4];
|
||||
|
||||
/// Icon color for the minimize button, defaults to the secondary color.
|
||||
#[allow(unused_variables)]
|
||||
fn minimize_button_icon_color(&self, status: ButtonState) -> [u8; 4] {
|
||||
self.secondary_color(true)
|
||||
/// Font name and the size for the title bar.
|
||||
///
|
||||
/// By default the font is `sans-serif` at the size of 11.
|
||||
///
|
||||
/// Returning `None` means that title won't be drawn.
|
||||
fn font(&self) -> Option<(String, f32)> {
|
||||
// Not having any title isn't something desirable for the users, so setting it to
|
||||
// something generic.
|
||||
Some((String::from("sans-serif"), 11.))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Theme> SCTKTheme for WaylandTheme<T> {
|
||||
fn get_primary_color(&self, active: bool) -> [u8; 4] {
|
||||
self.0.primary_color(active)
|
||||
}
|
||||
/// A button on Wayland's client side decorations.
|
||||
#[cfg(feature = "wayland")]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Button {
|
||||
/// Button that maximizes the window.
|
||||
Maximize,
|
||||
|
||||
fn get_secondary_color(&self, active: bool) -> [u8; 4] {
|
||||
self.0.secondary_color(active)
|
||||
}
|
||||
/// Button that minimizes the window.
|
||||
Minimize,
|
||||
|
||||
fn get_close_button_color(&self, status: SCTKButtonState) -> [u8; 4] {
|
||||
self.0.close_button_color(ButtonState::from_sctk(status))
|
||||
}
|
||||
|
||||
fn get_close_button_icon_color(&self, status: SCTKButtonState) -> [u8; 4] {
|
||||
self.0.close_button_color(ButtonState::from_sctk(status))
|
||||
}
|
||||
|
||||
fn get_maximize_button_color(&self, status: SCTKButtonState) -> [u8; 4] {
|
||||
self.0.maximize_button_color(ButtonState::from_sctk(status))
|
||||
}
|
||||
|
||||
fn get_maximize_button_icon_color(&self, status: SCTKButtonState) -> [u8; 4] {
|
||||
self.0
|
||||
.maximize_button_icon_color(ButtonState::from_sctk(status))
|
||||
}
|
||||
|
||||
fn get_minimize_button_color(&self, status: SCTKButtonState) -> [u8; 4] {
|
||||
self.0.minimize_button_color(ButtonState::from_sctk(status))
|
||||
}
|
||||
|
||||
fn get_minimize_button_icon_color(&self, status: SCTKButtonState) -> [u8; 4] {
|
||||
self.0
|
||||
.minimize_button_icon_color(ButtonState::from_sctk(status))
|
||||
}
|
||||
/// Button that closes the window.
|
||||
Close,
|
||||
}
|
||||
|
||||
/// A button state of the button on Wayland's client side decorations.
|
||||
#[cfg(feature = "wayland")]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ButtonState {
|
||||
/// Button is being hovered over by pointer.
|
||||
Hovered,
|
||||
@@ -477,12 +522,24 @@ pub enum ButtonState {
|
||||
Disabled,
|
||||
}
|
||||
|
||||
impl ButtonState {
|
||||
fn from_sctk(button_state: SCTKButtonState) -> Self {
|
||||
match button_state {
|
||||
SCTKButtonState::Hovered => Self::Hovered,
|
||||
SCTKButtonState::Idle => Self::Idle,
|
||||
SCTKButtonState::Disabled => Self::Disabled,
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "wayland")]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Element {
|
||||
/// Bar itself.
|
||||
Bar,
|
||||
|
||||
/// Separator between window and title bar.
|
||||
Separator,
|
||||
|
||||
/// Title bar text.
|
||||
Text,
|
||||
}
|
||||
|
||||
#[cfg(feature = "wayland")]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ARGBColor {
|
||||
pub a: u8,
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ use stdweb::web::html_element::CanvasElement;
|
||||
#[cfg(feature = "stdweb")]
|
||||
pub trait WindowExtStdweb {
|
||||
fn canvas(&self) -> CanvasElement;
|
||||
|
||||
/// Whether the browser reports the preferred color scheme to be "dark".
|
||||
fn is_dark_mode(&self) -> bool;
|
||||
}
|
||||
|
||||
#[cfg(feature = "web-sys")]
|
||||
@@ -22,6 +25,9 @@ use web_sys::HtmlCanvasElement;
|
||||
#[cfg(feature = "web-sys")]
|
||||
pub trait WindowExtWebSys {
|
||||
fn canvas(&self) -> HtmlCanvasElement;
|
||||
|
||||
/// Whether the browser reports the preferred color scheme to be "dark".
|
||||
fn is_dark_mode(&self) -> bool;
|
||||
}
|
||||
|
||||
#[cfg(feature = "stdweb")]
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
#![cfg(target_os = "windows")]
|
||||
|
||||
use std::os::raw::c_void;
|
||||
use std::path::Path;
|
||||
|
||||
use libc;
|
||||
use winapi::shared::minwindef::WORD;
|
||||
use winapi::shared::windef::HWND;
|
||||
|
||||
use crate::{
|
||||
dpi::PhysicalSize,
|
||||
event::DeviceId,
|
||||
event_loop::EventLoop,
|
||||
monitor::MonitorHandle,
|
||||
platform_impl::EventLoop as WindowsEventLoop,
|
||||
window::{Icon, Window, WindowBuilder},
|
||||
platform_impl::{EventLoop as WindowsEventLoop, WinIcon},
|
||||
window::{BadIcon, Icon, Window, WindowBuilder},
|
||||
};
|
||||
|
||||
/// Additional methods on `EventLoop` that are specific to Windows.
|
||||
@@ -114,6 +117,14 @@ pub trait WindowBuilderExtWindows {
|
||||
|
||||
/// This sets `WS_EX_NOREDIRECTIONBITMAP`.
|
||||
fn with_no_redirection_bitmap(self, flag: bool) -> WindowBuilder;
|
||||
|
||||
/// Enables or disables drag and drop support (enabled by default). Will interfere with other crates
|
||||
/// that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED` instead of
|
||||
/// `COINIT_APARTMENTTHREADED`) on the same thread. Note that winit may still attempt to initialize
|
||||
/// COM API regardless of this option. Currently only fullscreen mode does that, but there may be more in the future.
|
||||
/// If you need COM API with `COINIT_MULTITHREADED` you must initialize it before calling any winit functions.
|
||||
/// See https://docs.microsoft.com/en-us/windows/win32/api/objbase/nf-objbase-coinitialize#remarks for more information.
|
||||
fn with_drag_and_drop(self, flag: bool) -> WindowBuilder;
|
||||
}
|
||||
|
||||
impl WindowBuilderExtWindows for WindowBuilder {
|
||||
@@ -134,6 +145,12 @@ impl WindowBuilderExtWindows for WindowBuilder {
|
||||
self.platform_specific.no_redirection_bitmap = flag;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_drag_and_drop(mut self, flag: bool) -> WindowBuilder {
|
||||
self.platform_specific.drag_and_drop = flag;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on `MonitorHandle` that are specific to Windows.
|
||||
@@ -171,3 +188,40 @@ impl DeviceIdExtWindows for DeviceId {
|
||||
self.0.persistent_identifier()
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on `Icon` that are specific to Windows.
|
||||
pub trait IconExtWindows: Sized {
|
||||
/// Create an icon from a file path.
|
||||
///
|
||||
/// Specify `size` to load a specific icon size from the file, or `None` to load the default
|
||||
/// icon size from the file.
|
||||
///
|
||||
/// In cases where the specified size does not exist in the file, Windows may perform scaling
|
||||
/// to get an icon of the desired size.
|
||||
fn from_path<P: AsRef<Path>>(path: P, size: Option<PhysicalSize<u32>>)
|
||||
-> Result<Self, BadIcon>;
|
||||
|
||||
/// Create an icon from a resource embedded in this executable or library.
|
||||
///
|
||||
/// Specify `size` to load a specific icon size from the file, or `None` to load the default
|
||||
/// icon size from the file.
|
||||
///
|
||||
/// In cases where the specified size does not exist in the file, Windows may perform scaling
|
||||
/// to get an icon of the desired size.
|
||||
fn from_resource(ordinal: WORD, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon>;
|
||||
}
|
||||
|
||||
impl IconExtWindows for Icon {
|
||||
fn from_path<P: AsRef<Path>>(
|
||||
path: P,
|
||||
size: Option<PhysicalSize<u32>>,
|
||||
) -> Result<Self, BadIcon> {
|
||||
let win_icon = WinIcon::from_path(path, size)?;
|
||||
Ok(Icon { inner: win_icon })
|
||||
}
|
||||
|
||||
fn from_resource(ordinal: WORD, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon> {
|
||||
let win_icon = WinIcon::from_resource(ordinal, size)?;
|
||||
Ok(Icon { inner: win_icon })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
#![allow(dead_code)]
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(non_upper_case_globals)]
|
||||
|
||||
use libc;
|
||||
use std::os::raw;
|
||||
|
||||
#[link(name = "android")]
|
||||
#[link(name = "EGL")]
|
||||
#[link(name = "GLESv2")]
|
||||
extern "C" {}
|
||||
|
||||
/**
|
||||
** asset_manager.h
|
||||
**/
|
||||
pub type AAssetManager = raw::c_void;
|
||||
|
||||
/**
|
||||
** native_window.h
|
||||
**/
|
||||
pub type ANativeWindow = raw::c_void;
|
||||
|
||||
extern "C" {
|
||||
pub fn ANativeWindow_getHeight(window: *const ANativeWindow) -> libc::int32_t;
|
||||
pub fn ANativeWindow_getWidth(window: *const ANativeWindow) -> libc::int32_t;
|
||||
}
|
||||
|
||||
/**
|
||||
** native_activity.h
|
||||
**/
|
||||
pub type JavaVM = ();
|
||||
pub type JNIEnv = ();
|
||||
pub type jobject = *const libc::c_void;
|
||||
|
||||
pub type AInputQueue = (); // FIXME: wrong
|
||||
pub type ARect = (); // FIXME: wrong
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ANativeActivity {
|
||||
pub callbacks: *mut ANativeActivityCallbacks,
|
||||
pub vm: *mut JavaVM,
|
||||
pub env: *mut JNIEnv,
|
||||
pub clazz: jobject,
|
||||
pub internalDataPath: *const libc::c_char,
|
||||
pub externalDataPath: *const libc::c_char,
|
||||
pub sdkVersion: libc::int32_t,
|
||||
pub instance: *mut libc::c_void,
|
||||
pub assetManager: *mut AAssetManager,
|
||||
pub obbPath: *const libc::c_char,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ANativeActivityCallbacks {
|
||||
pub onStart: extern "C" fn(*mut ANativeActivity),
|
||||
pub onResume: extern "C" fn(*mut ANativeActivity),
|
||||
pub onSaveInstanceState: extern "C" fn(*mut ANativeActivity, *mut libc::size_t),
|
||||
pub onPause: extern "C" fn(*mut ANativeActivity),
|
||||
pub onStop: extern "C" fn(*mut ANativeActivity),
|
||||
pub onDestroy: extern "C" fn(*mut ANativeActivity),
|
||||
pub onWindowFocusChanged: extern "C" fn(*mut ANativeActivity, libc::c_int),
|
||||
pub onNativeWindowCreated: extern "C" fn(*mut ANativeActivity, *const ANativeWindow),
|
||||
pub onNativeWindowResized: extern "C" fn(*mut ANativeActivity, *const ANativeWindow),
|
||||
pub onNativeWindowRedrawNeeded: extern "C" fn(*mut ANativeActivity, *const ANativeWindow),
|
||||
pub onNativeWindowDestroyed: extern "C" fn(*mut ANativeActivity, *const ANativeWindow),
|
||||
pub onInputQueueCreated: extern "C" fn(*mut ANativeActivity, *mut AInputQueue),
|
||||
pub onInputQueueDestroyed: extern "C" fn(*mut ANativeActivity, *mut AInputQueue),
|
||||
pub onContentRectChanged: extern "C" fn(*mut ANativeActivity, *const ARect),
|
||||
pub onConfigurationChanged: extern "C" fn(*mut ANativeActivity),
|
||||
pub onLowMemory: extern "C" fn(*mut ANativeActivity),
|
||||
}
|
||||
|
||||
/**
|
||||
** looper.h
|
||||
**/
|
||||
pub type ALooper = ();
|
||||
|
||||
#[link(name = "android")]
|
||||
extern "C" {
|
||||
pub fn ALooper_forThread() -> *const ALooper;
|
||||
pub fn ALooper_acquire(looper: *const ALooper);
|
||||
pub fn ALooper_release(looper: *const ALooper);
|
||||
pub fn ALooper_prepare(opts: libc::c_int) -> *const ALooper;
|
||||
pub fn ALooper_pollOnce(
|
||||
timeoutMillis: libc::c_int,
|
||||
outFd: *mut libc::c_int,
|
||||
outEvents: *mut libc::c_int,
|
||||
outData: *mut *mut libc::c_void,
|
||||
) -> libc::c_int;
|
||||
pub fn ALooper_pollAll(
|
||||
timeoutMillis: libc::c_int,
|
||||
outFd: *mut libc::c_int,
|
||||
outEvents: *mut libc::c_int,
|
||||
outData: *mut *mut libc::c_void,
|
||||
) -> libc::c_int;
|
||||
pub fn ALooper_wake(looper: *const ALooper);
|
||||
pub fn ALooper_addFd(
|
||||
looper: *const ALooper,
|
||||
fd: libc::c_int,
|
||||
ident: libc::c_int,
|
||||
events: libc::c_int,
|
||||
callback: ALooper_callbackFunc,
|
||||
data: *mut libc::c_void,
|
||||
) -> libc::c_int;
|
||||
pub fn ALooper_removeFd(looper: *const ALooper, fd: libc::c_int) -> libc::c_int;
|
||||
}
|
||||
|
||||
pub const ALOOPER_PREPARE_ALLOW_NON_CALLBACKS: libc::c_int = 1 << 0;
|
||||
|
||||
pub const ALOOPER_POLL_WAKE: libc::c_int = -1;
|
||||
pub const ALOOPER_POLL_CALLBACK: libc::c_int = -2;
|
||||
pub const ALOOPER_POLL_TIMEOUT: libc::c_int = -3;
|
||||
pub const ALOOPER_POLL_ERROR: libc::c_int = -4;
|
||||
|
||||
pub const ALOOPER_EVENT_INPUT: libc::c_int = 1 << 0;
|
||||
pub const ALOOPER_EVENT_OUTPUT: libc::c_int = 1 << 1;
|
||||
pub const ALOOPER_EVENT_ERROR: libc::c_int = 1 << 2;
|
||||
pub const ALOOPER_EVENT_HANGUP: libc::c_int = 1 << 3;
|
||||
pub const ALOOPER_EVENT_INVALID: libc::c_int = 1 << 4;
|
||||
|
||||
pub type ALooper_callbackFunc =
|
||||
extern "C" fn(libc::c_int, libc::c_int, *mut libc::c_void) -> libc::c_int;
|
||||
@@ -1,448 +1,587 @@
|
||||
#![cfg(target_os = "android")]
|
||||
|
||||
extern crate android_glue;
|
||||
|
||||
mod ffi;
|
||||
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::VecDeque,
|
||||
fmt,
|
||||
os::raw::c_void,
|
||||
sync::mpsc::{channel, Receiver},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
error::{ExternalError, NotSupportedError},
|
||||
events::{Touch, TouchPhase},
|
||||
window::MonitorHandle as RootMonitorHandle,
|
||||
CreationError, CursorIcon, Event, LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize,
|
||||
WindowAttributes, WindowEvent, WindowId as RootWindowId,
|
||||
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
|
||||
error, event,
|
||||
event_loop::{self, ControlFlow},
|
||||
monitor, window,
|
||||
};
|
||||
use ndk::{
|
||||
configuration::Configuration,
|
||||
event::{InputEvent, MotionAction},
|
||||
looper::{ForeignLooper, Poll, ThreadLooper},
|
||||
};
|
||||
use ndk_glue::{Event, Rect};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use raw_window_handle::{android::AndroidHandle, RawWindowHandle};
|
||||
use CreationError::OsError;
|
||||
|
||||
pub type OsError = std::io::Error;
|
||||
|
||||
pub struct EventLoop {
|
||||
event_rx: Receiver<android_glue::Event>,
|
||||
suspend_callback: RefCell<Option<Box<dyn Fn(bool) -> ()>>>,
|
||||
lazy_static! {
|
||||
static ref CONFIG: RwLock<Configuration> = RwLock::new(Configuration::new());
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct EventLoopProxy;
|
||||
enum EventSource {
|
||||
Callback,
|
||||
InputQueue,
|
||||
User,
|
||||
}
|
||||
|
||||
impl EventLoop {
|
||||
pub fn new() -> EventLoop {
|
||||
let (tx, rx) = channel();
|
||||
android_glue::add_sender(tx);
|
||||
EventLoop {
|
||||
event_rx: rx,
|
||||
suspend_callback: Default::default(),
|
||||
fn poll(poll: Poll) -> Option<EventSource> {
|
||||
match poll {
|
||||
Poll::Event { data, .. } => match data as usize {
|
||||
0 => Some(EventSource::Callback),
|
||||
1 => Some(EventSource::InputQueue),
|
||||
_ => unreachable!(),
|
||||
},
|
||||
Poll::Timeout => None,
|
||||
Poll::Wake => Some(EventSource::User),
|
||||
Poll::Callback => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoop<T: 'static> {
|
||||
window_target: event_loop::EventLoopWindowTarget<T>,
|
||||
user_queue: Arc<Mutex<VecDeque<T>>>,
|
||||
first_event: Option<EventSource>,
|
||||
start_cause: event::StartCause,
|
||||
looper: ThreadLooper,
|
||||
running: bool,
|
||||
}
|
||||
|
||||
macro_rules! call_event_handler {
|
||||
( $event_handler:expr, $window_target:expr, $cf:expr, $event:expr ) => {{
|
||||
if $cf != ControlFlow::Exit {
|
||||
$event_handler($event, $window_target, &mut $cf);
|
||||
} else {
|
||||
$event_handler($event, $window_target, &mut ControlFlow::Exit);
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoop<T> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
window_target: event_loop::EventLoopWindowTarget {
|
||||
p: EventLoopWindowTarget {
|
||||
_marker: std::marker::PhantomData,
|
||||
},
|
||||
_marker: std::marker::PhantomData,
|
||||
},
|
||||
user_queue: Default::default(),
|
||||
first_event: None,
|
||||
start_cause: event::StartCause::Init,
|
||||
looper: ThreadLooper::for_thread().unwrap(),
|
||||
running: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
let mut rb = VecDeque::with_capacity(1);
|
||||
rb.push_back(MonitorHandle);
|
||||
rb
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> MonitorHandle {
|
||||
MonitorHandle
|
||||
}
|
||||
|
||||
pub fn poll_events<F>(&mut self, mut callback: F)
|
||||
pub fn run<F>(mut self, event_handler: F) -> !
|
||||
where
|
||||
F: FnMut(::Event),
|
||||
F: 'static
|
||||
+ FnMut(event::Event<'_, T>, &event_loop::EventLoopWindowTarget<T>, &mut ControlFlow),
|
||||
{
|
||||
while let Ok(event) = self.event_rx.try_recv() {
|
||||
let e = match event {
|
||||
android_glue::Event::EventMotion(motion) => {
|
||||
let dpi_factor = MonitorHandle.scale_factor();
|
||||
let location = LogicalPosition::from_physical(
|
||||
(motion.x as f64, motion.y as f64),
|
||||
dpi_factor,
|
||||
self.run_return(event_handler);
|
||||
::std::process::exit(0);
|
||||
}
|
||||
|
||||
pub fn run_return<F>(&mut self, mut event_handler: F)
|
||||
where
|
||||
F: FnMut(event::Event<'_, T>, &event_loop::EventLoopWindowTarget<T>, &mut ControlFlow),
|
||||
{
|
||||
let mut control_flow = ControlFlow::default();
|
||||
|
||||
'event_loop: loop {
|
||||
call_event_handler!(
|
||||
event_handler,
|
||||
self.window_target(),
|
||||
control_flow,
|
||||
event::Event::NewEvents(self.start_cause)
|
||||
);
|
||||
|
||||
let mut redraw = false;
|
||||
let mut resized = false;
|
||||
|
||||
match self.first_event.take() {
|
||||
Some(EventSource::Callback) => match ndk_glue::poll_events().unwrap() {
|
||||
Event::WindowCreated => {
|
||||
call_event_handler!(
|
||||
event_handler,
|
||||
self.window_target(),
|
||||
control_flow,
|
||||
event::Event::Resumed
|
||||
);
|
||||
}
|
||||
Event::WindowResized => resized = true,
|
||||
Event::WindowRedrawNeeded => redraw = true,
|
||||
Event::WindowDestroyed => {
|
||||
call_event_handler!(
|
||||
event_handler,
|
||||
self.window_target(),
|
||||
control_flow,
|
||||
event::Event::Suspended
|
||||
);
|
||||
}
|
||||
Event::Pause => self.running = false,
|
||||
Event::Resume => self.running = true,
|
||||
Event::ConfigChanged => {
|
||||
let am = ndk_glue::native_activity().asset_manager();
|
||||
let config = Configuration::from_asset_manager(&am);
|
||||
let old_scale_factor = MonitorHandle.scale_factor();
|
||||
*CONFIG.write().unwrap() = config;
|
||||
let scale_factor = MonitorHandle.scale_factor();
|
||||
if (scale_factor - old_scale_factor).abs() < f64::EPSILON {
|
||||
let mut size = MonitorHandle.size();
|
||||
let event = event::Event::WindowEvent {
|
||||
window_id: window::WindowId(WindowId),
|
||||
event: event::WindowEvent::ScaleFactorChanged {
|
||||
new_inner_size: &mut size,
|
||||
scale_factor,
|
||||
},
|
||||
};
|
||||
call_event_handler!(
|
||||
event_handler,
|
||||
self.window_target(),
|
||||
control_flow,
|
||||
event
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Some(EventSource::InputQueue) => {
|
||||
if let Some(input_queue) = ndk_glue::input_queue().as_ref() {
|
||||
while let Some(event) = input_queue.get_event() {
|
||||
println!("event {:?}", event);
|
||||
if let Some(event) = input_queue.pre_dispatch(event) {
|
||||
let window_id = window::WindowId(WindowId);
|
||||
let device_id = event::DeviceId(DeviceId);
|
||||
match &event {
|
||||
InputEvent::MotionEvent(motion_event) => {
|
||||
let phase = match motion_event.action() {
|
||||
MotionAction::Down => Some(event::TouchPhase::Started),
|
||||
MotionAction::Up => Some(event::TouchPhase::Ended),
|
||||
MotionAction::Move => Some(event::TouchPhase::Moved),
|
||||
MotionAction::Cancel => {
|
||||
Some(event::TouchPhase::Cancelled)
|
||||
}
|
||||
_ => None, // TODO mouse events
|
||||
};
|
||||
let pointer = motion_event.pointer_at_index(0);
|
||||
let location = PhysicalPosition {
|
||||
x: pointer.x() as _,
|
||||
y: pointer.y() as _,
|
||||
};
|
||||
|
||||
if let Some(phase) = phase {
|
||||
let event = event::Event::WindowEvent {
|
||||
window_id,
|
||||
event: event::WindowEvent::Touch(event::Touch {
|
||||
device_id,
|
||||
phase,
|
||||
location,
|
||||
id: 0,
|
||||
force: None,
|
||||
}),
|
||||
};
|
||||
call_event_handler!(
|
||||
event_handler,
|
||||
self.window_target(),
|
||||
control_flow,
|
||||
event
|
||||
);
|
||||
}
|
||||
}
|
||||
InputEvent::KeyEvent(_) => {} // TODO
|
||||
};
|
||||
input_queue.finish_event(event, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(EventSource::User) => {
|
||||
let mut user_queue = self.user_queue.lock().unwrap();
|
||||
while let Some(event) = user_queue.pop_front() {
|
||||
call_event_handler!(
|
||||
event_handler,
|
||||
self.window_target(),
|
||||
control_flow,
|
||||
event::Event::UserEvent(event)
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
call_event_handler!(
|
||||
event_handler,
|
||||
self.window_target(),
|
||||
control_flow,
|
||||
event::Event::MainEventsCleared
|
||||
);
|
||||
|
||||
if resized && self.running {
|
||||
let size = MonitorHandle.size();
|
||||
let event = event::Event::WindowEvent {
|
||||
window_id: window::WindowId(WindowId),
|
||||
event: event::WindowEvent::Resized(size),
|
||||
};
|
||||
call_event_handler!(event_handler, self.window_target(), control_flow, event);
|
||||
}
|
||||
|
||||
if redraw && self.running {
|
||||
let event = event::Event::RedrawRequested(window::WindowId(WindowId));
|
||||
call_event_handler!(event_handler, self.window_target(), control_flow, event);
|
||||
}
|
||||
|
||||
call_event_handler!(
|
||||
event_handler,
|
||||
self.window_target(),
|
||||
control_flow,
|
||||
event::Event::RedrawEventsCleared
|
||||
);
|
||||
|
||||
match control_flow {
|
||||
ControlFlow::Exit => {
|
||||
self.first_event = poll(
|
||||
self.looper
|
||||
.poll_once_timeout(Duration::from_millis(0))
|
||||
.unwrap(),
|
||||
);
|
||||
Some(Event::WindowEvent {
|
||||
window_id: RootWindowId(WindowId),
|
||||
event: WindowEvent::Touch(Touch {
|
||||
phase: match motion.action {
|
||||
android_glue::MotionAction::Down => TouchPhase::Started,
|
||||
android_glue::MotionAction::Move => TouchPhase::Moved,
|
||||
android_glue::MotionAction::Up => TouchPhase::Ended,
|
||||
android_glue::MotionAction::Cancel => TouchPhase::Cancelled,
|
||||
},
|
||||
location,
|
||||
force: None, // TODO
|
||||
id: motion.pointer_id as u64,
|
||||
device_id: DEVICE_ID,
|
||||
}),
|
||||
})
|
||||
self.start_cause = event::StartCause::WaitCancelled {
|
||||
start: Instant::now(),
|
||||
requested_resume: None,
|
||||
};
|
||||
break 'event_loop;
|
||||
}
|
||||
android_glue::Event::InitWindow => {
|
||||
// The activity went to foreground.
|
||||
if let Some(cb) = self.suspend_callback.borrow().as_ref() {
|
||||
(*cb)(false);
|
||||
ControlFlow::Poll => {
|
||||
self.first_event = poll(
|
||||
self.looper
|
||||
.poll_all_timeout(Duration::from_millis(0))
|
||||
.unwrap(),
|
||||
);
|
||||
self.start_cause = event::StartCause::Poll;
|
||||
}
|
||||
ControlFlow::Wait => {
|
||||
self.first_event = poll(self.looper.poll_all().unwrap());
|
||||
self.start_cause = event::StartCause::WaitCancelled {
|
||||
start: Instant::now(),
|
||||
requested_resume: None,
|
||||
}
|
||||
Some(Event::Resumed)
|
||||
}
|
||||
android_glue::Event::TermWindow => {
|
||||
// The activity went to background.
|
||||
if let Some(cb) = self.suspend_callback.borrow().as_ref() {
|
||||
(*cb)(true);
|
||||
}
|
||||
Some(Event::Suspended)
|
||||
}
|
||||
android_glue::Event::WindowResized | android_glue::Event::ConfigChanged => {
|
||||
// Activity Orientation changed or resized.
|
||||
let native_window = unsafe { android_glue::native_window() };
|
||||
if native_window.is_null() {
|
||||
None
|
||||
ControlFlow::WaitUntil(instant) => {
|
||||
let start = Instant::now();
|
||||
let duration = if instant <= start {
|
||||
Duration::default()
|
||||
} else {
|
||||
let dpi_factor = MonitorHandle.scale_factor();
|
||||
let physical_size = MonitorHandle.size();
|
||||
let size = LogicalSize::from_physical(physical_size, dpi_factor);
|
||||
Some(Event::WindowEvent {
|
||||
window_id: RootWindowId(WindowId),
|
||||
event: WindowEvent::Resized(size),
|
||||
})
|
||||
instant - start
|
||||
};
|
||||
self.first_event = poll(self.looper.poll_all_timeout(duration).unwrap());
|
||||
self.start_cause = if self.first_event.is_some() {
|
||||
event::StartCause::WaitCancelled {
|
||||
start,
|
||||
requested_resume: Some(instant),
|
||||
}
|
||||
} else {
|
||||
event::StartCause::ResumeTimeReached {
|
||||
start,
|
||||
requested_resume: instant,
|
||||
}
|
||||
}
|
||||
}
|
||||
android_glue::Event::WindowRedrawNeeded => {
|
||||
// The activity needs to be redrawn.
|
||||
Some(Event::WindowEvent {
|
||||
window_id: RootWindowId(WindowId),
|
||||
event: WindowEvent::Redraw,
|
||||
})
|
||||
}
|
||||
android_glue::Event::Wake => Some(Event::Awakened),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(event) = e {
|
||||
callback(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_suspend_callback(&self, cb: Option<Box<dyn Fn(bool) -> ()>>) {
|
||||
*self.suspend_callback.borrow_mut() = cb;
|
||||
pub fn window_target(&self) -> &event_loop::EventLoopWindowTarget<T> {
|
||||
&self.window_target
|
||||
}
|
||||
|
||||
pub fn run_forever<F>(&mut self, mut callback: F)
|
||||
where
|
||||
F: FnMut(::Event) -> ::ControlFlow,
|
||||
{
|
||||
// Yeah that's a very bad implementation.
|
||||
loop {
|
||||
let mut control_flow = ::ControlFlow::Continue;
|
||||
self.poll_events(|e| {
|
||||
if let ::ControlFlow::Break = callback(e) {
|
||||
control_flow = ::ControlFlow::Break;
|
||||
}
|
||||
});
|
||||
if let ::ControlFlow::Break = control_flow {
|
||||
break;
|
||||
}
|
||||
::std::thread::sleep(::std::time::Duration::from_millis(5));
|
||||
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||
EventLoopProxy {
|
||||
queue: self.user_queue.clone(),
|
||||
looper: ForeignLooper::for_thread().expect("called from event loop thread"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_proxy(&self) -> EventLoopProxy {
|
||||
EventLoopProxy
|
||||
}
|
||||
}
|
||||
|
||||
impl EventLoopProxy {
|
||||
pub fn wakeup(&self) -> Result<(), ::EventLoopClosed<()>> {
|
||||
android_glue::wake_event_loop();
|
||||
pub struct EventLoopProxy<T: 'static> {
|
||||
queue: Arc<Mutex<VecDeque<T>>>,
|
||||
looper: ForeignLooper,
|
||||
}
|
||||
|
||||
impl<T> EventLoopProxy<T> {
|
||||
pub fn send_event(&self, event: T) -> Result<(), event_loop::EventLoopClosed<T>> {
|
||||
self.queue.lock().unwrap().push_back(event);
|
||||
self.looper.wake();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
impl<T> Clone for EventLoopProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
EventLoopProxy {
|
||||
queue: self.queue.clone(),
|
||||
looper: self.looper.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoopWindowTarget<T: 'static> {
|
||||
_marker: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoopWindowTarget<T> {
|
||||
pub fn primary_monitor(&self) -> Option<monitor::MonitorHandle> {
|
||||
Some(monitor::MonitorHandle {
|
||||
inner: MonitorHandle,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
let mut v = VecDeque::with_capacity(1);
|
||||
v.push_back(MonitorHandle);
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct WindowId;
|
||||
|
||||
impl WindowId {
|
||||
pub unsafe fn dummy() -> Self {
|
||||
pub fn dummy() -> Self {
|
||||
WindowId
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct DeviceId;
|
||||
|
||||
impl DeviceId {
|
||||
pub unsafe fn dummy() -> Self {
|
||||
pub fn dummy() -> Self {
|
||||
DeviceId
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Window {
|
||||
native_window: *const c_void,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MonitorHandle;
|
||||
|
||||
impl fmt::Debug for MonitorHandle {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
#[derive(Debug)]
|
||||
struct MonitorHandle {
|
||||
name: Option<String>,
|
||||
dimensions: PhysicalSize<u32>,
|
||||
position: PhysicalPosition<i32>,
|
||||
scale_factor: f64,
|
||||
}
|
||||
|
||||
let monitor_id_proxy = MonitorHandle {
|
||||
name: self.name(),
|
||||
dimensions: self.size(),
|
||||
position: self.outer_position(),
|
||||
scale_factor: self.scale_factor(),
|
||||
};
|
||||
|
||||
monitor_id_proxy.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl MonitorHandle {
|
||||
#[inline]
|
||||
pub fn name(&self) -> Option<String> {
|
||||
Some("Primary".to_string())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
unsafe {
|
||||
let window = android_glue::native_window();
|
||||
(
|
||||
ffi::ANativeWindow_getWidth(window) as f64,
|
||||
ffi::ANativeWindow_getHeight(window) as f64,
|
||||
)
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn outer_position(&self) -> PhysicalPosition<i32> {
|
||||
// Android assumes single screen
|
||||
(0, 0).into()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
1.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct PlatformSpecificWindowBuilderAttributes;
|
||||
#[derive(Clone, Default)]
|
||||
pub struct PlatformSpecificHeadlessBuilderAttributes;
|
||||
|
||||
pub struct Window;
|
||||
|
||||
impl Window {
|
||||
pub fn new(
|
||||
_: &EventLoop,
|
||||
win_attribs: WindowAttributes,
|
||||
pub fn new<T: 'static>(
|
||||
_el: &EventLoopWindowTarget<T>,
|
||||
_window_attrs: window::WindowAttributes,
|
||||
_: PlatformSpecificWindowBuilderAttributes,
|
||||
) -> Result<Window, CreationError> {
|
||||
let native_window = unsafe { android_glue::native_window() };
|
||||
if native_window.is_null() {
|
||||
return Err(OsError(format!("Android's native window is null")));
|
||||
}
|
||||
|
||||
android_glue::set_multitouch(true);
|
||||
|
||||
Ok(Window {
|
||||
native_window: native_window as *const _,
|
||||
})
|
||||
) -> Result<Self, error::OsError> {
|
||||
// FIXME this ignores requested window attributes
|
||||
Ok(Self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn native_window(&self) -> *const c_void {
|
||||
self.native_window
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_title(&self, _: &str) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn show(&self) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn hide(&self) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn outer_position(&self) -> Option<LogicalPosition<f64>> {
|
||||
// N/A
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn inner_position(&self) -> Option<LogicalPosition<f64>> {
|
||||
// N/A
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_outer_position(&self, _position: LogicalPosition<f64>) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_min_inner_size(&self, _dimensions: Option<LogicalSize<f64>>) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_max_inner_size(&self, _dimensions: Option<LogicalSize<f64>>) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_resizable(&self, _resizable: bool) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn inner_size(&self) -> Option<LogicalSize<f64>> {
|
||||
if self.native_window.is_null() {
|
||||
None
|
||||
} else {
|
||||
let dpi_factor = self.scale_factor();
|
||||
let physical_size = self.current_monitor().size();
|
||||
Some(LogicalSize::from_physical(physical_size, dpi_factor))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn outer_size(&self) -> Option<LogicalSize<f64>> {
|
||||
self.inner_size()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_inner_size(&self, _size: LogicalSize<f64>) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
self.current_monitor().scale_factor()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_icon(&self, _: CursorIcon) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_grab(&self, _grab: bool) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn hide_cursor(&self, _hide: bool) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_position(
|
||||
&self,
|
||||
_position: LogicalPosition<f64>,
|
||||
) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_minimized(&self, _minimized: bool) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_maximized(&self, _maximized: bool) {
|
||||
// N/A
|
||||
// Android has single screen maximized apps so nothing to do
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn fullscreen(&self) -> Option<RootMonitorHandle> {
|
||||
// N/A
|
||||
// Android has single screen maximized apps so nothing to do
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_fullscreen(&self, _monitor: Option<RootMonitorHandle>) {
|
||||
// N/A
|
||||
// Android has single screen maximized apps so nothing to do
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_decorations(&self, _decorations: bool) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_always_on_top(&self, _always_on_top: bool) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_window_icon(&self, _icon: Option<::Icon>) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_ime_position(&self, _spot: LogicalPosition<f64>) {
|
||||
// N/A
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn current_monitor(&self) -> RootMonitorHandle {
|
||||
RootMonitorHandle {
|
||||
inner: MonitorHandle,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
let mut rb = VecDeque::with_capacity(1);
|
||||
rb.push_back(MonitorHandle);
|
||||
rb
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> MonitorHandle {
|
||||
MonitorHandle
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn id(&self) -> WindowId {
|
||||
WindowId
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn raw_window_handle(&self) -> RawWindowHandle {
|
||||
let handle = AndroidHandle {
|
||||
a_native_window: self.native_window,
|
||||
..WindowsHandle::empty()
|
||||
pub fn primary_monitor(&self) -> Option<monitor::MonitorHandle> {
|
||||
Some(monitor::MonitorHandle {
|
||||
inner: MonitorHandle,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
let mut v = VecDeque::with_capacity(1);
|
||||
v.push_back(MonitorHandle);
|
||||
v
|
||||
}
|
||||
|
||||
pub fn current_monitor(&self) -> Option<monitor::MonitorHandle> {
|
||||
Some(monitor::MonitorHandle {
|
||||
inner: MonitorHandle,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
MonitorHandle.scale_factor()
|
||||
}
|
||||
|
||||
pub fn request_redraw(&self) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, error::NotSupportedError> {
|
||||
Err(error::NotSupportedError::new())
|
||||
}
|
||||
|
||||
pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, error::NotSupportedError> {
|
||||
Err(error::NotSupportedError::new())
|
||||
}
|
||||
|
||||
pub fn set_outer_position(&self, _position: Position) {
|
||||
// no effect
|
||||
}
|
||||
|
||||
pub fn inner_size(&self) -> PhysicalSize<u32> {
|
||||
self.outer_size()
|
||||
}
|
||||
|
||||
pub fn set_inner_size(&self, _size: Size) {
|
||||
warn!("Cannot set window size on Android");
|
||||
}
|
||||
|
||||
pub fn outer_size(&self) -> PhysicalSize<u32> {
|
||||
MonitorHandle.size()
|
||||
}
|
||||
|
||||
pub fn set_min_inner_size(&self, _: Option<Size>) {}
|
||||
|
||||
pub fn set_max_inner_size(&self, _: Option<Size>) {}
|
||||
|
||||
pub fn set_title(&self, _title: &str) {}
|
||||
|
||||
pub fn set_visible(&self, _visibility: bool) {}
|
||||
|
||||
pub fn set_resizable(&self, _resizeable: bool) {}
|
||||
|
||||
pub fn set_minimized(&self, _minimized: bool) {}
|
||||
|
||||
pub fn set_maximized(&self, _maximized: bool) {}
|
||||
|
||||
pub fn set_fullscreen(&self, _monitor: Option<window::Fullscreen>) {
|
||||
warn!("Cannot set fullscreen on Android");
|
||||
}
|
||||
|
||||
pub fn fullscreen(&self) -> Option<window::Fullscreen> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn set_decorations(&self, _decorations: bool) {}
|
||||
|
||||
pub fn set_always_on_top(&self, _always_on_top: bool) {}
|
||||
|
||||
pub fn set_window_icon(&self, _window_icon: Option<crate::icon::Icon>) {}
|
||||
|
||||
pub fn set_ime_position(&self, _position: Position) {}
|
||||
|
||||
pub fn set_cursor_icon(&self, _: window::CursorIcon) {}
|
||||
|
||||
pub fn set_cursor_position(&self, _: Position) -> Result<(), error::ExternalError> {
|
||||
Err(error::ExternalError::NotSupported(
|
||||
error::NotSupportedError::new(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn set_cursor_grab(&self, _: bool) -> Result<(), error::ExternalError> {
|
||||
Err(error::ExternalError::NotSupported(
|
||||
error::NotSupportedError::new(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn set_cursor_visible(&self, _: bool) {}
|
||||
|
||||
pub fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle {
|
||||
let a_native_window = if let Some(native_window) = ndk_glue::native_window().as_ref() {
|
||||
unsafe { native_window.ptr().as_mut() as *mut _ as *mut _ }
|
||||
} else {
|
||||
panic!("native window null");
|
||||
};
|
||||
RawWindowHandle::Android(handle)
|
||||
let mut handle = raw_window_handle::android::AndroidHandle::empty();
|
||||
handle.a_native_window = a_native_window;
|
||||
raw_window_handle::RawWindowHandle::Android(handle)
|
||||
}
|
||||
|
||||
pub fn config(&self) -> Configuration {
|
||||
CONFIG.read().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn content_rect(&self) -> Rect {
|
||||
ndk_glue::content_rect()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for Window {}
|
||||
unsafe impl Sync for Window {}
|
||||
#[derive(Default, Clone, Debug)]
|
||||
pub struct OsError;
|
||||
|
||||
// Constant device ID, to be removed when this backend is updated to report real device IDs.
|
||||
const DEVICE_ID: ::DeviceId = ::DeviceId(DeviceId);
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
impl Display for OsError {
|
||||
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
write!(fmt, "Android OS Error")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct MonitorHandle;
|
||||
|
||||
impl MonitorHandle {
|
||||
pub fn name(&self) -> Option<String> {
|
||||
Some("Android Device".to_owned())
|
||||
}
|
||||
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
if let Some(native_window) = ndk_glue::native_window().as_ref() {
|
||||
let width = native_window.width() as _;
|
||||
let height = native_window.height() as _;
|
||||
PhysicalSize::new(width, height)
|
||||
} else {
|
||||
PhysicalSize::new(0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||
(0, 0).into()
|
||||
}
|
||||
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
let config = CONFIG.read().unwrap();
|
||||
config
|
||||
.density()
|
||||
.map(|dpi| dpi as f64 / 160.0)
|
||||
.unwrap_or(1.0)
|
||||
}
|
||||
|
||||
pub fn video_modes(&self) -> impl Iterator<Item = monitor::VideoMode> {
|
||||
let size = self.size().into();
|
||||
let mut v = Vec::new();
|
||||
// FIXME this is not the real refresh rate
|
||||
// (it is guarunteed to support 32 bit color though)
|
||||
v.push(monitor::VideoMode {
|
||||
video_mode: VideoMode {
|
||||
size,
|
||||
bit_depth: 32,
|
||||
refresh_rate: 60,
|
||||
monitor: self.clone(),
|
||||
},
|
||||
});
|
||||
v.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
pub struct VideoMode {
|
||||
size: (u32, u32),
|
||||
bit_depth: u16,
|
||||
refresh_rate: u16,
|
||||
monitor: MonitorHandle,
|
||||
}
|
||||
|
||||
impl VideoMode {
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
self.size.into()
|
||||
}
|
||||
|
||||
pub fn bit_depth(&self) -> u16 {
|
||||
self.bit_depth
|
||||
}
|
||||
|
||||
pub fn refresh_rate(&self) -> u16 {
|
||||
self.refresh_rate
|
||||
}
|
||||
|
||||
pub fn monitor(&self) -> monitor::MonitorHandle {
|
||||
monitor::MonitorHandle {
|
||||
inner: self.monitor.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::{
|
||||
event_loop::{
|
||||
ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootEventLoopWindowTarget,
|
||||
},
|
||||
monitor::MonitorHandle as RootMonitorHandle,
|
||||
platform::ios::Idiom,
|
||||
};
|
||||
|
||||
@@ -24,7 +25,8 @@ use crate::platform_impl::platform::{
|
||||
CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddSource, CFRunLoopGetMain,
|
||||
CFRunLoopObserverCreate, CFRunLoopObserverRef, CFRunLoopSourceContext,
|
||||
CFRunLoopSourceCreate, CFRunLoopSourceInvalidate, CFRunLoopSourceRef,
|
||||
CFRunLoopSourceSignal, CFRunLoopWakeUp, NSString, UIApplicationMain, UIUserInterfaceIdiom,
|
||||
CFRunLoopSourceSignal, CFRunLoopWakeUp, NSStringRust, UIApplicationMain,
|
||||
UIUserInterfaceIdiom,
|
||||
},
|
||||
monitor, view, MonitorHandle,
|
||||
};
|
||||
@@ -49,6 +51,20 @@ pub struct EventLoopWindowTarget<T: 'static> {
|
||||
sender_to_clone: Sender<T>,
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoopWindowTarget<T> {
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
// guaranteed to be on main thread
|
||||
unsafe { monitor::uiscreens() }
|
||||
}
|
||||
|
||||
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
// guaranteed to be on main thread
|
||||
let monitor = unsafe { monitor::main_uiscreen() };
|
||||
|
||||
Some(RootMonitorHandle { inner: monitor })
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoop<T: 'static> {
|
||||
window_target: RootEventLoopWindowTarget<T>,
|
||||
}
|
||||
@@ -105,7 +121,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
0,
|
||||
ptr::null(),
|
||||
nil,
|
||||
NSString::alloc(nil).init_str("AppDelegate"),
|
||||
NSStringRust::alloc(nil).init_str("AppDelegate"),
|
||||
);
|
||||
unreachable!()
|
||||
}
|
||||
@@ -115,16 +131,6 @@ impl<T: 'static> EventLoop<T> {
|
||||
EventLoopProxy::new(self.window_target.p.sender_to_clone.clone())
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
// guaranteed to be on main thread
|
||||
unsafe { monitor::uiscreens() }
|
||||
}
|
||||
|
||||
pub fn primary_monitor(&self) -> MonitorHandle {
|
||||
// guaranteed to be on main thread
|
||||
unsafe { monitor::main_uiscreen() }
|
||||
}
|
||||
|
||||
pub fn window_target(&self) -> &RootEventLoopWindowTarget<T> {
|
||||
&self.window_target
|
||||
}
|
||||
|
||||
@@ -29,14 +29,14 @@ pub struct NSOperatingSystemVersion {
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct CGPoint {
|
||||
pub x: CGFloat,
|
||||
pub y: CGFloat,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct CGSize {
|
||||
pub width: CGFloat,
|
||||
pub height: CGFloat,
|
||||
@@ -52,7 +52,7 @@ impl CGSize {
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct CGRect {
|
||||
pub origin: CGPoint,
|
||||
pub size: CGSize,
|
||||
@@ -359,7 +359,10 @@ pub struct CFRunLoopSourceContext {
|
||||
pub perform: Option<extern "C" fn(*mut c_void)>,
|
||||
}
|
||||
|
||||
pub trait NSString: Sized {
|
||||
// This is named NSStringRust rather than NSString because the "Debug View Heirarchy" feature of
|
||||
// Xcode requires a non-ambiguous reference to NSString for unclear reasons. This makes Xcode happy
|
||||
// so please test if you change the name back to NSString.
|
||||
pub trait NSStringRust: Sized {
|
||||
unsafe fn alloc(_: Self) -> id {
|
||||
msg_send![class!(NSString), alloc]
|
||||
}
|
||||
@@ -370,7 +373,7 @@ pub trait NSString: Sized {
|
||||
unsafe fn UTF8String(self) -> *const c_char;
|
||||
}
|
||||
|
||||
impl NSString for id {
|
||||
impl NSStringRust for id {
|
||||
unsafe fn initWithUTF8String_(self, c_string: *const c_char) -> id {
|
||||
msg_send![self, initWithUTF8String: c_string as id]
|
||||
}
|
||||
|
||||
@@ -83,6 +83,8 @@ pub use self::{
|
||||
window::{PlatformSpecificWindowBuilderAttributes, Window, WindowId},
|
||||
};
|
||||
|
||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId {
|
||||
uiscreen: ffi::id,
|
||||
|
||||
@@ -6,6 +6,7 @@ use objc::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
dpi::PhysicalPosition,
|
||||
event::{DeviceId as RootDeviceId, Event, Force, Touch, TouchPhase, WindowEvent},
|
||||
platform::ios::MonitorHandleExtIOS,
|
||||
platform_impl::platform::{
|
||||
@@ -122,17 +123,26 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
|
||||
|
||||
let window: id = msg_send![object, window];
|
||||
assert!(!window.is_null());
|
||||
let bounds: CGRect = msg_send![window, bounds];
|
||||
let window_bounds: CGRect = msg_send![window, bounds];
|
||||
let screen: id = msg_send![window, screen];
|
||||
let screen_space: id = msg_send![screen, coordinateSpace];
|
||||
let screen_frame: CGRect =
|
||||
msg_send![object, convertRect:bounds toCoordinateSpace:screen_space];
|
||||
let dpi_factor: CGFloat = msg_send![screen, scale];
|
||||
msg_send![object, convertRect:window_bounds toCoordinateSpace:screen_space];
|
||||
let scale_factor: CGFloat = msg_send![screen, scale];
|
||||
let size = crate::dpi::LogicalSize {
|
||||
width: screen_frame.size.width as f64,
|
||||
height: screen_frame.size.height as f64,
|
||||
}
|
||||
.to_physical(dpi_factor.into());
|
||||
.to_physical(scale_factor.into());
|
||||
|
||||
// If the app is started in landscape, the view frame and window bounds can be mismatched.
|
||||
// The view frame will be in portrait and the window bounds in landscape. So apply the
|
||||
// window bounds to the view frame to make it consistent.
|
||||
let view_frame: CGRect = msg_send![object, frame];
|
||||
if view_frame != window_bounds {
|
||||
let () = msg_send![object, setFrame: window_bounds];
|
||||
}
|
||||
|
||||
app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(window.into()),
|
||||
event: WindowEvent::Resized(size),
|
||||
@@ -162,15 +172,15 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
|
||||
// `setContentScaleFactor` may be called with a value of 0, which means "reset the
|
||||
// content scale factor to a device-specific default value", so we can't use the
|
||||
// parameter here. We can query the actual factor using the getter
|
||||
let dpi_factor: CGFloat = msg_send![object, contentScaleFactor];
|
||||
let scale_factor: CGFloat = msg_send![object, contentScaleFactor];
|
||||
assert!(
|
||||
!dpi_factor.is_nan()
|
||||
&& dpi_factor.is_finite()
|
||||
&& dpi_factor.is_sign_positive()
|
||||
&& dpi_factor > 0.0,
|
||||
!scale_factor.is_nan()
|
||||
&& scale_factor.is_finite()
|
||||
&& scale_factor.is_sign_positive()
|
||||
&& scale_factor > 0.0,
|
||||
"invalid scale_factor set on UIView",
|
||||
);
|
||||
let scale_factor: f64 = dpi_factor.into();
|
||||
let scale_factor: f64 = scale_factor.into();
|
||||
let bounds: CGRect = msg_send![object, bounds];
|
||||
let screen: id = msg_send![window, screen];
|
||||
let screen_space: id = msg_send![screen, coordinateSpace];
|
||||
@@ -209,7 +219,7 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
|
||||
if touch == nil {
|
||||
break;
|
||||
}
|
||||
let location: CGPoint = msg_send![touch, locationInView: nil];
|
||||
let logical_location: CGPoint = msg_send![touch, locationInView: nil];
|
||||
let touch_type: UITouchType = msg_send![touch, type];
|
||||
let force = if os_supports_force {
|
||||
let trait_collection: id = msg_send![object, traitCollection];
|
||||
@@ -248,12 +258,19 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
|
||||
_ => panic!("unexpected touch phase: {:?}", phase as i32),
|
||||
};
|
||||
|
||||
let physical_location = {
|
||||
let scale_factor: CGFloat = msg_send![object, contentScaleFactor];
|
||||
PhysicalPosition::from_logical::<(f64, f64), f64>(
|
||||
(logical_location.x as _, logical_location.y as _),
|
||||
scale_factor,
|
||||
)
|
||||
};
|
||||
touch_events.push(EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(window.into()),
|
||||
event: WindowEvent::Touch(Touch {
|
||||
device_id: RootDeviceId(DeviceId { uiscreen }),
|
||||
id: touch_id,
|
||||
location: (location.x as f64, location.y as f64).into(),
|
||||
location: physical_location,
|
||||
force,
|
||||
phase,
|
||||
}),
|
||||
@@ -511,7 +528,15 @@ pub unsafe fn create_window(
|
||||
msg_send![window, setScreen:video_mode.monitor().ui_screen()]
|
||||
}
|
||||
Some(Fullscreen::Borderless(ref monitor)) => {
|
||||
msg_send![window, setScreen:monitor.ui_screen()]
|
||||
let uiscreen: id = match &monitor {
|
||||
Some(monitor) => monitor.ui_screen() as id,
|
||||
None => {
|
||||
let uiscreen: id = msg_send![window, screen];
|
||||
uiscreen
|
||||
}
|
||||
};
|
||||
|
||||
msg_send![window, setScreen: uiscreen]
|
||||
}
|
||||
None => (),
|
||||
}
|
||||
|
||||
@@ -83,8 +83,8 @@ impl Inner {
|
||||
x: safe_area.origin.x as f64,
|
||||
y: safe_area.origin.y as f64,
|
||||
};
|
||||
let dpi_factor = self.scale_factor();
|
||||
Ok(position.to_physical(dpi_factor))
|
||||
let scale_factor = self.scale_factor();
|
||||
Ok(position.to_physical(scale_factor))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,15 +95,15 @@ impl Inner {
|
||||
x: screen_frame.origin.x as f64,
|
||||
y: screen_frame.origin.y as f64,
|
||||
};
|
||||
let dpi_factor = self.scale_factor();
|
||||
Ok(position.to_physical(dpi_factor))
|
||||
let scale_factor = self.scale_factor();
|
||||
Ok(position.to_physical(scale_factor))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_outer_position(&self, physical_position: Position) {
|
||||
unsafe {
|
||||
let dpi_factor = self.scale_factor();
|
||||
let position = physical_position.to_logical::<f64>(dpi_factor);
|
||||
let scale_factor = self.scale_factor();
|
||||
let position = physical_position.to_logical::<f64>(scale_factor);
|
||||
let screen_frame = self.screen_frame();
|
||||
let new_screen_frame = CGRect {
|
||||
origin: CGPoint {
|
||||
@@ -119,30 +119,30 @@ impl Inner {
|
||||
|
||||
pub fn inner_size(&self) -> PhysicalSize<u32> {
|
||||
unsafe {
|
||||
let dpi_factor = self.scale_factor();
|
||||
let scale_factor = self.scale_factor();
|
||||
let safe_area = self.safe_area_screen_space();
|
||||
let size = LogicalSize {
|
||||
width: safe_area.size.width as f64,
|
||||
height: safe_area.size.height as f64,
|
||||
};
|
||||
size.to_physical(dpi_factor)
|
||||
size.to_physical(scale_factor)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn outer_size(&self) -> PhysicalSize<u32> {
|
||||
unsafe {
|
||||
let dpi_factor = self.scale_factor();
|
||||
let scale_factor = self.scale_factor();
|
||||
let screen_frame = self.screen_frame();
|
||||
let size = LogicalSize {
|
||||
width: screen_frame.size.width as f64,
|
||||
height: screen_frame.size.height as f64,
|
||||
};
|
||||
size.to_physical(dpi_factor)
|
||||
size.to_physical(scale_factor)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_inner_size(&self, _size: Size) {
|
||||
unimplemented!("not clear what `Window::set_inner_size` means on iOS");
|
||||
warn!("not clear what `Window::set_inner_size` means on iOS");
|
||||
}
|
||||
|
||||
pub fn set_min_inner_size(&self, _dimensions: Option<Size>) {
|
||||
@@ -196,7 +196,9 @@ impl Inner {
|
||||
let () = msg_send![uiscreen, setCurrentMode: video_mode.video_mode.screen_mode];
|
||||
uiscreen
|
||||
}
|
||||
Some(Fullscreen::Borderless(monitor)) => monitor.ui_screen() as id,
|
||||
Some(Fullscreen::Borderless(monitor)) => monitor
|
||||
.unwrap_or_else(|| self.current_monitor_inner())
|
||||
.ui_screen() as id,
|
||||
None => {
|
||||
warn!("`Window::set_fullscreen(None)` ignored on iOS");
|
||||
return;
|
||||
@@ -224,7 +226,7 @@ impl Inner {
|
||||
|
||||
pub fn fullscreen(&self) -> Option<Fullscreen> {
|
||||
unsafe {
|
||||
let monitor = self.current_monitor();
|
||||
let monitor = self.current_monitor_inner();
|
||||
let uiscreen = monitor.inner.ui_screen();
|
||||
let screen_space_bounds = self.screen_frame();
|
||||
let screen_bounds: CGRect = msg_send![uiscreen, bounds];
|
||||
@@ -235,7 +237,7 @@ impl Inner {
|
||||
&& screen_space_bounds.size.width == screen_bounds.size.width
|
||||
&& screen_space_bounds.size.height == screen_bounds.size.height
|
||||
{
|
||||
Some(Fullscreen::Borderless(monitor))
|
||||
Some(Fullscreen::Borderless(Some(monitor)))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -258,7 +260,8 @@ impl Inner {
|
||||
warn!("`Window::set_ime_position` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn current_monitor(&self) -> RootMonitorHandle {
|
||||
// Allow directly accessing the current monitor internally without unwrapping.
|
||||
fn current_monitor_inner(&self) -> RootMonitorHandle {
|
||||
unsafe {
|
||||
let uiscreen: id = msg_send![self.window, screen];
|
||||
RootMonitorHandle {
|
||||
@@ -267,12 +270,17 @@ impl Inner {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn current_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
Some(self.current_monitor_inner())
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
unsafe { monitor::uiscreens() }
|
||||
}
|
||||
|
||||
pub fn primary_monitor(&self) -> MonitorHandle {
|
||||
unsafe { monitor::main_uiscreen() }
|
||||
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
let monitor = unsafe { monitor::main_uiscreen() };
|
||||
Some(RootMonitorHandle { inner: monitor })
|
||||
}
|
||||
|
||||
pub fn id(&self) -> WindowId {
|
||||
@@ -347,16 +355,18 @@ impl Window {
|
||||
Some(Fullscreen::Exclusive(ref video_mode)) => {
|
||||
video_mode.video_mode.monitor.ui_screen() as id
|
||||
}
|
||||
Some(Fullscreen::Borderless(ref monitor)) => monitor.ui_screen() as id,
|
||||
None => monitor::main_uiscreen().ui_screen(),
|
||||
Some(Fullscreen::Borderless(Some(ref monitor))) => monitor.inner.ui_screen(),
|
||||
Some(Fullscreen::Borderless(None)) | None => {
|
||||
monitor::main_uiscreen().ui_screen() as id
|
||||
}
|
||||
};
|
||||
|
||||
let screen_bounds: CGRect = msg_send![screen, bounds];
|
||||
|
||||
let frame = match window_attributes.inner_size {
|
||||
Some(dim) => {
|
||||
let dpi_factor = msg_send![screen, scale];
|
||||
let size = dim.to_logical::<f64>(dpi_factor);
|
||||
let scale_factor = msg_send![screen, scale];
|
||||
let size = dim.to_logical::<f64>(scale_factor);
|
||||
CGRect {
|
||||
origin: screen_bounds.origin,
|
||||
size: CGSize {
|
||||
@@ -400,8 +410,8 @@ impl Window {
|
||||
|
||||
// Like the Windows and macOS backends, we send a `ScaleFactorChanged` and `Resized`
|
||||
// event on window creation if the DPI factor != 1.0
|
||||
let dpi_factor: CGFloat = msg_send![view, contentScaleFactor];
|
||||
let scale_factor: f64 = dpi_factor.into();
|
||||
let scale_factor: CGFloat = msg_send![view, contentScaleFactor];
|
||||
let scale_factor: f64 = scale_factor.into();
|
||||
if scale_factor != 1.0 {
|
||||
let bounds: CGRect = msg_send![view, bounds];
|
||||
let screen: id = msg_send![window, screen];
|
||||
|
||||
@@ -1,12 +1,27 @@
|
||||
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#![cfg(any(
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
|
||||
use std::{collections::VecDeque, env, ffi::CStr, fmt, mem::MaybeUninit, os::raw::*, sync::Arc};
|
||||
#[cfg(all(not(feature = "x11"), not(feature = "wayland")))]
|
||||
compile_error!("Please select a feature to build for unix: `x11`, `wayland`");
|
||||
|
||||
#[cfg(feature = "wayland")]
|
||||
use std::error::Error;
|
||||
use std::{collections::VecDeque, env, fmt};
|
||||
#[cfg(feature = "x11")]
|
||||
use std::{ffi::CStr, mem::MaybeUninit, os::raw::*, sync::Arc};
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
use parking_lot::Mutex;
|
||||
use raw_window_handle::RawWindowHandle;
|
||||
use smithay_client_toolkit::reexports::client::ConnectError;
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
pub use self::x11::XNotSupported;
|
||||
#[cfg(feature = "x11")]
|
||||
use self::x11::{ffi::XVisualInfo, util::WindowType as XWindowType, XConnection, XError};
|
||||
use crate::{
|
||||
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
|
||||
@@ -18,7 +33,11 @@ use crate::{
|
||||
window::{CursorIcon, Fullscreen, WindowAttributes},
|
||||
};
|
||||
|
||||
pub(crate) use crate::icon::RgbaIcon as PlatformIcon;
|
||||
|
||||
#[cfg(feature = "wayland")]
|
||||
pub mod wayland;
|
||||
#[cfg(feature = "x11")]
|
||||
pub mod x11;
|
||||
|
||||
/// Environment variable specifying which backend should be used on unix platform.
|
||||
@@ -32,175 +51,216 @@ const BACKEND_PREFERENCE_ENV_VAR: &str = "WINIT_UNIX_BACKEND";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PlatformSpecificWindowBuilderAttributes {
|
||||
#[cfg(feature = "x11")]
|
||||
pub visual_infos: Option<XVisualInfo>,
|
||||
#[cfg(feature = "x11")]
|
||||
pub screen_id: Option<i32>,
|
||||
#[cfg(feature = "x11")]
|
||||
pub resize_increments: Option<Size>,
|
||||
#[cfg(feature = "x11")]
|
||||
pub base_size: Option<Size>,
|
||||
#[cfg(feature = "x11")]
|
||||
pub class: Option<(String, String)>,
|
||||
#[cfg(feature = "x11")]
|
||||
pub override_redirect: bool,
|
||||
#[cfg(feature = "x11")]
|
||||
pub x11_window_types: Vec<XWindowType>,
|
||||
#[cfg(feature = "x11")]
|
||||
pub gtk_theme_variant: Option<String>,
|
||||
#[cfg(feature = "wayland")]
|
||||
pub app_id: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for PlatformSpecificWindowBuilderAttributes {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
#[cfg(feature = "x11")]
|
||||
visual_infos: None,
|
||||
#[cfg(feature = "x11")]
|
||||
screen_id: None,
|
||||
#[cfg(feature = "x11")]
|
||||
resize_increments: None,
|
||||
#[cfg(feature = "x11")]
|
||||
base_size: None,
|
||||
#[cfg(feature = "x11")]
|
||||
class: None,
|
||||
#[cfg(feature = "x11")]
|
||||
override_redirect: false,
|
||||
#[cfg(feature = "x11")]
|
||||
x11_window_types: vec![XWindowType::Normal],
|
||||
#[cfg(feature = "x11")]
|
||||
gtk_theme_variant: None,
|
||||
#[cfg(feature = "wayland")]
|
||||
app_id: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
lazy_static! {
|
||||
pub static ref X11_BACKEND: Mutex<Result<Arc<XConnection>, XNotSupported>> =
|
||||
{ Mutex::new(XConnection::new(Some(x_error_callback)).map(Arc::new)) };
|
||||
Mutex::new(XConnection::new(Some(x_error_callback)).map(Arc::new));
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum OsError {
|
||||
#[cfg(feature = "x11")]
|
||||
XError(XError),
|
||||
#[cfg(feature = "x11")]
|
||||
XMisc(&'static str),
|
||||
#[cfg(feature = "wayland")]
|
||||
WaylandMisc(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for OsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
match self {
|
||||
OsError::XError(e) => f.pad(&e.description),
|
||||
OsError::XMisc(e) => f.pad(e),
|
||||
fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
match *self {
|
||||
#[cfg(feature = "x11")]
|
||||
OsError::XError(ref e) => _f.pad(&e.description),
|
||||
#[cfg(feature = "x11")]
|
||||
OsError::XMisc(ref e) => _f.pad(e),
|
||||
#[cfg(feature = "wayland")]
|
||||
OsError::WaylandMisc(ref e) => _f.pad(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Window {
|
||||
#[cfg(feature = "x11")]
|
||||
X(x11::Window),
|
||||
#[cfg(feature = "wayland")]
|
||||
Wayland(wayland::Window),
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum WindowId {
|
||||
#[cfg(feature = "x11")]
|
||||
X(x11::WindowId),
|
||||
#[cfg(feature = "wayland")]
|
||||
Wayland(wayland::WindowId),
|
||||
}
|
||||
|
||||
impl WindowId {
|
||||
pub unsafe fn dummy() -> Self {
|
||||
WindowId::Wayland(wayland::WindowId::dummy())
|
||||
#[cfg(feature = "wayland")]
|
||||
return WindowId::Wayland(wayland::WindowId::dummy());
|
||||
#[cfg(all(not(feature = "wayland"), feature = "x11"))]
|
||||
return WindowId::X(x11::WindowId::dummy());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum DeviceId {
|
||||
#[cfg(feature = "x11")]
|
||||
X(x11::DeviceId),
|
||||
#[cfg(feature = "wayland")]
|
||||
Wayland(wayland::DeviceId),
|
||||
}
|
||||
|
||||
impl DeviceId {
|
||||
pub unsafe fn dummy() -> Self {
|
||||
DeviceId::Wayland(wayland::DeviceId::dummy())
|
||||
#[cfg(feature = "wayland")]
|
||||
return DeviceId::Wayland(wayland::DeviceId::dummy());
|
||||
#[cfg(all(not(feature = "wayland"), feature = "x11"))]
|
||||
return DeviceId::X(x11::DeviceId::dummy());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum MonitorHandle {
|
||||
#[cfg(feature = "x11")]
|
||||
X(x11::MonitorHandle),
|
||||
#[cfg(feature = "wayland")]
|
||||
Wayland(wayland::MonitorHandle),
|
||||
}
|
||||
|
||||
/// `x11_or_wayland!(match expr; Enum(foo) => foo.something())`
|
||||
/// expands to the equivalent of
|
||||
/// ```ignore
|
||||
/// match self {
|
||||
/// Enum::X(foo) => foo.something(),
|
||||
/// Enum::Wayland(foo) => foo.something(),
|
||||
/// }
|
||||
/// ```
|
||||
/// The result can be converted to another enum by adding `; as AnotherEnum`
|
||||
macro_rules! x11_or_wayland {
|
||||
(match $what:expr; $enum:ident ( $($c1:tt)* ) => $x:expr; as $enum2:ident ) => {
|
||||
match $what {
|
||||
#[cfg(feature = "x11")]
|
||||
$enum::X($($c1)*) => $enum2::X($x),
|
||||
#[cfg(feature = "wayland")]
|
||||
$enum::Wayland($($c1)*) => $enum2::Wayland($x),
|
||||
}
|
||||
};
|
||||
(match $what:expr; $enum:ident ( $($c1:tt)* ) => $x:expr) => {
|
||||
match $what {
|
||||
#[cfg(feature = "x11")]
|
||||
$enum::X($($c1)*) => $x,
|
||||
#[cfg(feature = "wayland")]
|
||||
$enum::Wayland($($c1)*) => $x,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl MonitorHandle {
|
||||
#[inline]
|
||||
pub fn name(&self) -> Option<String> {
|
||||
match self {
|
||||
&MonitorHandle::X(ref m) => m.name(),
|
||||
&MonitorHandle::Wayland(ref m) => m.name(),
|
||||
}
|
||||
x11_or_wayland!(match self; MonitorHandle(m) => m.name())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn native_identifier(&self) -> u32 {
|
||||
match self {
|
||||
&MonitorHandle::X(ref m) => m.native_identifier(),
|
||||
&MonitorHandle::Wayland(ref m) => m.native_identifier(),
|
||||
}
|
||||
x11_or_wayland!(match self; MonitorHandle(m) => m.native_identifier())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
match self {
|
||||
&MonitorHandle::X(ref m) => m.size(),
|
||||
&MonitorHandle::Wayland(ref m) => m.size(),
|
||||
}
|
||||
x11_or_wayland!(match self; MonitorHandle(m) => m.size())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||
match self {
|
||||
&MonitorHandle::X(ref m) => m.position(),
|
||||
&MonitorHandle::Wayland(ref m) => m.position(),
|
||||
}
|
||||
x11_or_wayland!(match self; MonitorHandle(m) => m.position())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
match self {
|
||||
&MonitorHandle::X(ref m) => m.scale_factor(),
|
||||
&MonitorHandle::Wayland(ref m) => m.scale_factor() as f64,
|
||||
}
|
||||
x11_or_wayland!(match self; MonitorHandle(m) => m.scale_factor() as f64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn video_modes(&self) -> Box<dyn Iterator<Item = RootVideoMode>> {
|
||||
match self {
|
||||
MonitorHandle::X(m) => Box::new(m.video_modes()),
|
||||
MonitorHandle::Wayland(m) => Box::new(m.video_modes()),
|
||||
}
|
||||
x11_or_wayland!(match self; MonitorHandle(m) => Box::new(m.video_modes()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum VideoMode {
|
||||
#[cfg(feature = "x11")]
|
||||
X(x11::VideoMode),
|
||||
#[cfg(feature = "wayland")]
|
||||
Wayland(wayland::VideoMode),
|
||||
}
|
||||
|
||||
impl VideoMode {
|
||||
#[inline]
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
match self {
|
||||
&VideoMode::X(ref m) => m.size(),
|
||||
&VideoMode::Wayland(ref m) => m.size(),
|
||||
}
|
||||
x11_or_wayland!(match self; VideoMode(m) => m.size())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn bit_depth(&self) -> u16 {
|
||||
match self {
|
||||
&VideoMode::X(ref m) => m.bit_depth(),
|
||||
&VideoMode::Wayland(ref m) => m.bit_depth(),
|
||||
}
|
||||
x11_or_wayland!(match self; VideoMode(m) => m.bit_depth())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn refresh_rate(&self) -> u16 {
|
||||
match self {
|
||||
&VideoMode::X(ref m) => m.refresh_rate(),
|
||||
&VideoMode::Wayland(ref m) => m.refresh_rate(),
|
||||
}
|
||||
x11_or_wayland!(match self; VideoMode(m) => m.refresh_rate())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn monitor(&self) -> RootMonitorHandle {
|
||||
match self {
|
||||
&VideoMode::X(ref m) => m.monitor(),
|
||||
&VideoMode::Wayland(ref m) => m.monitor(),
|
||||
}
|
||||
x11_or_wayland!(match self; VideoMode(m) => m.monitor())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,9 +272,11 @@ impl Window {
|
||||
pl_attribs: PlatformSpecificWindowBuilderAttributes,
|
||||
) -> Result<Self, RootOsError> {
|
||||
match *window_target {
|
||||
#[cfg(feature = "wayland")]
|
||||
EventLoopWindowTarget::Wayland(ref window_target) => {
|
||||
wayland::Window::new(window_target, attribs, pl_attribs).map(Window::Wayland)
|
||||
}
|
||||
#[cfg(feature = "x11")]
|
||||
EventLoopWindowTarget::X(ref window_target) => {
|
||||
x11::Window::new(window_target, attribs, pl_attribs).map(Window::X)
|
||||
}
|
||||
@@ -223,232 +285,174 @@ impl Window {
|
||||
|
||||
#[inline]
|
||||
pub fn id(&self) -> WindowId {
|
||||
match self {
|
||||
&Window::X(ref w) => WindowId::X(w.id()),
|
||||
&Window::Wayland(ref w) => WindowId::Wayland(w.id()),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.id(); as WindowId)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_title(&self, title: &str) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_title(title),
|
||||
&Window::Wayland(ref w) => w.set_title(title),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_title(title));
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_visible(&self, visible: bool) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_visible(visible),
|
||||
&Window::Wayland(ref w) => w.set_visible(visible),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_visible(visible))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
match self {
|
||||
&Window::X(ref w) => w.outer_position(),
|
||||
&Window::Wayland(ref w) => w.outer_position(),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.outer_position())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
match self {
|
||||
&Window::X(ref m) => m.inner_position(),
|
||||
&Window::Wayland(ref m) => m.inner_position(),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.inner_position())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_outer_position(&self, position: Position) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_outer_position(position),
|
||||
&Window::Wayland(ref w) => w.set_outer_position(position),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_outer_position(position))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn inner_size(&self) -> PhysicalSize<u32> {
|
||||
match self {
|
||||
&Window::X(ref w) => w.inner_size(),
|
||||
&Window::Wayland(ref w) => w.inner_size(),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.inner_size())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn outer_size(&self) -> PhysicalSize<u32> {
|
||||
match self {
|
||||
&Window::X(ref w) => w.outer_size(),
|
||||
&Window::Wayland(ref w) => w.outer_size(),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.outer_size())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_inner_size(&self, size: Size) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_inner_size(size),
|
||||
&Window::Wayland(ref w) => w.set_inner_size(size),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_inner_size(size))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_min_inner_size(&self, dimensions: Option<Size>) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_min_inner_size(dimensions),
|
||||
&Window::Wayland(ref w) => w.set_min_inner_size(dimensions),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_min_inner_size(dimensions))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_max_inner_size(&self, dimensions: Option<Size>) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_max_inner_size(dimensions),
|
||||
&Window::Wayland(ref w) => w.set_max_inner_size(dimensions),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_max_inner_size(dimensions))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_resizable(&self, resizable: bool) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_resizable(resizable),
|
||||
&Window::Wayland(ref w) => w.set_resizable(resizable),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_resizable(resizable))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_icon(&self, cursor: CursorIcon) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_cursor_icon(cursor),
|
||||
&Window::Wayland(ref w) => w.set_cursor_icon(cursor),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_cursor_icon(cursor))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_grab(&self, grab: bool) -> Result<(), ExternalError> {
|
||||
match self {
|
||||
&Window::X(ref window) => window.set_cursor_grab(grab),
|
||||
&Window::Wayland(ref window) => window.set_cursor_grab(grab),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(window) => window.set_cursor_grab(grab))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_visible(&self, visible: bool) {
|
||||
match self {
|
||||
&Window::X(ref window) => window.set_cursor_visible(visible),
|
||||
&Window::Wayland(ref window) => window.set_cursor_visible(visible),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(window) => window.set_cursor_visible(visible))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
match self {
|
||||
&Window::X(ref w) => w.scale_factor(),
|
||||
&Window::Wayland(ref w) => w.scale_factor() as f64,
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.scale_factor() as f64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_cursor_position(position),
|
||||
&Window::Wayland(ref w) => w.set_cursor_position(position),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_cursor_position(position))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_maximized(&self, maximized: bool) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_maximized(maximized),
|
||||
&Window::Wayland(ref w) => w.set_maximized(maximized),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_maximized(maximized))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_minimized(&self, minimized: bool) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_minimized(minimized),
|
||||
&Window::Wayland(ref w) => w.set_minimized(minimized),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_minimized(minimized))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn fullscreen(&self) -> Option<Fullscreen> {
|
||||
match self {
|
||||
&Window::X(ref w) => w.fullscreen(),
|
||||
&Window::Wayland(ref w) => w.fullscreen(),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.fullscreen())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_fullscreen(&self, monitor: Option<Fullscreen>) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_fullscreen(monitor),
|
||||
&Window::Wayland(ref w) => w.set_fullscreen(monitor),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_fullscreen(monitor))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_decorations(&self, decorations: bool) {
|
||||
x11_or_wayland!(match self; Window(w) => w.set_decorations(decorations))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_always_on_top(&self, _always_on_top: bool) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_decorations(decorations),
|
||||
&Window::Wayland(ref w) => w.set_decorations(decorations),
|
||||
#[cfg(feature = "x11")]
|
||||
&Window::X(ref w) => w.set_always_on_top(_always_on_top),
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_always_on_top(&self, always_on_top: bool) {
|
||||
pub fn set_window_icon(&self, _window_icon: Option<Icon>) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_always_on_top(always_on_top),
|
||||
&Window::Wayland(_) => (),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_window_icon(&self, window_icon: Option<Icon>) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_window_icon(window_icon),
|
||||
&Window::Wayland(_) => (),
|
||||
#[cfg(feature = "x11")]
|
||||
&Window::X(ref w) => w.set_window_icon(_window_icon),
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_ime_position(&self, position: Position) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.set_ime_position(position),
|
||||
&Window::Wayland(_) => (),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.set_ime_position(position))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn request_redraw(&self) {
|
||||
match self {
|
||||
&Window::X(ref w) => w.request_redraw(),
|
||||
&Window::Wayland(ref w) => w.request_redraw(),
|
||||
}
|
||||
x11_or_wayland!(match self; Window(w) => w.request_redraw())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn current_monitor(&self) -> RootMonitorHandle {
|
||||
pub fn current_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
match self {
|
||||
&Window::X(ref window) => RootMonitorHandle {
|
||||
inner: MonitorHandle::X(window.current_monitor()),
|
||||
},
|
||||
&Window::Wayland(ref window) => RootMonitorHandle {
|
||||
inner: MonitorHandle::Wayland(window.current_monitor()),
|
||||
},
|
||||
#[cfg(feature = "x11")]
|
||||
&Window::X(ref window) => {
|
||||
let current_monitor = MonitorHandle::X(window.current_monitor());
|
||||
Some(RootMonitorHandle {
|
||||
inner: current_monitor,
|
||||
})
|
||||
}
|
||||
#[cfg(feature = "wayland")]
|
||||
&Window::Wayland(ref window) => {
|
||||
let current_monitor = MonitorHandle::Wayland(window.current_monitor()?);
|
||||
Some(RootMonitorHandle {
|
||||
inner: current_monitor,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
match self {
|
||||
#[cfg(feature = "x11")]
|
||||
&Window::X(ref window) => window
|
||||
.available_monitors()
|
||||
.into_iter()
|
||||
.map(MonitorHandle::X)
|
||||
.collect(),
|
||||
#[cfg(feature = "wayland")]
|
||||
&Window::Wayland(ref window) => window
|
||||
.available_monitors()
|
||||
.into_iter()
|
||||
@@ -458,21 +462,31 @@ impl Window {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> MonitorHandle {
|
||||
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
match self {
|
||||
&Window::X(ref window) => MonitorHandle::X(window.primary_monitor()),
|
||||
&Window::Wayland(ref window) => MonitorHandle::Wayland(window.primary_monitor()),
|
||||
#[cfg(feature = "x11")]
|
||||
&Window::X(ref window) => {
|
||||
let primary_monitor = MonitorHandle::X(window.primary_monitor());
|
||||
Some(RootMonitorHandle {
|
||||
inner: primary_monitor,
|
||||
})
|
||||
}
|
||||
#[cfg(feature = "wayland")]
|
||||
&Window::Wayland(ref window) => window.primary_monitor(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn raw_window_handle(&self) -> RawWindowHandle {
|
||||
match self {
|
||||
#[cfg(feature = "x11")]
|
||||
&Window::X(ref window) => RawWindowHandle::Xlib(window.raw_window_handle()),
|
||||
#[cfg(feature = "wayland")]
|
||||
&Window::Wayland(ref window) => RawWindowHandle::Wayland(window.raw_window_handle()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
unsafe extern "C" fn x_error_callback(
|
||||
display: *mut x11::ffi::Display,
|
||||
event: *mut x11::ffi::XErrorEvent,
|
||||
@@ -506,21 +520,22 @@ unsafe extern "C" fn x_error_callback(
|
||||
}
|
||||
|
||||
pub enum EventLoop<T: 'static> {
|
||||
#[cfg(feature = "wayland")]
|
||||
Wayland(wayland::EventLoop<T>),
|
||||
#[cfg(feature = "x11")]
|
||||
X(x11::EventLoop<T>),
|
||||
}
|
||||
|
||||
pub enum EventLoopProxy<T: 'static> {
|
||||
#[cfg(feature = "x11")]
|
||||
X(x11::EventLoopProxy<T>),
|
||||
#[cfg(feature = "wayland")]
|
||||
Wayland(wayland::EventLoopProxy<T>),
|
||||
}
|
||||
|
||||
impl<T: 'static> Clone for EventLoopProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
match self {
|
||||
EventLoopProxy::X(proxy) => EventLoopProxy::X(proxy.clone()),
|
||||
EventLoopProxy::Wayland(proxy) => EventLoopProxy::Wayland(proxy.clone()),
|
||||
}
|
||||
x11_or_wayland!(match self; EventLoopProxy(proxy) => proxy.clone(); as EventLoopProxy)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -536,12 +551,18 @@ impl<T: 'static> EventLoop<T> {
|
||||
match env_var.as_str() {
|
||||
"x11" => {
|
||||
// TODO: propagate
|
||||
#[cfg(feature = "x11")]
|
||||
return EventLoop::new_x11_any_thread()
|
||||
.expect("Failed to initialize X11 backend");
|
||||
#[cfg(not(feature = "x11"))]
|
||||
panic!("x11 feature is not enabled")
|
||||
}
|
||||
"wayland" => {
|
||||
#[cfg(feature = "wayland")]
|
||||
return EventLoop::new_wayland_any_thread()
|
||||
.expect("Failed to initialize Wayland backend");
|
||||
#[cfg(not(feature = "wayland"))]
|
||||
panic!("wayland feature is not enabled");
|
||||
}
|
||||
_ => panic!(
|
||||
"Unknown environment variable value for {}, try one of `x11`,`wayland`",
|
||||
@@ -550,16 +571,23 @@ impl<T: 'static> EventLoop<T> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "wayland")]
|
||||
let wayland_err = match EventLoop::new_wayland_any_thread() {
|
||||
Ok(event_loop) => return event_loop,
|
||||
Err(err) => err,
|
||||
};
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
let x11_err = match EventLoop::new_x11_any_thread() {
|
||||
Ok(event_loop) => return event_loop,
|
||||
Err(err) => err,
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "wayland"))]
|
||||
let wayland_err = "backend disabled";
|
||||
#[cfg(not(feature = "x11"))]
|
||||
let x11_err = "backend disabled";
|
||||
|
||||
let err_string = format!(
|
||||
"Failed to initialize any backend! Wayland status: {:?} X11 status: {:?}",
|
||||
wayland_err, x11_err,
|
||||
@@ -567,41 +595,93 @@ impl<T: 'static> EventLoop<T> {
|
||||
panic!(err_string);
|
||||
}
|
||||
|
||||
pub fn new_wayland() -> Result<EventLoop<T>, ConnectError> {
|
||||
#[cfg(feature = "wayland")]
|
||||
pub fn new_wayland() -> Result<EventLoop<T>, Box<dyn Error>> {
|
||||
assert_is_main_thread("new_wayland_any_thread");
|
||||
|
||||
EventLoop::new_wayland_any_thread()
|
||||
}
|
||||
|
||||
pub fn new_wayland_any_thread() -> Result<EventLoop<T>, ConnectError> {
|
||||
#[cfg(feature = "wayland")]
|
||||
pub fn new_wayland_any_thread() -> Result<EventLoop<T>, Box<dyn Error>> {
|
||||
wayland::EventLoop::new().map(EventLoop::Wayland)
|
||||
}
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
pub fn new_x11() -> Result<EventLoop<T>, XNotSupported> {
|
||||
assert_is_main_thread("new_x11_any_thread");
|
||||
|
||||
EventLoop::new_x11_any_thread()
|
||||
}
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
pub fn new_x11_any_thread() -> Result<EventLoop<T>, XNotSupported> {
|
||||
X11_BACKEND
|
||||
.lock()
|
||||
.as_ref()
|
||||
.map(Arc::clone)
|
||||
.map(x11::EventLoop::new)
|
||||
.map(EventLoop::X)
|
||||
.map_err(|err| err.clone())
|
||||
let xconn = match X11_BACKEND.lock().as_ref() {
|
||||
Ok(xconn) => xconn.clone(),
|
||||
Err(err) => return Err(err.clone()),
|
||||
};
|
||||
|
||||
Ok(EventLoop::X(x11::EventLoop::new(xconn)))
|
||||
}
|
||||
|
||||
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.create_proxy(); as EventLoopProxy)
|
||||
}
|
||||
|
||||
pub fn run_return<F>(&mut self, callback: F)
|
||||
where
|
||||
F: FnMut(crate::event::Event<'_, T>, &RootELW<T>, &mut ControlFlow),
|
||||
{
|
||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.run_return(callback))
|
||||
}
|
||||
|
||||
pub fn run<F>(self, callback: F) -> !
|
||||
where
|
||||
F: 'static + FnMut(crate::event::Event<'_, T>, &RootELW<T>, &mut ControlFlow),
|
||||
{
|
||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.run(callback))
|
||||
}
|
||||
|
||||
pub fn window_target(&self) -> &crate::event_loop::EventLoopWindowTarget<T> {
|
||||
x11_or_wayland!(match self; EventLoop(evl) => evl.window_target())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoopProxy<T> {
|
||||
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||
x11_or_wayland!(match self; EventLoopProxy(proxy) => proxy.send_event(event))
|
||||
}
|
||||
}
|
||||
|
||||
pub enum EventLoopWindowTarget<T> {
|
||||
#[cfg(feature = "wayland")]
|
||||
Wayland(wayland::EventLoopWindowTarget<T>),
|
||||
#[cfg(feature = "x11")]
|
||||
X(x11::EventLoopWindowTarget<T>),
|
||||
}
|
||||
|
||||
impl<T> EventLoopWindowTarget<T> {
|
||||
#[inline]
|
||||
pub fn is_wayland(&self) -> bool {
|
||||
match *self {
|
||||
#[cfg(feature = "wayland")]
|
||||
EventLoopWindowTarget::Wayland(_) => true,
|
||||
#[cfg(feature = "x11")]
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
match *self {
|
||||
EventLoop::Wayland(ref evlp) => evlp
|
||||
#[cfg(feature = "wayland")]
|
||||
EventLoopWindowTarget::Wayland(ref evlp) => evlp
|
||||
.available_monitors()
|
||||
.into_iter()
|
||||
.map(MonitorHandle::Wayland)
|
||||
.collect(),
|
||||
EventLoop::X(ref evlp) => evlp
|
||||
#[cfg(feature = "x11")]
|
||||
EventLoopWindowTarget::X(ref evlp) => evlp
|
||||
.x_connection()
|
||||
.available_monitors()
|
||||
.into_iter()
|
||||
@@ -611,68 +691,17 @@ impl<T: 'static> EventLoop<T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> MonitorHandle {
|
||||
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
match *self {
|
||||
EventLoop::Wayland(ref evlp) => MonitorHandle::Wayland(evlp.primary_monitor()),
|
||||
EventLoop::X(ref evlp) => MonitorHandle::X(evlp.x_connection().primary_monitor()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||
match *self {
|
||||
EventLoop::Wayland(ref evlp) => EventLoopProxy::Wayland(evlp.create_proxy()),
|
||||
EventLoop::X(ref evlp) => EventLoopProxy::X(evlp.create_proxy()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_return<F>(&mut self, callback: F)
|
||||
where
|
||||
F: FnMut(crate::event::Event<'_, T>, &RootELW<T>, &mut ControlFlow),
|
||||
{
|
||||
match *self {
|
||||
EventLoop::Wayland(ref mut evlp) => evlp.run_return(callback),
|
||||
EventLoop::X(ref mut evlp) => evlp.run_return(callback),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run<F>(self, callback: F) -> !
|
||||
where
|
||||
F: 'static + FnMut(crate::event::Event<'_, T>, &RootELW<T>, &mut ControlFlow),
|
||||
{
|
||||
match self {
|
||||
EventLoop::Wayland(evlp) => evlp.run(callback),
|
||||
EventLoop::X(evlp) => evlp.run(callback),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn window_target(&self) -> &crate::event_loop::EventLoopWindowTarget<T> {
|
||||
match *self {
|
||||
EventLoop::Wayland(ref evl) => evl.window_target(),
|
||||
EventLoop::X(ref evl) => evl.window_target(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoopProxy<T> {
|
||||
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||
match *self {
|
||||
EventLoopProxy::Wayland(ref proxy) => proxy.send_event(event),
|
||||
EventLoopProxy::X(ref proxy) => proxy.send_event(event),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum EventLoopWindowTarget<T> {
|
||||
Wayland(wayland::EventLoopWindowTarget<T>),
|
||||
X(x11::EventLoopWindowTarget<T>),
|
||||
}
|
||||
|
||||
impl<T> EventLoopWindowTarget<T> {
|
||||
#[inline]
|
||||
pub fn is_wayland(&self) -> bool {
|
||||
match *self {
|
||||
EventLoopWindowTarget::Wayland(_) => true,
|
||||
EventLoopWindowTarget::X(_) => false,
|
||||
#[cfg(feature = "wayland")]
|
||||
EventLoopWindowTarget::Wayland(ref evlp) => evlp.primary_monitor(),
|
||||
#[cfg(feature = "x11")]
|
||||
EventLoopWindowTarget::X(ref evlp) => {
|
||||
let primary_monitor = MonitorHandle::X(evlp.x_connection().primary_monitor());
|
||||
Some(RootMonitorHandle {
|
||||
inner: primary_monitor,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -724,7 +753,5 @@ fn is_main_thread() -> bool {
|
||||
|
||||
#[cfg(target_os = "netbsd")]
|
||||
fn is_main_thread() -> bool {
|
||||
use libc::_lwp_self;
|
||||
|
||||
unsafe { _lwp_self() == 1 }
|
||||
std::thread::current().name() == Some("main")
|
||||
}
|
||||
|
||||
149
src/platform_impl/linux/wayland/env.rs
Normal file
149
src/platform_impl/linux/wayland/env.rs
Normal file
@@ -0,0 +1,149 @@
|
||||
//! SCTK environment setup.
|
||||
|
||||
use sctk::reexports::client::protocol::wl_compositor::WlCompositor;
|
||||
use sctk::reexports::client::protocol::wl_output::WlOutput;
|
||||
use sctk::reexports::protocols::unstable::xdg_shell::v6::client::zxdg_shell_v6::ZxdgShellV6;
|
||||
use sctk::reexports::client::protocol::wl_seat::WlSeat;
|
||||
use sctk::reexports::protocols::unstable::xdg_decoration::v1::client::zxdg_decoration_manager_v1::ZxdgDecorationManagerV1;
|
||||
use sctk::reexports::client::protocol::wl_shell::WlShell;
|
||||
use sctk::reexports::client::protocol::wl_subcompositor::WlSubcompositor;
|
||||
use sctk::reexports::client::{Attached, DispatchData};
|
||||
use sctk::reexports::client::protocol::wl_shm::WlShm;
|
||||
use sctk::reexports::protocols::xdg_shell::client::xdg_wm_base::XdgWmBase;
|
||||
use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1;
|
||||
use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPointerConstraintsV1;
|
||||
use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3;
|
||||
|
||||
use sctk::environment::{Environment, SimpleGlobal};
|
||||
use sctk::output::{OutputHandler, OutputHandling, OutputInfo, OutputStatusListener};
|
||||
use sctk::seat::{SeatData, SeatHandler, SeatHandling, SeatListener};
|
||||
use sctk::shell::{Shell, ShellHandler, ShellHandling};
|
||||
use sctk::shm::ShmHandler;
|
||||
|
||||
/// Set of extra features that are supported by the compositor.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct WindowingFeatures {
|
||||
cursor_grab: bool,
|
||||
}
|
||||
|
||||
impl WindowingFeatures {
|
||||
/// Create `WindowingFeatures` based on the presented interfaces.
|
||||
pub fn new(env: &Environment<WinitEnv>) -> Self {
|
||||
let cursor_grab = env.get_global::<ZwpPointerConstraintsV1>().is_some();
|
||||
Self { cursor_grab }
|
||||
}
|
||||
|
||||
pub fn cursor_grab(&self) -> bool {
|
||||
self.cursor_grab
|
||||
}
|
||||
}
|
||||
|
||||
sctk::environment!(WinitEnv,
|
||||
singles = [
|
||||
WlShm => shm,
|
||||
WlCompositor => compositor,
|
||||
WlSubcompositor => subcompositor,
|
||||
WlShell => shell,
|
||||
XdgWmBase => shell,
|
||||
ZxdgShellV6 => shell,
|
||||
ZxdgDecorationManagerV1 => decoration_manager,
|
||||
ZwpRelativePointerManagerV1 => relative_pointer_manager,
|
||||
ZwpPointerConstraintsV1 => pointer_constraints,
|
||||
ZwpTextInputManagerV3 => text_input_manager,
|
||||
],
|
||||
multis = [
|
||||
WlSeat => seats,
|
||||
WlOutput => outputs,
|
||||
]
|
||||
);
|
||||
|
||||
/// The environment that we utilize.
|
||||
pub struct WinitEnv {
|
||||
seats: SeatHandler,
|
||||
|
||||
outputs: OutputHandler,
|
||||
|
||||
shm: ShmHandler,
|
||||
|
||||
compositor: SimpleGlobal<WlCompositor>,
|
||||
|
||||
subcompositor: SimpleGlobal<WlSubcompositor>,
|
||||
|
||||
shell: ShellHandler,
|
||||
|
||||
relative_pointer_manager: SimpleGlobal<ZwpRelativePointerManagerV1>,
|
||||
|
||||
pointer_constraints: SimpleGlobal<ZwpPointerConstraintsV1>,
|
||||
|
||||
text_input_manager: SimpleGlobal<ZwpTextInputManagerV3>,
|
||||
|
||||
decoration_manager: SimpleGlobal<ZxdgDecorationManagerV1>,
|
||||
}
|
||||
|
||||
impl WinitEnv {
|
||||
pub fn new() -> Self {
|
||||
// Output tracking for available_monitors, etc.
|
||||
let outputs = OutputHandler::new();
|
||||
|
||||
// Keyboard/Pointer/Touch input.
|
||||
let seats = SeatHandler::new();
|
||||
|
||||
// Essential globals.
|
||||
let shm = ShmHandler::new();
|
||||
let compositor = SimpleGlobal::new();
|
||||
let subcompositor = SimpleGlobal::new();
|
||||
|
||||
// Gracefully handle shell picking, since SCTK automatically supports multiple
|
||||
// backends.
|
||||
let shell = ShellHandler::new();
|
||||
|
||||
// Server side decorations.
|
||||
let decoration_manager = SimpleGlobal::new();
|
||||
|
||||
// Device events for pointer.
|
||||
let relative_pointer_manager = SimpleGlobal::new();
|
||||
|
||||
// Pointer grab functionality.
|
||||
let pointer_constraints = SimpleGlobal::new();
|
||||
|
||||
// IME handling.
|
||||
let text_input_manager = SimpleGlobal::new();
|
||||
|
||||
Self {
|
||||
seats,
|
||||
outputs,
|
||||
shm,
|
||||
compositor,
|
||||
subcompositor,
|
||||
shell,
|
||||
decoration_manager,
|
||||
relative_pointer_manager,
|
||||
pointer_constraints,
|
||||
text_input_manager,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ShellHandling for WinitEnv {
|
||||
fn get_shell(&self) -> Option<Shell> {
|
||||
self.shell.get_shell()
|
||||
}
|
||||
}
|
||||
|
||||
impl SeatHandling for WinitEnv {
|
||||
fn listen<F: FnMut(Attached<WlSeat>, &SeatData, DispatchData<'_>) + 'static>(
|
||||
&mut self,
|
||||
f: F,
|
||||
) -> SeatListener {
|
||||
self.seats.listen(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl OutputHandling for WinitEnv {
|
||||
fn listen<F: FnMut(WlOutput, &OutputInfo, DispatchData<'_>) + 'static>(
|
||||
&mut self,
|
||||
f: F,
|
||||
) -> OutputStatusListener {
|
||||
self.outputs.listen(f)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
535
src/platform_impl/linux/wayland/event_loop/mod.rs
Normal file
535
src/platform_impl/linux/wayland/event_loop/mod.rs
Normal file
@@ -0,0 +1,535 @@
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::process;
|
||||
use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use sctk::reexports::client::protocol::wl_compositor::WlCompositor;
|
||||
use sctk::reexports::client::protocol::wl_shm::WlShm;
|
||||
use sctk::reexports::client::Display;
|
||||
|
||||
use sctk::reexports::calloop;
|
||||
|
||||
use sctk::environment::Environment;
|
||||
use sctk::seat::pointer::{ThemeManager, ThemeSpec};
|
||||
use sctk::WaylandSource;
|
||||
|
||||
use crate::event::{Event, StartCause, WindowEvent};
|
||||
use crate::event_loop::{ControlFlow, EventLoopWindowTarget as RootEventLoopWindowTarget};
|
||||
use crate::platform_impl::platform::sticky_exit_callback;
|
||||
|
||||
use super::env::{WindowingFeatures, WinitEnv};
|
||||
use super::output::OutputManager;
|
||||
use super::seat::SeatManager;
|
||||
use super::window::shim::{self, WindowUpdate};
|
||||
use super::{DeviceId, WindowId};
|
||||
|
||||
mod proxy;
|
||||
mod sink;
|
||||
mod state;
|
||||
|
||||
pub use proxy::EventLoopProxy;
|
||||
pub use state::WinitState;
|
||||
|
||||
use sink::EventSink;
|
||||
|
||||
pub struct EventLoopWindowTarget<T> {
|
||||
/// Wayland display.
|
||||
pub display: Display,
|
||||
|
||||
/// Environment to handle object creation, etc.
|
||||
pub env: Environment<WinitEnv>,
|
||||
|
||||
/// Event loop handle.
|
||||
pub event_loop_handle: calloop::LoopHandle<WinitState>,
|
||||
|
||||
/// Output manager.
|
||||
pub output_manager: OutputManager,
|
||||
|
||||
/// State that we share across callbacks.
|
||||
pub state: RefCell<WinitState>,
|
||||
|
||||
/// Wayland source.
|
||||
pub wayland_source: Rc<calloop::Source<WaylandSource>>,
|
||||
|
||||
/// A proxy to wake up event loop.
|
||||
pub event_loop_awakener: calloop::ping::Ping,
|
||||
|
||||
/// The available windowing features.
|
||||
pub windowing_features: WindowingFeatures,
|
||||
|
||||
/// Theme manager to manage cursors.
|
||||
///
|
||||
/// It's being shared amoung all windows to avoid loading
|
||||
/// multiple similar themes.
|
||||
pub theme_manager: ThemeManager,
|
||||
|
||||
_marker: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
pub struct EventLoop<T: 'static> {
|
||||
/// Event loop.
|
||||
event_loop: calloop::EventLoop<WinitState>,
|
||||
|
||||
/// Wayland display.
|
||||
display: Display,
|
||||
|
||||
/// Pending user events.
|
||||
pending_user_events: Rc<RefCell<Vec<T>>>,
|
||||
|
||||
/// Sender of user events.
|
||||
user_events_sender: calloop::channel::Sender<T>,
|
||||
|
||||
/// Wayland source of events.
|
||||
wayland_source: Rc<calloop::Source<WaylandSource>>,
|
||||
|
||||
/// Window target.
|
||||
window_target: RootEventLoopWindowTarget<T>,
|
||||
|
||||
/// Output manager.
|
||||
_seat_manager: SeatManager,
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoop<T> {
|
||||
pub fn new() -> Result<EventLoop<T>, Box<dyn Error>> {
|
||||
// Connect to wayland server and setup event queue.
|
||||
let display = Display::connect_to_env()?;
|
||||
let mut event_queue = display.create_event_queue();
|
||||
let display_proxy = display.attach(event_queue.token());
|
||||
|
||||
// Setup environment.
|
||||
let env = Environment::new(&display_proxy, &mut event_queue, WinitEnv::new())?;
|
||||
|
||||
// Create event loop.
|
||||
let event_loop = calloop::EventLoop::<WinitState>::new()?;
|
||||
// Build windowing features.
|
||||
let windowing_features = WindowingFeatures::new(&env);
|
||||
|
||||
// Create a theme manager.
|
||||
let compositor = env.require_global::<WlCompositor>();
|
||||
let shm = env.require_global::<WlShm>();
|
||||
let theme_manager = ThemeManager::init(ThemeSpec::System, compositor, shm);
|
||||
|
||||
// Setup theme seat and output managers.
|
||||
let seat_manager = SeatManager::new(&env, event_loop.handle(), theme_manager.clone());
|
||||
let output_manager = OutputManager::new(&env);
|
||||
|
||||
// A source of events that we plug into our event loop.
|
||||
let wayland_source = WaylandSource::new(event_queue).quick_insert(event_loop.handle())?;
|
||||
let wayland_source = Rc::new(wayland_source);
|
||||
|
||||
// A source of user events.
|
||||
let pending_user_events = Rc::new(RefCell::new(Vec::new()));
|
||||
let pending_user_events_clone = pending_user_events.clone();
|
||||
let (user_events_sender, user_events_channel) = calloop::channel::channel();
|
||||
|
||||
// User events channel.
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(user_events_channel, move |event, _, _| {
|
||||
if let calloop::channel::Event::Msg(msg) = event {
|
||||
pending_user_events_clone.borrow_mut().push(msg);
|
||||
}
|
||||
})?;
|
||||
|
||||
// An event's loop awakener to wake up for window events from winit's windows.
|
||||
let (event_loop_awakener, event_loop_awakener_source) = calloop::ping::make_ping()?;
|
||||
|
||||
// Handler of window requests.
|
||||
event_loop.handle().insert_source(
|
||||
event_loop_awakener_source,
|
||||
move |_, _, winit_state| {
|
||||
shim::handle_window_requests(winit_state);
|
||||
},
|
||||
)?;
|
||||
|
||||
let event_loop_handle = event_loop.handle();
|
||||
let window_map = HashMap::new();
|
||||
let event_sink = EventSink::new();
|
||||
let window_updates = HashMap::new();
|
||||
|
||||
// Create event loop window target.
|
||||
let event_loop_window_target = EventLoopWindowTarget {
|
||||
display: display.clone(),
|
||||
env,
|
||||
state: RefCell::new(WinitState {
|
||||
window_map,
|
||||
event_sink,
|
||||
window_updates,
|
||||
}),
|
||||
event_loop_handle,
|
||||
output_manager,
|
||||
event_loop_awakener,
|
||||
wayland_source: wayland_source.clone(),
|
||||
windowing_features,
|
||||
theme_manager,
|
||||
_marker: std::marker::PhantomData,
|
||||
};
|
||||
|
||||
// Create event loop itself.
|
||||
let event_loop = Self {
|
||||
event_loop,
|
||||
display,
|
||||
pending_user_events,
|
||||
wayland_source,
|
||||
_seat_manager: seat_manager,
|
||||
user_events_sender,
|
||||
window_target: RootEventLoopWindowTarget {
|
||||
p: crate::platform_impl::EventLoopWindowTarget::Wayland(event_loop_window_target),
|
||||
_marker: std::marker::PhantomData,
|
||||
},
|
||||
};
|
||||
|
||||
Ok(event_loop)
|
||||
}
|
||||
|
||||
pub fn run<F>(mut self, callback: F) -> !
|
||||
where
|
||||
F: FnMut(Event<'_, T>, &RootEventLoopWindowTarget<T>, &mut ControlFlow) + 'static,
|
||||
{
|
||||
self.run_return(callback);
|
||||
process::exit(0)
|
||||
}
|
||||
|
||||
pub fn run_return<F>(&mut self, mut callback: F)
|
||||
where
|
||||
F: FnMut(Event<'_, T>, &RootEventLoopWindowTarget<T>, &mut ControlFlow),
|
||||
{
|
||||
// Send pending events to the server.
|
||||
let _ = self.display.flush();
|
||||
|
||||
let mut control_flow = ControlFlow::default();
|
||||
|
||||
let pending_user_events = self.pending_user_events.clone();
|
||||
|
||||
callback(
|
||||
Event::NewEvents(StartCause::Init),
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
);
|
||||
|
||||
let mut window_updates: Vec<(WindowId, WindowUpdate)> = Vec::new();
|
||||
let mut event_sink_back_buffer = Vec::new();
|
||||
|
||||
// NOTE We break on errors from dispatches, since if we've got protocol error
|
||||
// libwayland-client/wayland-rs will inform us anyway, but crashing downstream is not
|
||||
// really an option. Instead we inform that the event loop got destroyed. We may
|
||||
// communicate an error that something was terminated, but winit doesn't provide us
|
||||
// with an API to do that via some event.
|
||||
loop {
|
||||
// Handle pending user events. We don't need back buffer, since we can't dispatch
|
||||
// user events indirectly via callback to the user.
|
||||
for user_event in pending_user_events.borrow_mut().drain(..) {
|
||||
sticky_exit_callback(
|
||||
Event::UserEvent(user_event),
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
&mut callback,
|
||||
);
|
||||
}
|
||||
|
||||
// Process 'new' pending updates.
|
||||
self.with_state(|state| {
|
||||
window_updates.clear();
|
||||
window_updates.extend(
|
||||
state
|
||||
.window_updates
|
||||
.iter_mut()
|
||||
.map(|(wid, window_update)| (*wid, window_update.take())),
|
||||
);
|
||||
});
|
||||
|
||||
for (window_id, window_update) in window_updates.iter_mut() {
|
||||
if let Some(scale_factor) = window_update.scale_factor.map(|f| f as f64) {
|
||||
let mut physical_size = self.with_state(|state| {
|
||||
let window_handle = state.window_map.get(&window_id).unwrap();
|
||||
let mut size = window_handle.size.lock().unwrap();
|
||||
|
||||
// Update the new logical size if it was changed.
|
||||
let window_size = window_update.size.unwrap_or(*size);
|
||||
*size = window_size;
|
||||
|
||||
window_size.to_physical(scale_factor)
|
||||
});
|
||||
|
||||
sticky_exit_callback(
|
||||
Event::WindowEvent {
|
||||
window_id: crate::window::WindowId(
|
||||
crate::platform_impl::WindowId::Wayland(*window_id),
|
||||
),
|
||||
event: WindowEvent::ScaleFactorChanged {
|
||||
scale_factor,
|
||||
new_inner_size: &mut physical_size,
|
||||
},
|
||||
},
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
&mut callback,
|
||||
);
|
||||
|
||||
// We don't update size on a window handle since we'll do that later
|
||||
// when handling size update.
|
||||
let new_logical_size = physical_size.to_logical(scale_factor);
|
||||
window_update.size = Some(new_logical_size);
|
||||
}
|
||||
|
||||
if let Some(size) = window_update.size.take() {
|
||||
let physical_size = self.with_state(|state| {
|
||||
let window_handle = state.window_map.get_mut(&window_id).unwrap();
|
||||
let mut window_size = window_handle.size.lock().unwrap();
|
||||
|
||||
// Always issue resize event on scale factor change.
|
||||
let physical_size =
|
||||
if window_update.scale_factor.is_none() && *window_size == size {
|
||||
// The size hasn't changed, don't inform downstream about that.
|
||||
None
|
||||
} else {
|
||||
*window_size = size;
|
||||
let scale_factor =
|
||||
sctk::get_surface_scale_factor(&window_handle.window.surface());
|
||||
let physical_size = size.to_physical(scale_factor as f64);
|
||||
Some(physical_size)
|
||||
};
|
||||
|
||||
// We still perform all of those resize related logic even if the size
|
||||
// hasn't changed, since GNOME relies on `set_geometry` calls after
|
||||
// configures.
|
||||
window_handle.window.resize(size.width, size.height);
|
||||
window_handle.window.refresh();
|
||||
|
||||
// Mark that refresh isn't required, since we've done it right now.
|
||||
window_update.refresh_frame = false;
|
||||
|
||||
physical_size
|
||||
});
|
||||
|
||||
if let Some(physical_size) = physical_size {
|
||||
sticky_exit_callback(
|
||||
Event::WindowEvent {
|
||||
window_id: crate::window::WindowId(
|
||||
crate::platform_impl::WindowId::Wayland(*window_id),
|
||||
),
|
||||
event: WindowEvent::Resized(physical_size),
|
||||
},
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
&mut callback,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if window_update.close_window {
|
||||
sticky_exit_callback(
|
||||
Event::WindowEvent {
|
||||
window_id: crate::window::WindowId(
|
||||
crate::platform_impl::WindowId::Wayland(*window_id),
|
||||
),
|
||||
event: WindowEvent::CloseRequested,
|
||||
},
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
&mut callback,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// The purpose of the back buffer and that swap is to not hold borrow_mut when
|
||||
// we're doing callback to the user, since we can double borrow if the user decides
|
||||
// to create a window in one of those callbacks.
|
||||
self.with_state(|state| {
|
||||
std::mem::swap(
|
||||
&mut event_sink_back_buffer,
|
||||
&mut state.event_sink.window_events,
|
||||
)
|
||||
});
|
||||
|
||||
// Handle pending window events.
|
||||
for event in event_sink_back_buffer.drain(..) {
|
||||
let event = event.map_nonuser_event().unwrap();
|
||||
sticky_exit_callback(event, &self.window_target, &mut control_flow, &mut callback);
|
||||
}
|
||||
|
||||
// Send events cleared.
|
||||
sticky_exit_callback(
|
||||
Event::MainEventsCleared,
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
&mut callback,
|
||||
);
|
||||
|
||||
// Handle RedrawRequested events.
|
||||
for (window_id, window_update) in window_updates.iter() {
|
||||
// Handle refresh of the frame.
|
||||
if window_update.refresh_frame {
|
||||
self.with_state(|state| {
|
||||
let window_handle = state.window_map.get_mut(&window_id).unwrap();
|
||||
window_handle.window.refresh();
|
||||
if !window_update.redraw_requested {
|
||||
window_handle.window.surface().commit();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Handle redraw request.
|
||||
if window_update.redraw_requested {
|
||||
sticky_exit_callback(
|
||||
Event::RedrawRequested(crate::window::WindowId(
|
||||
crate::platform_impl::WindowId::Wayland(*window_id),
|
||||
)),
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
&mut callback,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Send RedrawEventCleared.
|
||||
sticky_exit_callback(
|
||||
Event::RedrawEventsCleared,
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
&mut callback,
|
||||
);
|
||||
|
||||
// Send pending events to the server.
|
||||
let _ = self.display.flush();
|
||||
|
||||
// During the run of the user callback, some other code monitoring and reading the
|
||||
// Wayland socket may have been run (mesa for example does this with vsync), if that
|
||||
// is the case, some events may have been enqueued in our event queue.
|
||||
//
|
||||
// If some messages are there, the event loop needs to behave as if it was instantly
|
||||
// woken up by messages arriving from the Wayland socket, to avoid delaying the
|
||||
// dispatch of these events until we're woken up again.
|
||||
let instant_wakeup = {
|
||||
let handle = self.event_loop.handle();
|
||||
let source = self.wayland_source.clone();
|
||||
let dispatched = handle.with_source(&source, |wayland_source| {
|
||||
let queue = wayland_source.queue();
|
||||
self.with_state(|state| {
|
||||
queue.dispatch_pending(state, |_, _, _| unimplemented!())
|
||||
})
|
||||
});
|
||||
|
||||
if let Ok(dispatched) = dispatched {
|
||||
dispatched > 0
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
match control_flow {
|
||||
ControlFlow::Exit => break,
|
||||
ControlFlow::Poll => {
|
||||
// Non-blocking dispatch.
|
||||
let timeout = Duration::from_millis(0);
|
||||
if self.loop_dispatch(Some(timeout)).is_err() {
|
||||
break;
|
||||
}
|
||||
|
||||
callback(
|
||||
Event::NewEvents(StartCause::Poll),
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
);
|
||||
}
|
||||
ControlFlow::Wait => {
|
||||
let timeout = if instant_wakeup {
|
||||
Some(Duration::from_millis(0))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if self.loop_dispatch(timeout).is_err() {
|
||||
break;
|
||||
}
|
||||
|
||||
callback(
|
||||
Event::NewEvents(StartCause::WaitCancelled {
|
||||
start: Instant::now(),
|
||||
requested_resume: None,
|
||||
}),
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
);
|
||||
}
|
||||
ControlFlow::WaitUntil(deadline) => {
|
||||
let start = Instant::now();
|
||||
|
||||
// Compute the amount of time we'll block for.
|
||||
let duration = if deadline > start && !instant_wakeup {
|
||||
deadline - start
|
||||
} else {
|
||||
Duration::from_millis(0)
|
||||
};
|
||||
|
||||
if self.loop_dispatch(Some(duration)).is_err() {
|
||||
break;
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
|
||||
if now < deadline {
|
||||
callback(
|
||||
Event::NewEvents(StartCause::WaitCancelled {
|
||||
start,
|
||||
requested_resume: Some(deadline),
|
||||
}),
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
)
|
||||
} else {
|
||||
callback(
|
||||
Event::NewEvents(StartCause::ResumeTimeReached {
|
||||
start,
|
||||
requested_resume: deadline,
|
||||
}),
|
||||
&self.window_target,
|
||||
&mut control_flow,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callback(Event::LoopDestroyed, &self.window_target, &mut control_flow);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||
EventLoopProxy::new(self.user_events_sender.clone())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn window_target(&self) -> &RootEventLoopWindowTarget<T> {
|
||||
&self.window_target
|
||||
}
|
||||
|
||||
fn with_state<U, F: FnOnce(&mut WinitState) -> U>(&mut self, f: F) -> U {
|
||||
let state = match &mut self.window_target.p {
|
||||
crate::platform_impl::EventLoopWindowTarget::Wayland(ref mut window_target) => {
|
||||
window_target.state.get_mut()
|
||||
}
|
||||
#[cfg(feature = "x11")]
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
f(state)
|
||||
}
|
||||
|
||||
fn loop_dispatch<D: Into<Option<std::time::Duration>>>(
|
||||
&mut self,
|
||||
timeout: D,
|
||||
) -> std::io::Result<()> {
|
||||
let mut state = match &mut self.window_target.p {
|
||||
crate::platform_impl::EventLoopWindowTarget::Wayland(ref mut window_target) => {
|
||||
window_target.state.get_mut()
|
||||
}
|
||||
#[cfg(feature = "x11")]
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
self.event_loop.dispatch(timeout, &mut state)
|
||||
}
|
||||
}
|
||||
32
src/platform_impl/linux/wayland/event_loop/proxy.rs
Normal file
32
src/platform_impl/linux/wayland/event_loop/proxy.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
//! An event loop proxy.
|
||||
|
||||
use std::sync::mpsc::SendError;
|
||||
|
||||
use sctk::reexports::calloop::channel::Sender;
|
||||
|
||||
use crate::event_loop::EventLoopClosed;
|
||||
|
||||
/// A handle that can be sent across the threads and used to wake up the `EventLoop`.
|
||||
pub struct EventLoopProxy<T: 'static> {
|
||||
user_events_sender: Sender<T>,
|
||||
}
|
||||
|
||||
impl<T: 'static> Clone for EventLoopProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
EventLoopProxy {
|
||||
user_events_sender: self.user_events_sender.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoopProxy<T> {
|
||||
pub fn new(user_events_sender: Sender<T>) -> Self {
|
||||
Self { user_events_sender }
|
||||
}
|
||||
|
||||
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||
self.user_events_sender
|
||||
.send(event)
|
||||
.map_err(|SendError(error)| EventLoopClosed(error))
|
||||
}
|
||||
}
|
||||
36
src/platform_impl/linux/wayland/event_loop/sink.rs
Normal file
36
src/platform_impl/linux/wayland/event_loop/sink.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
//! An event loop's sink to deliver events from the Wayland event callbacks.
|
||||
|
||||
use crate::event::{DeviceEvent, DeviceId as RootDeviceId, Event, WindowEvent};
|
||||
use crate::platform_impl::platform::{DeviceId as PlatformDeviceId, WindowId as PlatformWindowId};
|
||||
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.
|
||||
#[derive(Default)]
|
||||
pub struct EventSink {
|
||||
pub window_events: Vec<Event<'static, ()>>,
|
||||
}
|
||||
|
||||
impl EventSink {
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Add new device event to a queue.
|
||||
pub fn push_device_event(&mut self, event: DeviceEvent, device_id: DeviceId) {
|
||||
self.window_events.push(Event::DeviceEvent {
|
||||
event,
|
||||
device_id: RootDeviceId(PlatformDeviceId::Wayland(device_id)),
|
||||
});
|
||||
}
|
||||
|
||||
/// Add new window event to a queue.
|
||||
pub fn push_window_event(&mut self, event: WindowEvent<'static>, window_id: WindowId) {
|
||||
self.window_events.push(Event::WindowEvent {
|
||||
event,
|
||||
window_id: RootWindowId(PlatformWindowId::Wayland(window_id)),
|
||||
});
|
||||
}
|
||||
}
|
||||
25
src/platform_impl/linux/wayland/event_loop/state.rs
Normal file
25
src/platform_impl/linux/wayland/event_loop/state.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
//! A state that we pass around in a dispatch.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::EventSink;
|
||||
use crate::platform_impl::wayland::window::shim::{WindowHandle, WindowUpdate};
|
||||
use crate::platform_impl::wayland::WindowId;
|
||||
|
||||
/// Wrapper to carry winit's state.
|
||||
pub struct WinitState {
|
||||
/// A sink for window and device events that is being filled during dispatching
|
||||
/// event loop and forwarded downstream afterwards.
|
||||
pub event_sink: EventSink,
|
||||
|
||||
/// Window updates, which are coming from SCTK or the compositor, which require
|
||||
/// calling back to the winit's downstream. They are handled right in the event loop,
|
||||
/// unlike the ones coming from buffers on the `WindowHandle`'s.
|
||||
pub window_updates: HashMap<WindowId, WindowUpdate>,
|
||||
|
||||
/// Window map containing all SCTK windows. Since those windows aren't allowed
|
||||
/// to be sent to other threads, they live on the event loop's thread
|
||||
/// and requests from winit's windows are being forwarded to them either via
|
||||
/// `WindowUpdate` or buffer on the associated with it `WindowHandle`.
|
||||
pub window_map: HashMap<WindowId, WindowHandle>,
|
||||
}
|
||||
@@ -1,382 +0,0 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use super::{event_loop::EventsSink, make_wid, DeviceId};
|
||||
use smithay_client_toolkit::{
|
||||
keyboard::{
|
||||
self, map_keyboard_auto_with_repeat, Event as KbEvent, KeyRepeatEvent, KeyRepeatKind,
|
||||
},
|
||||
reexports::client::protocol::{wl_keyboard, wl_seat},
|
||||
};
|
||||
|
||||
use crate::event::{
|
||||
DeviceEvent, ElementState, KeyboardInput, ModifiersState, VirtualKeyCode, WindowEvent,
|
||||
};
|
||||
|
||||
pub fn init_keyboard(
|
||||
seat: &wl_seat::WlSeat,
|
||||
sink: EventsSink,
|
||||
modifiers_tracker: Arc<Mutex<ModifiersState>>,
|
||||
) -> wl_keyboard::WlKeyboard {
|
||||
// { variables to be captured by the closures
|
||||
let target = Arc::new(Mutex::new(None));
|
||||
let my_sink = sink.clone();
|
||||
let repeat_sink = sink.clone();
|
||||
let repeat_target = target.clone();
|
||||
let my_modifiers = modifiers_tracker.clone();
|
||||
// }
|
||||
let ret = map_keyboard_auto_with_repeat(
|
||||
seat,
|
||||
KeyRepeatKind::System,
|
||||
move |evt: KbEvent<'_>, _| {
|
||||
match evt {
|
||||
KbEvent::Enter { surface, .. } => {
|
||||
let wid = make_wid(&surface);
|
||||
my_sink.send_window_event(WindowEvent::Focused(true), wid);
|
||||
*target.lock().unwrap() = Some(wid);
|
||||
}
|
||||
KbEvent::Leave { surface, .. } => {
|
||||
let wid = make_wid(&surface);
|
||||
my_sink.send_window_event(WindowEvent::Focused(false), wid);
|
||||
*target.lock().unwrap() = None;
|
||||
}
|
||||
KbEvent::Key {
|
||||
rawkey,
|
||||
keysym,
|
||||
state,
|
||||
utf8,
|
||||
..
|
||||
} => {
|
||||
if let Some(wid) = *target.lock().unwrap() {
|
||||
let state = match state {
|
||||
wl_keyboard::KeyState::Pressed => ElementState::Pressed,
|
||||
wl_keyboard::KeyState::Released => ElementState::Released,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let vkcode = key_to_vkey(rawkey, keysym);
|
||||
my_sink.send_window_event(
|
||||
#[allow(deprecated)]
|
||||
WindowEvent::KeyboardInput {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
input: KeyboardInput {
|
||||
state,
|
||||
scancode: rawkey,
|
||||
virtual_keycode: vkcode,
|
||||
modifiers: modifiers_tracker.lock().unwrap().clone(),
|
||||
},
|
||||
is_synthetic: false,
|
||||
},
|
||||
wid,
|
||||
);
|
||||
// send char event only on key press, not release
|
||||
if let ElementState::Released = state {
|
||||
return;
|
||||
}
|
||||
if let Some(txt) = utf8 {
|
||||
for chr in txt.chars() {
|
||||
my_sink.send_window_event(WindowEvent::ReceivedCharacter(chr), wid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
KbEvent::RepeatInfo { .. } => { /* Handled by smithay client toolkit */ }
|
||||
KbEvent::Modifiers {
|
||||
modifiers: event_modifiers,
|
||||
} => {
|
||||
let modifiers = ModifiersState::from_wayland(event_modifiers);
|
||||
|
||||
*modifiers_tracker.lock().unwrap() = modifiers;
|
||||
|
||||
my_sink.send_device_event(DeviceEvent::ModifiersChanged(modifiers), DeviceId);
|
||||
}
|
||||
}
|
||||
},
|
||||
move |repeat_event: KeyRepeatEvent, _| {
|
||||
if let Some(wid) = *repeat_target.lock().unwrap() {
|
||||
let state = ElementState::Pressed;
|
||||
let vkcode = key_to_vkey(repeat_event.rawkey, repeat_event.keysym);
|
||||
repeat_sink.send_window_event(
|
||||
#[allow(deprecated)]
|
||||
WindowEvent::KeyboardInput {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
input: KeyboardInput {
|
||||
state,
|
||||
scancode: repeat_event.rawkey,
|
||||
virtual_keycode: vkcode,
|
||||
modifiers: my_modifiers.lock().unwrap().clone(),
|
||||
},
|
||||
is_synthetic: false,
|
||||
},
|
||||
wid,
|
||||
);
|
||||
if let Some(txt) = repeat_event.utf8 {
|
||||
for chr in txt.chars() {
|
||||
repeat_sink.send_window_event(WindowEvent::ReceivedCharacter(chr), wid);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
match ret {
|
||||
Ok(keyboard) => keyboard,
|
||||
Err(_) => {
|
||||
// This is a fallback impl if libxkbcommon was not available
|
||||
// This case should probably never happen, as most wayland
|
||||
// compositors _need_ libxkbcommon anyway...
|
||||
//
|
||||
// In this case, we don't have the keymap information (it is
|
||||
// supposed to be serialized by the compositor using libxkbcommon)
|
||||
|
||||
seat.get_keyboard(|keyboard| {
|
||||
// { variables to be captured by the closure
|
||||
let mut target = None;
|
||||
let my_sink = sink;
|
||||
// }
|
||||
|
||||
keyboard.implement_closure(
|
||||
move |evt, _| match evt {
|
||||
wl_keyboard::Event::Enter { surface, .. } => {
|
||||
let wid = make_wid(&surface);
|
||||
my_sink.send_window_event(WindowEvent::Focused(true), wid);
|
||||
target = Some(wid);
|
||||
}
|
||||
wl_keyboard::Event::Leave { surface, .. } => {
|
||||
let wid = make_wid(&surface);
|
||||
my_sink.send_window_event(WindowEvent::Focused(false), wid);
|
||||
target = None;
|
||||
}
|
||||
wl_keyboard::Event::Key { key, state, .. } => {
|
||||
if let Some(wid) = target {
|
||||
let state = match state {
|
||||
wl_keyboard::KeyState::Pressed => ElementState::Pressed,
|
||||
wl_keyboard::KeyState::Released => ElementState::Released,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
my_sink.send_window_event(
|
||||
#[allow(deprecated)]
|
||||
WindowEvent::KeyboardInput {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
input: KeyboardInput {
|
||||
state,
|
||||
scancode: key,
|
||||
virtual_keycode: None,
|
||||
modifiers: ModifiersState::default(),
|
||||
},
|
||||
is_synthetic: false,
|
||||
},
|
||||
wid,
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
(),
|
||||
)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn key_to_vkey(rawkey: u32, keysym: u32) -> Option<VirtualKeyCode> {
|
||||
match rawkey {
|
||||
1 => Some(VirtualKeyCode::Escape),
|
||||
2 => Some(VirtualKeyCode::Key1),
|
||||
3 => Some(VirtualKeyCode::Key2),
|
||||
4 => Some(VirtualKeyCode::Key3),
|
||||
5 => Some(VirtualKeyCode::Key4),
|
||||
6 => Some(VirtualKeyCode::Key5),
|
||||
7 => Some(VirtualKeyCode::Key6),
|
||||
8 => Some(VirtualKeyCode::Key7),
|
||||
9 => Some(VirtualKeyCode::Key8),
|
||||
10 => Some(VirtualKeyCode::Key9),
|
||||
11 => Some(VirtualKeyCode::Key0),
|
||||
_ => keysym_to_vkey(keysym),
|
||||
}
|
||||
}
|
||||
|
||||
fn keysym_to_vkey(keysym: u32) -> Option<VirtualKeyCode> {
|
||||
use smithay_client_toolkit::keyboard::keysyms;
|
||||
match keysym {
|
||||
// letters
|
||||
keysyms::XKB_KEY_A | keysyms::XKB_KEY_a => Some(VirtualKeyCode::A),
|
||||
keysyms::XKB_KEY_B | keysyms::XKB_KEY_b => Some(VirtualKeyCode::B),
|
||||
keysyms::XKB_KEY_C | keysyms::XKB_KEY_c => Some(VirtualKeyCode::C),
|
||||
keysyms::XKB_KEY_D | keysyms::XKB_KEY_d => Some(VirtualKeyCode::D),
|
||||
keysyms::XKB_KEY_E | keysyms::XKB_KEY_e => Some(VirtualKeyCode::E),
|
||||
keysyms::XKB_KEY_F | keysyms::XKB_KEY_f => Some(VirtualKeyCode::F),
|
||||
keysyms::XKB_KEY_G | keysyms::XKB_KEY_g => Some(VirtualKeyCode::G),
|
||||
keysyms::XKB_KEY_H | keysyms::XKB_KEY_h => Some(VirtualKeyCode::H),
|
||||
keysyms::XKB_KEY_I | keysyms::XKB_KEY_i => Some(VirtualKeyCode::I),
|
||||
keysyms::XKB_KEY_J | keysyms::XKB_KEY_j => Some(VirtualKeyCode::J),
|
||||
keysyms::XKB_KEY_K | keysyms::XKB_KEY_k => Some(VirtualKeyCode::K),
|
||||
keysyms::XKB_KEY_L | keysyms::XKB_KEY_l => Some(VirtualKeyCode::L),
|
||||
keysyms::XKB_KEY_M | keysyms::XKB_KEY_m => Some(VirtualKeyCode::M),
|
||||
keysyms::XKB_KEY_N | keysyms::XKB_KEY_n => Some(VirtualKeyCode::N),
|
||||
keysyms::XKB_KEY_O | keysyms::XKB_KEY_o => Some(VirtualKeyCode::O),
|
||||
keysyms::XKB_KEY_P | keysyms::XKB_KEY_p => Some(VirtualKeyCode::P),
|
||||
keysyms::XKB_KEY_Q | keysyms::XKB_KEY_q => Some(VirtualKeyCode::Q),
|
||||
keysyms::XKB_KEY_R | keysyms::XKB_KEY_r => Some(VirtualKeyCode::R),
|
||||
keysyms::XKB_KEY_S | keysyms::XKB_KEY_s => Some(VirtualKeyCode::S),
|
||||
keysyms::XKB_KEY_T | keysyms::XKB_KEY_t => Some(VirtualKeyCode::T),
|
||||
keysyms::XKB_KEY_U | keysyms::XKB_KEY_u => Some(VirtualKeyCode::U),
|
||||
keysyms::XKB_KEY_V | keysyms::XKB_KEY_v => Some(VirtualKeyCode::V),
|
||||
keysyms::XKB_KEY_W | keysyms::XKB_KEY_w => Some(VirtualKeyCode::W),
|
||||
keysyms::XKB_KEY_X | keysyms::XKB_KEY_x => Some(VirtualKeyCode::X),
|
||||
keysyms::XKB_KEY_Y | keysyms::XKB_KEY_y => Some(VirtualKeyCode::Y),
|
||||
keysyms::XKB_KEY_Z | keysyms::XKB_KEY_z => Some(VirtualKeyCode::Z),
|
||||
// F--
|
||||
keysyms::XKB_KEY_F1 => Some(VirtualKeyCode::F1),
|
||||
keysyms::XKB_KEY_F2 => Some(VirtualKeyCode::F2),
|
||||
keysyms::XKB_KEY_F3 => Some(VirtualKeyCode::F3),
|
||||
keysyms::XKB_KEY_F4 => Some(VirtualKeyCode::F4),
|
||||
keysyms::XKB_KEY_F5 => Some(VirtualKeyCode::F5),
|
||||
keysyms::XKB_KEY_F6 => Some(VirtualKeyCode::F6),
|
||||
keysyms::XKB_KEY_F7 => Some(VirtualKeyCode::F7),
|
||||
keysyms::XKB_KEY_F8 => Some(VirtualKeyCode::F8),
|
||||
keysyms::XKB_KEY_F9 => Some(VirtualKeyCode::F9),
|
||||
keysyms::XKB_KEY_F10 => Some(VirtualKeyCode::F10),
|
||||
keysyms::XKB_KEY_F11 => Some(VirtualKeyCode::F11),
|
||||
keysyms::XKB_KEY_F12 => Some(VirtualKeyCode::F12),
|
||||
keysyms::XKB_KEY_F13 => Some(VirtualKeyCode::F13),
|
||||
keysyms::XKB_KEY_F14 => Some(VirtualKeyCode::F14),
|
||||
keysyms::XKB_KEY_F15 => Some(VirtualKeyCode::F15),
|
||||
keysyms::XKB_KEY_F16 => Some(VirtualKeyCode::F16),
|
||||
keysyms::XKB_KEY_F17 => Some(VirtualKeyCode::F17),
|
||||
keysyms::XKB_KEY_F18 => Some(VirtualKeyCode::F18),
|
||||
keysyms::XKB_KEY_F19 => Some(VirtualKeyCode::F19),
|
||||
keysyms::XKB_KEY_F20 => Some(VirtualKeyCode::F20),
|
||||
keysyms::XKB_KEY_F21 => Some(VirtualKeyCode::F21),
|
||||
keysyms::XKB_KEY_F22 => Some(VirtualKeyCode::F22),
|
||||
keysyms::XKB_KEY_F23 => Some(VirtualKeyCode::F23),
|
||||
keysyms::XKB_KEY_F24 => Some(VirtualKeyCode::F24),
|
||||
// flow control
|
||||
keysyms::XKB_KEY_Print => Some(VirtualKeyCode::Snapshot),
|
||||
keysyms::XKB_KEY_Scroll_Lock => Some(VirtualKeyCode::Scroll),
|
||||
keysyms::XKB_KEY_Pause => Some(VirtualKeyCode::Pause),
|
||||
keysyms::XKB_KEY_Insert => Some(VirtualKeyCode::Insert),
|
||||
keysyms::XKB_KEY_Home => Some(VirtualKeyCode::Home),
|
||||
keysyms::XKB_KEY_Delete => Some(VirtualKeyCode::Delete),
|
||||
keysyms::XKB_KEY_End => Some(VirtualKeyCode::End),
|
||||
keysyms::XKB_KEY_Page_Down => Some(VirtualKeyCode::PageDown),
|
||||
keysyms::XKB_KEY_Page_Up => Some(VirtualKeyCode::PageUp),
|
||||
// arrows
|
||||
keysyms::XKB_KEY_Left => Some(VirtualKeyCode::Left),
|
||||
keysyms::XKB_KEY_Up => Some(VirtualKeyCode::Up),
|
||||
keysyms::XKB_KEY_Right => Some(VirtualKeyCode::Right),
|
||||
keysyms::XKB_KEY_Down => Some(VirtualKeyCode::Down),
|
||||
//
|
||||
keysyms::XKB_KEY_BackSpace => Some(VirtualKeyCode::Back),
|
||||
keysyms::XKB_KEY_Return => Some(VirtualKeyCode::Return),
|
||||
keysyms::XKB_KEY_space => Some(VirtualKeyCode::Space),
|
||||
// keypad
|
||||
keysyms::XKB_KEY_Num_Lock => Some(VirtualKeyCode::Numlock),
|
||||
keysyms::XKB_KEY_KP_0 => Some(VirtualKeyCode::Numpad0),
|
||||
keysyms::XKB_KEY_KP_1 => Some(VirtualKeyCode::Numpad1),
|
||||
keysyms::XKB_KEY_KP_2 => Some(VirtualKeyCode::Numpad2),
|
||||
keysyms::XKB_KEY_KP_3 => Some(VirtualKeyCode::Numpad3),
|
||||
keysyms::XKB_KEY_KP_4 => Some(VirtualKeyCode::Numpad4),
|
||||
keysyms::XKB_KEY_KP_5 => Some(VirtualKeyCode::Numpad5),
|
||||
keysyms::XKB_KEY_KP_6 => Some(VirtualKeyCode::Numpad6),
|
||||
keysyms::XKB_KEY_KP_7 => Some(VirtualKeyCode::Numpad7),
|
||||
keysyms::XKB_KEY_KP_8 => Some(VirtualKeyCode::Numpad8),
|
||||
keysyms::XKB_KEY_KP_9 => Some(VirtualKeyCode::Numpad9),
|
||||
// misc
|
||||
// => Some(VirtualKeyCode::AbntC1),
|
||||
// => Some(VirtualKeyCode::AbntC2),
|
||||
keysyms::XKB_KEY_plus => Some(VirtualKeyCode::Add),
|
||||
keysyms::XKB_KEY_apostrophe => Some(VirtualKeyCode::Apostrophe),
|
||||
// => Some(VirtualKeyCode::Apps),
|
||||
// => Some(VirtualKeyCode::At),
|
||||
// => Some(VirtualKeyCode::Ax),
|
||||
keysyms::XKB_KEY_backslash => Some(VirtualKeyCode::Backslash),
|
||||
// => Some(VirtualKeyCode::Calculator),
|
||||
// => Some(VirtualKeyCode::Capital),
|
||||
keysyms::XKB_KEY_colon => Some(VirtualKeyCode::Colon),
|
||||
keysyms::XKB_KEY_comma => Some(VirtualKeyCode::Comma),
|
||||
// => Some(VirtualKeyCode::Convert),
|
||||
// => Some(VirtualKeyCode::Decimal),
|
||||
// => Some(VirtualKeyCode::Divide),
|
||||
keysyms::XKB_KEY_equal => Some(VirtualKeyCode::Equals),
|
||||
// => Some(VirtualKeyCode::Grave),
|
||||
// => Some(VirtualKeyCode::Kana),
|
||||
// => Some(VirtualKeyCode::Kanji),
|
||||
keysyms::XKB_KEY_Alt_L => Some(VirtualKeyCode::LAlt),
|
||||
// => Some(VirtualKeyCode::LBracket),
|
||||
keysyms::XKB_KEY_Control_L => Some(VirtualKeyCode::LControl),
|
||||
keysyms::XKB_KEY_Shift_L => Some(VirtualKeyCode::LShift),
|
||||
// => Some(VirtualKeyCode::LWin),
|
||||
// => Some(VirtualKeyCode::Mail),
|
||||
// => Some(VirtualKeyCode::MediaSelect),
|
||||
// => Some(VirtualKeyCode::MediaStop),
|
||||
keysyms::XKB_KEY_minus => Some(VirtualKeyCode::Minus),
|
||||
keysyms::XKB_KEY_asterisk => Some(VirtualKeyCode::Multiply),
|
||||
// => Some(VirtualKeyCode::Mute),
|
||||
// => Some(VirtualKeyCode::MyComputer),
|
||||
// => Some(VirtualKeyCode::NextTrack),
|
||||
// => Some(VirtualKeyCode::NoConvert),
|
||||
keysyms::XKB_KEY_KP_Separator => Some(VirtualKeyCode::NumpadComma),
|
||||
keysyms::XKB_KEY_KP_Enter => Some(VirtualKeyCode::NumpadEnter),
|
||||
keysyms::XKB_KEY_KP_Equal => Some(VirtualKeyCode::NumpadEquals),
|
||||
keysyms::XKB_KEY_KP_Add => Some(VirtualKeyCode::Add),
|
||||
keysyms::XKB_KEY_KP_Subtract => Some(VirtualKeyCode::Subtract),
|
||||
keysyms::XKB_KEY_KP_Divide => Some(VirtualKeyCode::Divide),
|
||||
keysyms::XKB_KEY_KP_Page_Up => Some(VirtualKeyCode::PageUp),
|
||||
keysyms::XKB_KEY_KP_Page_Down => Some(VirtualKeyCode::PageDown),
|
||||
keysyms::XKB_KEY_KP_Home => Some(VirtualKeyCode::Home),
|
||||
keysyms::XKB_KEY_KP_End => Some(VirtualKeyCode::End),
|
||||
// => Some(VirtualKeyCode::OEM102),
|
||||
// => Some(VirtualKeyCode::Period),
|
||||
// => Some(VirtualKeyCode::Playpause),
|
||||
// => Some(VirtualKeyCode::Power),
|
||||
// => Some(VirtualKeyCode::Prevtrack),
|
||||
keysyms::XKB_KEY_Alt_R => Some(VirtualKeyCode::RAlt),
|
||||
// => Some(VirtualKeyCode::RBracket),
|
||||
keysyms::XKB_KEY_Control_R => Some(VirtualKeyCode::RControl),
|
||||
keysyms::XKB_KEY_Shift_R => Some(VirtualKeyCode::RShift),
|
||||
// => Some(VirtualKeyCode::RWin),
|
||||
keysyms::XKB_KEY_semicolon => Some(VirtualKeyCode::Semicolon),
|
||||
keysyms::XKB_KEY_slash => Some(VirtualKeyCode::Slash),
|
||||
// => Some(VirtualKeyCode::Sleep),
|
||||
// => Some(VirtualKeyCode::Stop),
|
||||
// => Some(VirtualKeyCode::Subtract),
|
||||
// => Some(VirtualKeyCode::Sysrq),
|
||||
keysyms::XKB_KEY_Tab => Some(VirtualKeyCode::Tab),
|
||||
keysyms::XKB_KEY_ISO_Left_Tab => Some(VirtualKeyCode::Tab),
|
||||
// => Some(VirtualKeyCode::Underline),
|
||||
// => Some(VirtualKeyCode::Unlabeled),
|
||||
keysyms::XKB_KEY_XF86AudioLowerVolume => Some(VirtualKeyCode::VolumeDown),
|
||||
keysyms::XKB_KEY_XF86AudioRaiseVolume => Some(VirtualKeyCode::VolumeUp),
|
||||
// => Some(VirtualKeyCode::Wake),
|
||||
// => Some(VirtualKeyCode::Webback),
|
||||
// => Some(VirtualKeyCode::WebFavorites),
|
||||
// => Some(VirtualKeyCode::WebForward),
|
||||
// => Some(VirtualKeyCode::WebHome),
|
||||
// => Some(VirtualKeyCode::WebRefresh),
|
||||
// => Some(VirtualKeyCode::WebSearch),
|
||||
// => Some(VirtualKeyCode::WebStop),
|
||||
// => Some(VirtualKeyCode::Yen),
|
||||
keysyms::XKB_KEY_XF86Copy => Some(VirtualKeyCode::Copy),
|
||||
keysyms::XKB_KEY_XF86Paste => Some(VirtualKeyCode::Paste),
|
||||
keysyms::XKB_KEY_XF86Cut => Some(VirtualKeyCode::Cut),
|
||||
// fallback
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl ModifiersState {
|
||||
pub(crate) fn from_wayland(mods: keyboard::ModifiersState) -> ModifiersState {
|
||||
let mut m = ModifiersState::empty();
|
||||
m.set(ModifiersState::SHIFT, mods.shift);
|
||||
m.set(ModifiersState::CTRL, mods.ctrl);
|
||||
m.set(ModifiersState::ALT, mods.alt);
|
||||
m.set(ModifiersState::LOGO, mods.logo);
|
||||
m
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,21 @@
|
||||
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd",
|
||||
target_os = "netbsd", target_os = "openbsd"))]
|
||||
#![cfg(any(
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
|
||||
pub use self::{
|
||||
event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget, MonitorHandle, VideoMode},
|
||||
window::Window,
|
||||
};
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
|
||||
use smithay_client_toolkit::reexports::client::protocol::wl_surface;
|
||||
pub use event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget};
|
||||
pub use output::{MonitorHandle, VideoMode};
|
||||
pub use window::Window;
|
||||
|
||||
mod env;
|
||||
mod event_loop;
|
||||
mod keyboard;
|
||||
mod pointer;
|
||||
mod touch;
|
||||
mod output;
|
||||
mod seat;
|
||||
mod window;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
@@ -33,6 +37,6 @@ impl WindowId {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn make_wid(s: &wl_surface::WlSurface) -> WindowId {
|
||||
WindowId(s.as_ref().c_ptr() as usize)
|
||||
fn make_wid(surface: &WlSurface) -> WindowId {
|
||||
WindowId(surface.as_ref().c_ptr() as usize)
|
||||
}
|
||||
|
||||
240
src/platform_impl/linux/wayland/output.rs
Normal file
240
src/platform_impl/linux/wayland/output.rs
Normal file
@@ -0,0 +1,240 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use sctk::reexports::client::protocol::wl_output::WlOutput;
|
||||
use sctk::reexports::client::Display;
|
||||
|
||||
use sctk::environment::Environment;
|
||||
use sctk::output::OutputStatusListener;
|
||||
|
||||
use crate::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use crate::monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode};
|
||||
use crate::platform_impl::platform::{
|
||||
MonitorHandle as PlatformMonitorHandle, VideoMode as PlatformVideoMode,
|
||||
};
|
||||
|
||||
use super::env::WinitEnv;
|
||||
use super::event_loop::EventLoopWindowTarget;
|
||||
|
||||
/// Output manager.
|
||||
pub struct OutputManager {
|
||||
/// A handle that actually performs all operations on outputs.
|
||||
handle: OutputManagerHandle,
|
||||
|
||||
_output_listener: OutputStatusListener,
|
||||
}
|
||||
|
||||
impl OutputManager {
|
||||
pub fn new(env: &Environment<WinitEnv>) -> Self {
|
||||
let handle = OutputManagerHandle::new();
|
||||
|
||||
// Handle existing outputs.
|
||||
for output in env.get_all_outputs() {
|
||||
match sctk::output::with_output_info(&output, |info| info.obsolete) {
|
||||
Some(false) => (),
|
||||
// The output is obsolete or we've failed to access its data, skipping.
|
||||
_ => continue,
|
||||
}
|
||||
|
||||
// The output is present and unusable, add it to the output manager manager.
|
||||
handle.add_output(output);
|
||||
}
|
||||
|
||||
let handle_for_listener = handle.clone();
|
||||
|
||||
let output_listener = env.listen_for_outputs(move |output, info, _| {
|
||||
if info.obsolete {
|
||||
handle_for_listener.remove_output(output)
|
||||
} else {
|
||||
handle_for_listener.add_output(output)
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
handle,
|
||||
_output_listener: output_listener,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle(&self) -> OutputManagerHandle {
|
||||
self.handle.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A handle to output manager.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OutputManagerHandle {
|
||||
outputs: Arc<Mutex<VecDeque<MonitorHandle>>>,
|
||||
}
|
||||
|
||||
impl OutputManagerHandle {
|
||||
fn new() -> Self {
|
||||
let outputs = Arc::new(Mutex::new(VecDeque::new()));
|
||||
Self { outputs }
|
||||
}
|
||||
|
||||
/// Handle addition of the output.
|
||||
fn add_output(&self, output: WlOutput) {
|
||||
let mut outputs = self.outputs.lock().unwrap();
|
||||
let position = outputs.iter().position(|handle| handle.proxy == output);
|
||||
if position.is_none() {
|
||||
outputs.push_back(MonitorHandle::new(output));
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle removal of the output.
|
||||
fn remove_output(&self, output: WlOutput) {
|
||||
let mut outputs = self.outputs.lock().unwrap();
|
||||
let position = outputs.iter().position(|handle| handle.proxy == output);
|
||||
if let Some(position) = position {
|
||||
outputs.remove(position);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get all observed outputs.
|
||||
pub fn available_outputs(&self) -> VecDeque<MonitorHandle> {
|
||||
self.outputs.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MonitorHandle {
|
||||
pub(crate) proxy: WlOutput,
|
||||
}
|
||||
|
||||
impl PartialEq for MonitorHandle {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.native_identifier() == other.native_identifier()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for MonitorHandle {}
|
||||
|
||||
impl PartialOrd for MonitorHandle {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(&other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for MonitorHandle {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.native_identifier().cmp(&other.native_identifier())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for MonitorHandle {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.native_identifier().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl MonitorHandle {
|
||||
#[inline]
|
||||
pub(crate) fn new(proxy: WlOutput) -> Self {
|
||||
Self { proxy }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn name(&self) -> Option<String> {
|
||||
sctk::output::with_output_info(&self.proxy, |info| {
|
||||
format!("{} ({})", info.model, info.make)
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn native_identifier(&self) -> u32 {
|
||||
sctk::output::with_output_info(&self.proxy, |info| info.id).unwrap_or(0)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
match sctk::output::with_output_info(&self.proxy, |info| {
|
||||
info.modes
|
||||
.iter()
|
||||
.find(|mode| mode.is_current)
|
||||
.map(|mode| mode.dimensions)
|
||||
}) {
|
||||
Some(Some((w, h))) => (w as u32, h as u32),
|
||||
_ => (0, 0),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||
sctk::output::with_output_info(&self.proxy, |info| info.location)
|
||||
.unwrap_or((0, 0))
|
||||
.into()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn scale_factor(&self) -> i32 {
|
||||
sctk::output::with_output_info(&self.proxy, |info| info.scale_factor).unwrap_or(1)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn video_modes(&self) -> impl Iterator<Item = RootVideoMode> {
|
||||
let modes = sctk::output::with_output_info(&self.proxy, |info| info.modes.clone())
|
||||
.unwrap_or_else(Vec::new);
|
||||
|
||||
let monitor = self.clone();
|
||||
|
||||
modes.into_iter().map(move |mode| RootVideoMode {
|
||||
video_mode: PlatformVideoMode::Wayland(VideoMode {
|
||||
size: (mode.dimensions.0 as u32, mode.dimensions.1 as u32).into(),
|
||||
refresh_rate: (mode.refresh_rate as f32 / 1000.0).round() as u16,
|
||||
bit_depth: 32,
|
||||
monitor: monitor.clone(),
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct VideoMode {
|
||||
pub(crate) size: PhysicalSize<u32>,
|
||||
pub(crate) bit_depth: u16,
|
||||
pub(crate) refresh_rate: u16,
|
||||
pub(crate) monitor: MonitorHandle,
|
||||
}
|
||||
|
||||
impl VideoMode {
|
||||
#[inline]
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
self.size
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn bit_depth(&self) -> u16 {
|
||||
self.bit_depth
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn refresh_rate(&self) -> u16 {
|
||||
self.refresh_rate
|
||||
}
|
||||
|
||||
pub fn monitor(&self) -> RootMonitorHandle {
|
||||
RootMonitorHandle {
|
||||
inner: PlatformMonitorHandle::Wayland(self.monitor.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventLoopWindowTarget<T> {
|
||||
#[inline]
|
||||
pub fn display(&self) -> &Display {
|
||||
&self.display
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
self.output_manager.handle.available_outputs()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
// There's no primary monitor on Wayland.
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -1,282 +0,0 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::event::{
|
||||
DeviceEvent, ElementState, ModifiersState, MouseButton, MouseScrollDelta, TouchPhase,
|
||||
WindowEvent,
|
||||
};
|
||||
|
||||
use super::{
|
||||
event_loop::{CursorManager, EventsSink},
|
||||
make_wid,
|
||||
window::WindowStore,
|
||||
DeviceId,
|
||||
};
|
||||
|
||||
use smithay_client_toolkit::surface;
|
||||
|
||||
use smithay_client_toolkit::reexports::client::protocol::{
|
||||
wl_pointer::{self, Event as PtrEvent, WlPointer},
|
||||
wl_seat,
|
||||
};
|
||||
|
||||
use smithay_client_toolkit::reexports::protocols::unstable::relative_pointer::v1::client::{
|
||||
zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1, zwp_relative_pointer_v1::Event,
|
||||
zwp_relative_pointer_v1::ZwpRelativePointerV1,
|
||||
};
|
||||
|
||||
use smithay_client_toolkit::reexports::protocols::unstable::pointer_constraints::v1::client::{
|
||||
zwp_locked_pointer_v1::ZwpLockedPointerV1, zwp_pointer_constraints_v1::Lifetime,
|
||||
zwp_pointer_constraints_v1::ZwpPointerConstraintsV1,
|
||||
};
|
||||
|
||||
use smithay_client_toolkit::reexports::client::protocol::wl_surface::WlSurface;
|
||||
|
||||
pub fn implement_pointer(
|
||||
seat: &wl_seat::WlSeat,
|
||||
sink: EventsSink,
|
||||
store: Arc<Mutex<WindowStore>>,
|
||||
modifiers_tracker: Arc<Mutex<ModifiersState>>,
|
||||
cursor_manager: Arc<Mutex<CursorManager>>,
|
||||
) -> WlPointer {
|
||||
seat.get_pointer(|pointer| {
|
||||
// Currently focused winit surface
|
||||
let mut mouse_focus = None;
|
||||
let mut axis_buffer = None;
|
||||
let mut axis_discrete_buffer = None;
|
||||
let mut axis_state = TouchPhase::Ended;
|
||||
|
||||
pointer.implement_closure(
|
||||
move |evt, pointer| {
|
||||
let store = store.lock().unwrap();
|
||||
let mut cursor_manager = cursor_manager.lock().unwrap();
|
||||
match evt {
|
||||
PtrEvent::Enter {
|
||||
surface,
|
||||
surface_x,
|
||||
surface_y,
|
||||
..
|
||||
} => {
|
||||
let wid = store.find_wid(&surface);
|
||||
|
||||
if let Some(wid) = wid {
|
||||
let scale_factor = surface::get_dpi_factor(&surface) as f64;
|
||||
mouse_focus = Some(surface);
|
||||
|
||||
// Reload cursor style only when we enter winit's surface. Calling
|
||||
// this function every time on `PtrEvent::Enter` could interfere with
|
||||
// SCTK CSD handling, since it changes cursor icons when you hover
|
||||
// cursor over the window borders.
|
||||
cursor_manager.reload_cursor_style();
|
||||
|
||||
sink.send_window_event(
|
||||
WindowEvent::CursorEntered {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
},
|
||||
wid,
|
||||
);
|
||||
sink.send_window_event(
|
||||
WindowEvent::CursorMoved {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
position: (surface_x * scale_factor, surface_y * scale_factor)
|
||||
.into(),
|
||||
modifiers: modifiers_tracker.lock().unwrap().clone(),
|
||||
},
|
||||
wid,
|
||||
);
|
||||
}
|
||||
}
|
||||
PtrEvent::Leave { surface, .. } => {
|
||||
mouse_focus = None;
|
||||
let wid = store.find_wid(&surface);
|
||||
if let Some(wid) = wid {
|
||||
sink.send_window_event(
|
||||
WindowEvent::CursorLeft {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
},
|
||||
wid,
|
||||
);
|
||||
}
|
||||
}
|
||||
PtrEvent::Motion {
|
||||
surface_x,
|
||||
surface_y,
|
||||
..
|
||||
} => {
|
||||
if let Some(surface) = mouse_focus.as_ref() {
|
||||
let scale_factor = surface::get_dpi_factor(&surface) as f64;
|
||||
let wid = make_wid(surface);
|
||||
sink.send_window_event(
|
||||
WindowEvent::CursorMoved {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
position: (surface_x * scale_factor, surface_y * scale_factor)
|
||||
.into(),
|
||||
modifiers: modifiers_tracker.lock().unwrap().clone(),
|
||||
},
|
||||
wid,
|
||||
);
|
||||
}
|
||||
}
|
||||
PtrEvent::Button { button, state, .. } => {
|
||||
if let Some(surface) = mouse_focus.as_ref() {
|
||||
let state = match state {
|
||||
wl_pointer::ButtonState::Pressed => ElementState::Pressed,
|
||||
wl_pointer::ButtonState::Released => ElementState::Released,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let button = match button {
|
||||
0x110 => MouseButton::Left,
|
||||
0x111 => MouseButton::Right,
|
||||
0x112 => MouseButton::Middle,
|
||||
// TODO figure out the translation ?
|
||||
_ => return,
|
||||
};
|
||||
sink.send_window_event(
|
||||
WindowEvent::MouseInput {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
state,
|
||||
button,
|
||||
modifiers: modifiers_tracker.lock().unwrap().clone(),
|
||||
},
|
||||
make_wid(surface),
|
||||
);
|
||||
}
|
||||
}
|
||||
PtrEvent::Axis { axis, value, .. } => {
|
||||
if let Some(surface) = mouse_focus.as_ref() {
|
||||
let wid = make_wid(surface);
|
||||
if pointer.as_ref().version() < 5 {
|
||||
let (mut x, mut y) = (0.0, 0.0);
|
||||
// old seat compatibility
|
||||
match axis {
|
||||
// wayland vertical sign convention is the inverse of winit
|
||||
wl_pointer::Axis::VerticalScroll => y -= value as f32,
|
||||
wl_pointer::Axis::HorizontalScroll => x += value as f32,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
sink.send_window_event(
|
||||
WindowEvent::MouseWheel {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
delta: MouseScrollDelta::PixelDelta(
|
||||
(x as f64, y as f64).into(),
|
||||
),
|
||||
phase: TouchPhase::Moved,
|
||||
modifiers: modifiers_tracker.lock().unwrap().clone(),
|
||||
},
|
||||
wid,
|
||||
);
|
||||
} else {
|
||||
let (mut x, mut y) = axis_buffer.unwrap_or((0.0, 0.0));
|
||||
match axis {
|
||||
// wayland vertical sign convention is the inverse of winit
|
||||
wl_pointer::Axis::VerticalScroll => y -= value as f32,
|
||||
wl_pointer::Axis::HorizontalScroll => x += value as f32,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
axis_buffer = Some((x, y));
|
||||
axis_state = match axis_state {
|
||||
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
|
||||
_ => TouchPhase::Started,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
PtrEvent::Frame => {
|
||||
let axis_buffer = axis_buffer.take();
|
||||
let axis_discrete_buffer = axis_discrete_buffer.take();
|
||||
if let Some(surface) = mouse_focus.as_ref() {
|
||||
let wid = make_wid(surface);
|
||||
if let Some((x, y)) = axis_discrete_buffer {
|
||||
sink.send_window_event(
|
||||
WindowEvent::MouseWheel {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
delta: MouseScrollDelta::LineDelta(x as f32, y as f32),
|
||||
phase: axis_state,
|
||||
modifiers: modifiers_tracker.lock().unwrap().clone(),
|
||||
},
|
||||
wid,
|
||||
);
|
||||
} else if let Some((x, y)) = axis_buffer {
|
||||
sink.send_window_event(
|
||||
WindowEvent::MouseWheel {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
delta: MouseScrollDelta::PixelDelta(
|
||||
(x as f64, y as f64).into(),
|
||||
),
|
||||
phase: axis_state,
|
||||
modifiers: modifiers_tracker.lock().unwrap().clone(),
|
||||
},
|
||||
wid,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
PtrEvent::AxisSource { .. } => (),
|
||||
PtrEvent::AxisStop { .. } => {
|
||||
axis_state = TouchPhase::Ended;
|
||||
}
|
||||
PtrEvent::AxisDiscrete { axis, discrete } => {
|
||||
let (mut x, mut y) = axis_discrete_buffer.unwrap_or((0, 0));
|
||||
match axis {
|
||||
// wayland vertical sign convention is the inverse of winit
|
||||
wl_pointer::Axis::VerticalScroll => y -= discrete,
|
||||
wl_pointer::Axis::HorizontalScroll => x += discrete,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
axis_discrete_buffer = Some((x, y));
|
||||
axis_state = match axis_state {
|
||||
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
|
||||
_ => TouchPhase::Started,
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
},
|
||||
(),
|
||||
)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn implement_relative_pointer(
|
||||
sink: EventsSink,
|
||||
pointer: &WlPointer,
|
||||
manager: &ZwpRelativePointerManagerV1,
|
||||
) -> Result<ZwpRelativePointerV1, ()> {
|
||||
manager.get_relative_pointer(pointer, |rel_pointer| {
|
||||
rel_pointer.implement_closure(
|
||||
move |evt, _rel_pointer| match evt {
|
||||
Event::RelativeMotion { dx, dy, .. } => {
|
||||
sink.send_device_event(DeviceEvent::MouseMotion { delta: (dx, dy) }, DeviceId)
|
||||
}
|
||||
_ => unreachable!(),
|
||||
},
|
||||
(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn implement_locked_pointer(
|
||||
surface: &WlSurface,
|
||||
pointer: &WlPointer,
|
||||
constraints: &ZwpPointerConstraintsV1,
|
||||
) -> Result<ZwpLockedPointerV1, ()> {
|
||||
constraints.lock_pointer(surface, pointer, None, Lifetime::Persistent.to_raw(), |c| {
|
||||
c.implement_closure(|_, _| (), ())
|
||||
})
|
||||
}
|
||||
151
src/platform_impl/linux/wayland/seat/keyboard/handlers.rs
Normal file
151
src/platform_impl/linux/wayland/seat/keyboard/handlers.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
//! Handling of various keyboard events.
|
||||
|
||||
use sctk::reexports::client::protocol::wl_keyboard::KeyState;
|
||||
|
||||
use sctk::seat::keyboard::Event as KeyboardEvent;
|
||||
|
||||
use crate::event::{ElementState, KeyboardInput, ModifiersState, WindowEvent};
|
||||
use crate::platform_impl::wayland::event_loop::WinitState;
|
||||
use crate::platform_impl::wayland::{self, DeviceId};
|
||||
|
||||
use super::keymap;
|
||||
use super::KeyboardInner;
|
||||
|
||||
#[inline]
|
||||
pub(super) fn handle_keyboard(
|
||||
event: KeyboardEvent<'_>,
|
||||
inner: &mut KeyboardInner,
|
||||
winit_state: &mut WinitState,
|
||||
) {
|
||||
let event_sink = &mut winit_state.event_sink;
|
||||
match event {
|
||||
KeyboardEvent::Enter { surface, .. } => {
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
|
||||
// Window gained focus.
|
||||
event_sink.push_window_event(WindowEvent::Focused(true), window_id);
|
||||
|
||||
// Dispatch modifers changes that we've received before getting `Enter` event.
|
||||
if let Some(modifiers) = inner.pending_modifers_state.take() {
|
||||
*inner.modifiers_state.borrow_mut() = modifiers;
|
||||
event_sink.push_window_event(WindowEvent::ModifiersChanged(modifiers), window_id);
|
||||
}
|
||||
|
||||
inner.target_window_id = Some(window_id);
|
||||
}
|
||||
KeyboardEvent::Leave { surface, .. } => {
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
|
||||
// Notify that no modifiers are being pressed.
|
||||
if !inner.modifiers_state.borrow().is_empty() {
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::ModifiersChanged(ModifiersState::empty()),
|
||||
window_id,
|
||||
);
|
||||
}
|
||||
|
||||
// Window lost focus.
|
||||
event_sink.push_window_event(WindowEvent::Focused(false), window_id);
|
||||
|
||||
// Reset the id.
|
||||
inner.target_window_id = None;
|
||||
}
|
||||
KeyboardEvent::Key {
|
||||
rawkey,
|
||||
keysym,
|
||||
state,
|
||||
utf8,
|
||||
..
|
||||
} => {
|
||||
let window_id = match inner.target_window_id {
|
||||
Some(window_id) => window_id,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let state = match state {
|
||||
KeyState::Pressed => ElementState::Pressed,
|
||||
KeyState::Released => ElementState::Released,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let virtual_keycode = keymap::keysym_to_vkey(keysym);
|
||||
|
||||
event_sink.push_window_event(
|
||||
#[allow(deprecated)]
|
||||
WindowEvent::KeyboardInput {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
input: KeyboardInput {
|
||||
state,
|
||||
scancode: rawkey,
|
||||
virtual_keycode,
|
||||
modifiers: *inner.modifiers_state.borrow(),
|
||||
},
|
||||
is_synthetic: false,
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
|
||||
// Send ReceivedCharacter event only on ElementState::Pressed.
|
||||
if ElementState::Released == state {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(txt) = utf8 {
|
||||
for ch in txt.chars() {
|
||||
event_sink.push_window_event(WindowEvent::ReceivedCharacter(ch), window_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyboardEvent::Repeat {
|
||||
rawkey,
|
||||
keysym,
|
||||
utf8,
|
||||
..
|
||||
} => {
|
||||
let window_id = match inner.target_window_id {
|
||||
Some(window_id) => window_id,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let virtual_keycode = keymap::keysym_to_vkey(keysym);
|
||||
|
||||
event_sink.push_window_event(
|
||||
#[allow(deprecated)]
|
||||
WindowEvent::KeyboardInput {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
input: KeyboardInput {
|
||||
state: ElementState::Pressed,
|
||||
scancode: rawkey,
|
||||
virtual_keycode,
|
||||
modifiers: *inner.modifiers_state.borrow(),
|
||||
},
|
||||
is_synthetic: false,
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
|
||||
if let Some(txt) = utf8 {
|
||||
for ch in txt.chars() {
|
||||
event_sink.push_window_event(WindowEvent::ReceivedCharacter(ch), window_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyboardEvent::Modifiers { modifiers } => {
|
||||
let modifiers = ModifiersState::from(modifiers);
|
||||
if let Some(window_id) = inner.target_window_id {
|
||||
*inner.modifiers_state.borrow_mut() = modifiers;
|
||||
|
||||
event_sink.push_window_event(WindowEvent::ModifiersChanged(modifiers), window_id);
|
||||
} else {
|
||||
// Compositor must send modifiers after wl_keyboard::enter, however certain
|
||||
// compositors are still sending it before, so stash such events and send
|
||||
// them on wl_keyboard::enter.
|
||||
inner.pending_modifers_state = Some(modifiers);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
188
src/platform_impl/linux/wayland/seat/keyboard/keymap.rs
Normal file
188
src/platform_impl/linux/wayland/seat/keyboard/keymap.rs
Normal file
@@ -0,0 +1,188 @@
|
||||
//! Convert Wayland keys to winit keys.
|
||||
|
||||
use crate::event::VirtualKeyCode;
|
||||
|
||||
pub fn keysym_to_vkey(keysym: u32) -> Option<VirtualKeyCode> {
|
||||
use sctk::seat::keyboard::keysyms;
|
||||
match keysym {
|
||||
// Numbers.
|
||||
keysyms::XKB_KEY_1 => Some(VirtualKeyCode::Key1),
|
||||
keysyms::XKB_KEY_2 => Some(VirtualKeyCode::Key2),
|
||||
keysyms::XKB_KEY_3 => Some(VirtualKeyCode::Key3),
|
||||
keysyms::XKB_KEY_4 => Some(VirtualKeyCode::Key4),
|
||||
keysyms::XKB_KEY_5 => Some(VirtualKeyCode::Key5),
|
||||
keysyms::XKB_KEY_6 => Some(VirtualKeyCode::Key6),
|
||||
keysyms::XKB_KEY_7 => Some(VirtualKeyCode::Key7),
|
||||
keysyms::XKB_KEY_8 => Some(VirtualKeyCode::Key8),
|
||||
keysyms::XKB_KEY_9 => Some(VirtualKeyCode::Key9),
|
||||
keysyms::XKB_KEY_0 => Some(VirtualKeyCode::Key0),
|
||||
// Letters.
|
||||
keysyms::XKB_KEY_A | keysyms::XKB_KEY_a => Some(VirtualKeyCode::A),
|
||||
keysyms::XKB_KEY_B | keysyms::XKB_KEY_b => Some(VirtualKeyCode::B),
|
||||
keysyms::XKB_KEY_C | keysyms::XKB_KEY_c => Some(VirtualKeyCode::C),
|
||||
keysyms::XKB_KEY_D | keysyms::XKB_KEY_d => Some(VirtualKeyCode::D),
|
||||
keysyms::XKB_KEY_E | keysyms::XKB_KEY_e => Some(VirtualKeyCode::E),
|
||||
keysyms::XKB_KEY_F | keysyms::XKB_KEY_f => Some(VirtualKeyCode::F),
|
||||
keysyms::XKB_KEY_G | keysyms::XKB_KEY_g => Some(VirtualKeyCode::G),
|
||||
keysyms::XKB_KEY_H | keysyms::XKB_KEY_h => Some(VirtualKeyCode::H),
|
||||
keysyms::XKB_KEY_I | keysyms::XKB_KEY_i => Some(VirtualKeyCode::I),
|
||||
keysyms::XKB_KEY_J | keysyms::XKB_KEY_j => Some(VirtualKeyCode::J),
|
||||
keysyms::XKB_KEY_K | keysyms::XKB_KEY_k => Some(VirtualKeyCode::K),
|
||||
keysyms::XKB_KEY_L | keysyms::XKB_KEY_l => Some(VirtualKeyCode::L),
|
||||
keysyms::XKB_KEY_M | keysyms::XKB_KEY_m => Some(VirtualKeyCode::M),
|
||||
keysyms::XKB_KEY_N | keysyms::XKB_KEY_n => Some(VirtualKeyCode::N),
|
||||
keysyms::XKB_KEY_O | keysyms::XKB_KEY_o => Some(VirtualKeyCode::O),
|
||||
keysyms::XKB_KEY_P | keysyms::XKB_KEY_p => Some(VirtualKeyCode::P),
|
||||
keysyms::XKB_KEY_Q | keysyms::XKB_KEY_q => Some(VirtualKeyCode::Q),
|
||||
keysyms::XKB_KEY_R | keysyms::XKB_KEY_r => Some(VirtualKeyCode::R),
|
||||
keysyms::XKB_KEY_S | keysyms::XKB_KEY_s => Some(VirtualKeyCode::S),
|
||||
keysyms::XKB_KEY_T | keysyms::XKB_KEY_t => Some(VirtualKeyCode::T),
|
||||
keysyms::XKB_KEY_U | keysyms::XKB_KEY_u => Some(VirtualKeyCode::U),
|
||||
keysyms::XKB_KEY_V | keysyms::XKB_KEY_v => Some(VirtualKeyCode::V),
|
||||
keysyms::XKB_KEY_W | keysyms::XKB_KEY_w => Some(VirtualKeyCode::W),
|
||||
keysyms::XKB_KEY_X | keysyms::XKB_KEY_x => Some(VirtualKeyCode::X),
|
||||
keysyms::XKB_KEY_Y | keysyms::XKB_KEY_y => Some(VirtualKeyCode::Y),
|
||||
keysyms::XKB_KEY_Z | keysyms::XKB_KEY_z => Some(VirtualKeyCode::Z),
|
||||
// Escape.
|
||||
keysyms::XKB_KEY_Escape => Some(VirtualKeyCode::Escape),
|
||||
// Function keys.
|
||||
keysyms::XKB_KEY_F1 => Some(VirtualKeyCode::F1),
|
||||
keysyms::XKB_KEY_F2 => Some(VirtualKeyCode::F2),
|
||||
keysyms::XKB_KEY_F3 => Some(VirtualKeyCode::F3),
|
||||
keysyms::XKB_KEY_F4 => Some(VirtualKeyCode::F4),
|
||||
keysyms::XKB_KEY_F5 => Some(VirtualKeyCode::F5),
|
||||
keysyms::XKB_KEY_F6 => Some(VirtualKeyCode::F6),
|
||||
keysyms::XKB_KEY_F7 => Some(VirtualKeyCode::F7),
|
||||
keysyms::XKB_KEY_F8 => Some(VirtualKeyCode::F8),
|
||||
keysyms::XKB_KEY_F9 => Some(VirtualKeyCode::F9),
|
||||
keysyms::XKB_KEY_F10 => Some(VirtualKeyCode::F10),
|
||||
keysyms::XKB_KEY_F11 => Some(VirtualKeyCode::F11),
|
||||
keysyms::XKB_KEY_F12 => Some(VirtualKeyCode::F12),
|
||||
keysyms::XKB_KEY_F13 => Some(VirtualKeyCode::F13),
|
||||
keysyms::XKB_KEY_F14 => Some(VirtualKeyCode::F14),
|
||||
keysyms::XKB_KEY_F15 => Some(VirtualKeyCode::F15),
|
||||
keysyms::XKB_KEY_F16 => Some(VirtualKeyCode::F16),
|
||||
keysyms::XKB_KEY_F17 => Some(VirtualKeyCode::F17),
|
||||
keysyms::XKB_KEY_F18 => Some(VirtualKeyCode::F18),
|
||||
keysyms::XKB_KEY_F19 => Some(VirtualKeyCode::F19),
|
||||
keysyms::XKB_KEY_F20 => Some(VirtualKeyCode::F20),
|
||||
keysyms::XKB_KEY_F21 => Some(VirtualKeyCode::F21),
|
||||
keysyms::XKB_KEY_F22 => Some(VirtualKeyCode::F22),
|
||||
keysyms::XKB_KEY_F23 => Some(VirtualKeyCode::F23),
|
||||
keysyms::XKB_KEY_F24 => Some(VirtualKeyCode::F24),
|
||||
// Flow control.
|
||||
keysyms::XKB_KEY_Print => Some(VirtualKeyCode::Snapshot),
|
||||
keysyms::XKB_KEY_Scroll_Lock => Some(VirtualKeyCode::Scroll),
|
||||
keysyms::XKB_KEY_Pause => Some(VirtualKeyCode::Pause),
|
||||
keysyms::XKB_KEY_Insert => Some(VirtualKeyCode::Insert),
|
||||
keysyms::XKB_KEY_Home => Some(VirtualKeyCode::Home),
|
||||
keysyms::XKB_KEY_Delete => Some(VirtualKeyCode::Delete),
|
||||
keysyms::XKB_KEY_End => Some(VirtualKeyCode::End),
|
||||
keysyms::XKB_KEY_Page_Down => Some(VirtualKeyCode::PageDown),
|
||||
keysyms::XKB_KEY_Page_Up => Some(VirtualKeyCode::PageUp),
|
||||
// Arrows.
|
||||
keysyms::XKB_KEY_Left => Some(VirtualKeyCode::Left),
|
||||
keysyms::XKB_KEY_Up => Some(VirtualKeyCode::Up),
|
||||
keysyms::XKB_KEY_Right => Some(VirtualKeyCode::Right),
|
||||
keysyms::XKB_KEY_Down => Some(VirtualKeyCode::Down),
|
||||
|
||||
keysyms::XKB_KEY_BackSpace => Some(VirtualKeyCode::Back),
|
||||
keysyms::XKB_KEY_Return => Some(VirtualKeyCode::Return),
|
||||
keysyms::XKB_KEY_space => Some(VirtualKeyCode::Space),
|
||||
|
||||
keysyms::XKB_KEY_Multi_key => Some(VirtualKeyCode::Compose),
|
||||
keysyms::XKB_KEY_caret => Some(VirtualKeyCode::Caret),
|
||||
|
||||
// Keypad.
|
||||
keysyms::XKB_KEY_Num_Lock => Some(VirtualKeyCode::Numlock),
|
||||
keysyms::XKB_KEY_KP_0 => Some(VirtualKeyCode::Numpad0),
|
||||
keysyms::XKB_KEY_KP_1 => Some(VirtualKeyCode::Numpad1),
|
||||
keysyms::XKB_KEY_KP_2 => Some(VirtualKeyCode::Numpad2),
|
||||
keysyms::XKB_KEY_KP_3 => Some(VirtualKeyCode::Numpad3),
|
||||
keysyms::XKB_KEY_KP_4 => Some(VirtualKeyCode::Numpad4),
|
||||
keysyms::XKB_KEY_KP_5 => Some(VirtualKeyCode::Numpad5),
|
||||
keysyms::XKB_KEY_KP_6 => Some(VirtualKeyCode::Numpad6),
|
||||
keysyms::XKB_KEY_KP_7 => Some(VirtualKeyCode::Numpad7),
|
||||
keysyms::XKB_KEY_KP_8 => Some(VirtualKeyCode::Numpad8),
|
||||
keysyms::XKB_KEY_KP_9 => Some(VirtualKeyCode::Numpad9),
|
||||
// Misc.
|
||||
// => Some(VirtualKeyCode::AbntC1),
|
||||
// => Some(VirtualKeyCode::AbntC2),
|
||||
keysyms::XKB_KEY_plus => Some(VirtualKeyCode::Plus),
|
||||
keysyms::XKB_KEY_apostrophe => Some(VirtualKeyCode::Apostrophe),
|
||||
// => Some(VirtualKeyCode::Apps),
|
||||
keysyms::XKB_KEY_at => Some(VirtualKeyCode::At),
|
||||
// => Some(VirtualKeyCode::Ax),
|
||||
keysyms::XKB_KEY_backslash => Some(VirtualKeyCode::Backslash),
|
||||
keysyms::XKB_KEY_XF86Calculator => Some(VirtualKeyCode::Calculator),
|
||||
// => Some(VirtualKeyCode::Capital),
|
||||
keysyms::XKB_KEY_colon => Some(VirtualKeyCode::Colon),
|
||||
keysyms::XKB_KEY_comma => Some(VirtualKeyCode::Comma),
|
||||
// => Some(VirtualKeyCode::Convert),
|
||||
keysyms::XKB_KEY_equal => Some(VirtualKeyCode::Equals),
|
||||
keysyms::XKB_KEY_grave => Some(VirtualKeyCode::Grave),
|
||||
// => Some(VirtualKeyCode::Kana),
|
||||
keysyms::XKB_KEY_Kanji => Some(VirtualKeyCode::Kanji),
|
||||
keysyms::XKB_KEY_Alt_L => Some(VirtualKeyCode::LAlt),
|
||||
keysyms::XKB_KEY_bracketleft => Some(VirtualKeyCode::LBracket),
|
||||
keysyms::XKB_KEY_Control_L => Some(VirtualKeyCode::LControl),
|
||||
keysyms::XKB_KEY_Shift_L => Some(VirtualKeyCode::LShift),
|
||||
keysyms::XKB_KEY_Super_L => Some(VirtualKeyCode::LWin),
|
||||
keysyms::XKB_KEY_XF86Mail => Some(VirtualKeyCode::Mail),
|
||||
// => Some(VirtualKeyCode::MediaSelect),
|
||||
// => Some(VirtualKeyCode::MediaStop),
|
||||
keysyms::XKB_KEY_minus => Some(VirtualKeyCode::Minus),
|
||||
keysyms::XKB_KEY_asterisk => Some(VirtualKeyCode::Asterisk),
|
||||
keysyms::XKB_KEY_XF86AudioMute => Some(VirtualKeyCode::Mute),
|
||||
// => Some(VirtualKeyCode::MyComputer),
|
||||
keysyms::XKB_KEY_XF86AudioNext => Some(VirtualKeyCode::NextTrack),
|
||||
// => Some(VirtualKeyCode::NoConvert),
|
||||
keysyms::XKB_KEY_KP_Separator => Some(VirtualKeyCode::NumpadComma),
|
||||
keysyms::XKB_KEY_KP_Enter => Some(VirtualKeyCode::NumpadEnter),
|
||||
keysyms::XKB_KEY_KP_Equal => Some(VirtualKeyCode::NumpadEquals),
|
||||
keysyms::XKB_KEY_KP_Add => Some(VirtualKeyCode::NumpadAdd),
|
||||
keysyms::XKB_KEY_KP_Subtract => Some(VirtualKeyCode::NumpadSubtract),
|
||||
keysyms::XKB_KEY_KP_Multiply => Some(VirtualKeyCode::NumpadMultiply),
|
||||
keysyms::XKB_KEY_KP_Divide => Some(VirtualKeyCode::NumpadDivide),
|
||||
keysyms::XKB_KEY_KP_Decimal => Some(VirtualKeyCode::NumpadDecimal),
|
||||
keysyms::XKB_KEY_KP_Page_Up => Some(VirtualKeyCode::PageUp),
|
||||
keysyms::XKB_KEY_KP_Page_Down => Some(VirtualKeyCode::PageDown),
|
||||
keysyms::XKB_KEY_KP_Home => Some(VirtualKeyCode::Home),
|
||||
keysyms::XKB_KEY_KP_End => Some(VirtualKeyCode::End),
|
||||
// => Some(VirtualKeyCode::OEM102),
|
||||
keysyms::XKB_KEY_period => Some(VirtualKeyCode::Period),
|
||||
// => Some(VirtualKeyCode::Playpause),
|
||||
keysyms::XKB_KEY_XF86PowerOff => Some(VirtualKeyCode::Power),
|
||||
keysyms::XKB_KEY_XF86AudioPrev => Some(VirtualKeyCode::PrevTrack),
|
||||
keysyms::XKB_KEY_Alt_R => Some(VirtualKeyCode::RAlt),
|
||||
keysyms::XKB_KEY_bracketright => Some(VirtualKeyCode::RBracket),
|
||||
keysyms::XKB_KEY_Control_R => Some(VirtualKeyCode::RControl),
|
||||
keysyms::XKB_KEY_Shift_R => Some(VirtualKeyCode::RShift),
|
||||
keysyms::XKB_KEY_Super_R => Some(VirtualKeyCode::RWin),
|
||||
keysyms::XKB_KEY_semicolon => Some(VirtualKeyCode::Semicolon),
|
||||
keysyms::XKB_KEY_slash => Some(VirtualKeyCode::Slash),
|
||||
keysyms::XKB_KEY_XF86Sleep => Some(VirtualKeyCode::Sleep),
|
||||
// => Some(VirtualKeyCode::Stop),
|
||||
// => Some(VirtualKeyCode::Sysrq),
|
||||
keysyms::XKB_KEY_Tab => Some(VirtualKeyCode::Tab),
|
||||
keysyms::XKB_KEY_ISO_Left_Tab => Some(VirtualKeyCode::Tab),
|
||||
keysyms::XKB_KEY_underscore => Some(VirtualKeyCode::Underline),
|
||||
// => Some(VirtualKeyCode::Unlabeled),
|
||||
keysyms::XKB_KEY_XF86AudioLowerVolume => Some(VirtualKeyCode::VolumeDown),
|
||||
keysyms::XKB_KEY_XF86AudioRaiseVolume => Some(VirtualKeyCode::VolumeUp),
|
||||
// => Some(VirtualKeyCode::Wake),
|
||||
// => Some(VirtualKeyCode::Webback),
|
||||
// => Some(VirtualKeyCode::WebFavorites),
|
||||
// => Some(VirtualKeyCode::WebForward),
|
||||
// => Some(VirtualKeyCode::WebHome),
|
||||
// => Some(VirtualKeyCode::WebRefresh),
|
||||
// => Some(VirtualKeyCode::WebSearch),
|
||||
// => Some(VirtualKeyCode::WebStop),
|
||||
keysyms::XKB_KEY_yen => Some(VirtualKeyCode::Yen),
|
||||
keysyms::XKB_KEY_XF86Copy => Some(VirtualKeyCode::Copy),
|
||||
keysyms::XKB_KEY_XF86Paste => Some(VirtualKeyCode::Paste),
|
||||
keysyms::XKB_KEY_XF86Cut => Some(VirtualKeyCode::Cut),
|
||||
// Fallback.
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
105
src/platform_impl/linux/wayland/seat/keyboard/mod.rs
Normal file
105
src/platform_impl/linux/wayland/seat/keyboard/mod.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
//! Wayland keyboard handling.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use sctk::reexports::client::protocol::wl_keyboard::WlKeyboard;
|
||||
use sctk::reexports::client::protocol::wl_seat::WlSeat;
|
||||
use sctk::reexports::client::Attached;
|
||||
|
||||
use sctk::reexports::calloop::{LoopHandle, Source};
|
||||
|
||||
use sctk::seat::keyboard::{self, RepeatSource};
|
||||
|
||||
use crate::event::ModifiersState;
|
||||
use crate::platform_impl::wayland::event_loop::WinitState;
|
||||
use crate::platform_impl::wayland::WindowId;
|
||||
|
||||
mod handlers;
|
||||
mod keymap;
|
||||
|
||||
pub(crate) struct Keyboard {
|
||||
pub keyboard: WlKeyboard,
|
||||
|
||||
/// The source for repeat keys.
|
||||
pub repeat_source: Option<Source<RepeatSource>>,
|
||||
|
||||
/// LoopHandle to drop `RepeatSource`, when dropping the keyboard.
|
||||
pub loop_handle: LoopHandle<WinitState>,
|
||||
}
|
||||
|
||||
impl Keyboard {
|
||||
pub fn new(
|
||||
seat: &Attached<WlSeat>,
|
||||
loop_handle: LoopHandle<WinitState>,
|
||||
modifiers_state: Rc<RefCell<ModifiersState>>,
|
||||
) -> Option<Self> {
|
||||
let mut inner = KeyboardInner::new(modifiers_state);
|
||||
let keyboard_data = keyboard::map_keyboard_repeat(
|
||||
loop_handle.clone(),
|
||||
&seat,
|
||||
None,
|
||||
keyboard::RepeatKind::System,
|
||||
move |event, _, mut dispatch_data| {
|
||||
let winit_state = dispatch_data.get::<WinitState>().unwrap();
|
||||
handlers::handle_keyboard(event, &mut inner, winit_state);
|
||||
},
|
||||
);
|
||||
|
||||
let (keyboard, repeat_source) = keyboard_data.ok()?;
|
||||
|
||||
Some(Self {
|
||||
keyboard,
|
||||
loop_handle,
|
||||
repeat_source: Some(repeat_source),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Keyboard {
|
||||
fn drop(&mut self) {
|
||||
if self.keyboard.as_ref().version() >= 3 {
|
||||
self.keyboard.release();
|
||||
}
|
||||
|
||||
if let Some(repeat_source) = self.repeat_source.take() {
|
||||
self.loop_handle.remove(repeat_source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct KeyboardInner {
|
||||
/// Currently focused surface.
|
||||
target_window_id: Option<WindowId>,
|
||||
|
||||
/// A pending state of modifiers.
|
||||
///
|
||||
/// This state is getting set if we've got a modifiers update
|
||||
/// before `Enter` event, which shouldn't happen in general, however
|
||||
/// some compositors are still doing so.
|
||||
pending_modifers_state: Option<ModifiersState>,
|
||||
|
||||
/// Current state of modifiers keys.
|
||||
modifiers_state: Rc<RefCell<ModifiersState>>,
|
||||
}
|
||||
|
||||
impl KeyboardInner {
|
||||
fn new(modifiers_state: Rc<RefCell<ModifiersState>>) -> Self {
|
||||
Self {
|
||||
target_window_id: None,
|
||||
pending_modifers_state: None,
|
||||
modifiers_state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<keyboard::ModifiersState> for ModifiersState {
|
||||
fn from(mods: keyboard::ModifiersState) -> ModifiersState {
|
||||
let mut wl_mods = ModifiersState::empty();
|
||||
wl_mods.set(ModifiersState::SHIFT, mods.shift);
|
||||
wl_mods.set(ModifiersState::CTRL, mods.ctrl);
|
||||
wl_mods.set(ModifiersState::ALT, mods.alt);
|
||||
wl_mods.set(ModifiersState::LOGO, mods.logo);
|
||||
wl_mods
|
||||
}
|
||||
}
|
||||
208
src/platform_impl/linux/wayland/seat/mod.rs
Normal file
208
src/platform_impl/linux/wayland/seat/mod.rs
Normal file
@@ -0,0 +1,208 @@
|
||||
//! Seat handling and managing.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1;
|
||||
use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPointerConstraintsV1;
|
||||
use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3;
|
||||
|
||||
use sctk::reexports::client::protocol::wl_seat::WlSeat;
|
||||
use sctk::reexports::client::Attached;
|
||||
|
||||
use sctk::environment::Environment;
|
||||
use sctk::reexports::calloop::LoopHandle;
|
||||
use sctk::seat::pointer::ThemeManager;
|
||||
use sctk::seat::{SeatData, SeatListener};
|
||||
|
||||
use super::env::WinitEnv;
|
||||
use super::event_loop::WinitState;
|
||||
use crate::event::ModifiersState;
|
||||
|
||||
mod keyboard;
|
||||
pub mod pointer;
|
||||
pub mod text_input;
|
||||
mod touch;
|
||||
|
||||
use keyboard::Keyboard;
|
||||
use pointer::Pointers;
|
||||
use text_input::TextInput;
|
||||
use touch::Touch;
|
||||
|
||||
pub struct SeatManager {
|
||||
/// Listener for seats.
|
||||
_seat_listener: SeatListener,
|
||||
}
|
||||
|
||||
impl SeatManager {
|
||||
pub fn new(
|
||||
env: &Environment<WinitEnv>,
|
||||
loop_handle: LoopHandle<WinitState>,
|
||||
theme_manager: ThemeManager,
|
||||
) -> Self {
|
||||
let relative_pointer_manager = env.get_global::<ZwpRelativePointerManagerV1>();
|
||||
let pointer_constraints = env.get_global::<ZwpPointerConstraintsV1>();
|
||||
let text_input_manager = env.get_global::<ZwpTextInputManagerV3>();
|
||||
|
||||
let mut inner = SeatManagerInner::new(
|
||||
theme_manager,
|
||||
relative_pointer_manager,
|
||||
pointer_constraints,
|
||||
text_input_manager,
|
||||
loop_handle,
|
||||
);
|
||||
|
||||
// Handle existing seats.
|
||||
for seat in env.get_all_seats() {
|
||||
let seat_data = match sctk::seat::clone_seat_data(&seat) {
|
||||
Some(seat_data) => seat_data,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
inner.process_seat_update(&seat, &seat_data);
|
||||
}
|
||||
|
||||
let seat_listener = env.listen_for_seats(move |seat, seat_data, _| {
|
||||
inner.process_seat_update(&seat, &seat_data);
|
||||
});
|
||||
|
||||
Self {
|
||||
_seat_listener: seat_listener,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Inner state of the seat manager.
|
||||
struct SeatManagerInner {
|
||||
/// Currently observed seats.
|
||||
seats: Vec<SeatInfo>,
|
||||
|
||||
/// Loop handle.
|
||||
loop_handle: LoopHandle<WinitState>,
|
||||
|
||||
/// Relative pointer manager.
|
||||
relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>,
|
||||
|
||||
/// Pointer constraints.
|
||||
pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>,
|
||||
|
||||
/// Text input manager.
|
||||
text_input_manager: Option<Attached<ZwpTextInputManagerV3>>,
|
||||
|
||||
/// A theme manager.
|
||||
theme_manager: ThemeManager,
|
||||
}
|
||||
|
||||
impl SeatManagerInner {
|
||||
fn new(
|
||||
theme_manager: ThemeManager,
|
||||
relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>,
|
||||
pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>,
|
||||
text_input_manager: Option<Attached<ZwpTextInputManagerV3>>,
|
||||
loop_handle: LoopHandle<WinitState>,
|
||||
) -> Self {
|
||||
Self {
|
||||
seats: Vec::new(),
|
||||
loop_handle,
|
||||
relative_pointer_manager,
|
||||
pointer_constraints,
|
||||
text_input_manager,
|
||||
theme_manager,
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle seats update from the `SeatListener`.
|
||||
pub fn process_seat_update(&mut self, seat: &Attached<WlSeat>, seat_data: &SeatData) {
|
||||
let detached_seat = seat.detach();
|
||||
|
||||
let position = self.seats.iter().position(|si| si.seat == detached_seat);
|
||||
let index = position.unwrap_or_else(|| {
|
||||
self.seats.push(SeatInfo::new(detached_seat));
|
||||
self.seats.len() - 1
|
||||
});
|
||||
|
||||
let seat_info = &mut self.seats[index];
|
||||
|
||||
// Pointer handling.
|
||||
if seat_data.has_pointer && !seat_data.defunct {
|
||||
if seat_info.pointer.is_none() {
|
||||
seat_info.pointer = Some(Pointers::new(
|
||||
&seat,
|
||||
&self.theme_manager,
|
||||
&self.relative_pointer_manager,
|
||||
&self.pointer_constraints,
|
||||
seat_info.modifiers_state.clone(),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
seat_info.pointer = None;
|
||||
}
|
||||
|
||||
// Handle keyboard.
|
||||
if seat_data.has_keyboard && !seat_data.defunct {
|
||||
if seat_info.keyboard.is_none() {
|
||||
seat_info.keyboard = Keyboard::new(
|
||||
&seat,
|
||||
self.loop_handle.clone(),
|
||||
seat_info.modifiers_state.clone(),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
seat_info.keyboard = None;
|
||||
}
|
||||
|
||||
// Handle touch.
|
||||
if seat_data.has_touch && !seat_data.defunct {
|
||||
if seat_info.touch.is_none() {
|
||||
seat_info.touch = Some(Touch::new(&seat));
|
||||
}
|
||||
} else {
|
||||
seat_info.touch = None;
|
||||
}
|
||||
|
||||
// Handle text input.
|
||||
if let Some(text_input_manager) = self.text_input_manager.as_ref() {
|
||||
if seat_data.defunct {
|
||||
seat_info.text_input = None;
|
||||
} else if seat_info.text_input.is_none() {
|
||||
seat_info.text_input = Some(TextInput::new(&seat, &text_input_manager));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resources associtated with a given seat.
|
||||
struct SeatInfo {
|
||||
/// Seat to which this `SeatInfo` belongs.
|
||||
seat: WlSeat,
|
||||
|
||||
/// A keyboard handle with its repeat rate handling.
|
||||
keyboard: Option<Keyboard>,
|
||||
|
||||
/// All pointers we're using on a seat.
|
||||
pointer: Option<Pointers>,
|
||||
|
||||
/// Touch handling.
|
||||
touch: Option<Touch>,
|
||||
|
||||
/// Text input handling aka IME.
|
||||
text_input: Option<TextInput>,
|
||||
|
||||
/// The current state of modifiers observed in keyboard handler.
|
||||
///
|
||||
/// We keep modifiers state on a seat, since it's being used by pointer events as well.
|
||||
modifiers_state: Rc<RefCell<ModifiersState>>,
|
||||
}
|
||||
|
||||
impl SeatInfo {
|
||||
pub fn new(seat: WlSeat) -> Self {
|
||||
Self {
|
||||
seat,
|
||||
keyboard: None,
|
||||
pointer: None,
|
||||
touch: None,
|
||||
text_input: None,
|
||||
modifiers_state: Rc::new(RefCell::new(ModifiersState::default())),
|
||||
}
|
||||
}
|
||||
}
|
||||
74
src/platform_impl/linux/wayland/seat/pointer/data.rs
Normal file
74
src/platform_impl/linux/wayland/seat/pointer/data.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
//! Data which is used in pointer callbacks.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use sctk::reexports::client::Attached;
|
||||
use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::{ZwpPointerConstraintsV1};
|
||||
use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_confined_pointer_v1::ZwpConfinedPointerV1;
|
||||
|
||||
use crate::event::{ModifiersState, TouchPhase};
|
||||
|
||||
/// A data being used by pointer handlers.
|
||||
pub(super) struct PointerData {
|
||||
/// Winit's surface the pointer is currently over.
|
||||
pub surface: Option<WlSurface>,
|
||||
|
||||
/// Current modifiers state.
|
||||
///
|
||||
/// This refers a state of modifiers from `WlKeyboard` on
|
||||
/// the given seat.
|
||||
pub modifiers_state: Rc<RefCell<ModifiersState>>,
|
||||
|
||||
/// Pointer constraints.
|
||||
pub pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>,
|
||||
|
||||
pub confined_pointer: Rc<RefCell<Option<ZwpConfinedPointerV1>>>,
|
||||
|
||||
/// A latest event serial.
|
||||
pub latest_serial: Rc<Cell<u32>>,
|
||||
|
||||
/// The currently accumulated axis data on a pointer.
|
||||
pub axis_data: AxisData,
|
||||
}
|
||||
|
||||
impl PointerData {
|
||||
pub fn new(
|
||||
confined_pointer: Rc<RefCell<Option<ZwpConfinedPointerV1>>>,
|
||||
pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>,
|
||||
modifiers_state: Rc<RefCell<ModifiersState>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
surface: None,
|
||||
latest_serial: Rc::new(Cell::new(0)),
|
||||
confined_pointer,
|
||||
modifiers_state,
|
||||
pointer_constraints,
|
||||
axis_data: AxisData::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Axis data.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct AxisData {
|
||||
/// Current state of the axis.
|
||||
pub axis_state: TouchPhase,
|
||||
|
||||
/// A buffer for `PixelDelta` event.
|
||||
pub axis_buffer: Option<(f32, f32)>,
|
||||
|
||||
/// A buffer for `LineDelta` event.
|
||||
pub axis_discrete_buffer: Option<(f32, f32)>,
|
||||
}
|
||||
|
||||
impl AxisData {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
axis_state: TouchPhase::Ended,
|
||||
axis_buffer: None,
|
||||
axis_discrete_buffer: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
297
src/platform_impl/linux/wayland/seat/pointer/handlers.rs
Normal file
297
src/platform_impl/linux/wayland/seat/pointer/handlers.rs
Normal file
@@ -0,0 +1,297 @@
|
||||
//! Handlers for the pointers we're using.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use sctk::reexports::client::protocol::wl_pointer::{self, Event as PointerEvent};
|
||||
use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_v1::Event as RelativePointerEvent;
|
||||
|
||||
use sctk::seat::pointer::ThemedPointer;
|
||||
|
||||
use crate::dpi::LogicalPosition;
|
||||
use crate::event::{
|
||||
DeviceEvent, ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent,
|
||||
};
|
||||
use crate::platform_impl::wayland::event_loop::WinitState;
|
||||
use crate::platform_impl::wayland::{self, DeviceId};
|
||||
|
||||
use super::{PointerData, WinitPointer};
|
||||
|
||||
#[inline]
|
||||
pub(super) fn handle_pointer(
|
||||
pointer: ThemedPointer,
|
||||
event: PointerEvent,
|
||||
pointer_data: &Rc<RefCell<PointerData>>,
|
||||
winit_state: &mut WinitState,
|
||||
) {
|
||||
let event_sink = &mut winit_state.event_sink;
|
||||
let mut pointer_data = pointer_data.borrow_mut();
|
||||
match event {
|
||||
PointerEvent::Enter {
|
||||
surface,
|
||||
surface_x,
|
||||
surface_y,
|
||||
serial,
|
||||
..
|
||||
} => {
|
||||
pointer_data.latest_serial.replace(serial);
|
||||
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
if !winit_state.window_map.contains_key(&window_id) {
|
||||
return;
|
||||
}
|
||||
let window_handle = match winit_state.window_map.get_mut(&window_id) {
|
||||
Some(window_handle) => window_handle,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let scale_factor = sctk::get_surface_scale_factor(&surface) as f64;
|
||||
pointer_data.surface = Some(surface);
|
||||
|
||||
// Notify window that pointer entered the surface.
|
||||
let winit_pointer = WinitPointer {
|
||||
pointer,
|
||||
confined_pointer: Rc::downgrade(&pointer_data.confined_pointer),
|
||||
pointer_constraints: pointer_data.pointer_constraints.clone(),
|
||||
latest_serial: pointer_data.latest_serial.clone(),
|
||||
};
|
||||
window_handle.pointer_entered(winit_pointer);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::CursorEntered {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
|
||||
let position = LogicalPosition::new(surface_x, surface_y).to_physical(scale_factor);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::CursorMoved {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
position,
|
||||
modifiers: *pointer_data.modifiers_state.borrow(),
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
}
|
||||
PointerEvent::Leave { surface, serial } => {
|
||||
pointer_data.surface = None;
|
||||
pointer_data.latest_serial.replace(serial);
|
||||
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
|
||||
let window_handle = match winit_state.window_map.get_mut(&window_id) {
|
||||
Some(window_handle) => window_handle,
|
||||
None => return,
|
||||
};
|
||||
|
||||
// Notify a window that pointer is no longer observing it.
|
||||
let winit_pointer = WinitPointer {
|
||||
pointer,
|
||||
confined_pointer: Rc::downgrade(&pointer_data.confined_pointer),
|
||||
pointer_constraints: pointer_data.pointer_constraints.clone(),
|
||||
latest_serial: pointer_data.latest_serial.clone(),
|
||||
};
|
||||
window_handle.pointer_left(winit_pointer);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::CursorLeft {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
}
|
||||
PointerEvent::Motion {
|
||||
surface_x,
|
||||
surface_y,
|
||||
..
|
||||
} => {
|
||||
let surface = match pointer_data.surface.as_ref() {
|
||||
Some(surface) => surface,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let window_id = wayland::make_wid(surface);
|
||||
|
||||
let scale_factor = sctk::get_surface_scale_factor(&surface) as f64;
|
||||
let position = LogicalPosition::new(surface_x, surface_y).to_physical(scale_factor);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::CursorMoved {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
position,
|
||||
modifiers: *pointer_data.modifiers_state.borrow(),
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
}
|
||||
PointerEvent::Button {
|
||||
button,
|
||||
state,
|
||||
serial,
|
||||
..
|
||||
} => {
|
||||
pointer_data.latest_serial.replace(serial);
|
||||
let window_id = match pointer_data.surface.as_ref().map(wayland::make_wid) {
|
||||
Some(window_id) => window_id,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let state = match state {
|
||||
wl_pointer::ButtonState::Pressed => ElementState::Pressed,
|
||||
wl_pointer::ButtonState::Released => ElementState::Released,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let button = match button {
|
||||
0x110 => MouseButton::Left,
|
||||
0x111 => MouseButton::Right,
|
||||
0x112 => MouseButton::Middle,
|
||||
// TODO - figure out the translation.
|
||||
_ => return,
|
||||
};
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::MouseInput {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
state,
|
||||
button,
|
||||
modifiers: *pointer_data.modifiers_state.borrow(),
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
}
|
||||
PointerEvent::Axis { axis, value, .. } => {
|
||||
let surface = match pointer_data.surface.as_ref() {
|
||||
Some(surface) => surface,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
|
||||
if pointer.as_ref().version() < 5 {
|
||||
let (mut x, mut y) = (0.0, 0.0);
|
||||
|
||||
// Old seat compatibility.
|
||||
match axis {
|
||||
// Wayland vertical sign convention is the inverse of winit.
|
||||
wl_pointer::Axis::VerticalScroll => y -= value as f32,
|
||||
wl_pointer::Axis::HorizontalScroll => x += value as f32,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
let scale_factor = sctk::get_surface_scale_factor(&surface) as f64;
|
||||
let delta = LogicalPosition::new(x as f64, y as f64).to_physical(scale_factor);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::MouseWheel {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
delta: MouseScrollDelta::PixelDelta(delta),
|
||||
phase: TouchPhase::Moved,
|
||||
modifiers: *pointer_data.modifiers_state.borrow(),
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
} else {
|
||||
let (mut x, mut y) = pointer_data.axis_data.axis_buffer.unwrap_or((0.0, 0.0));
|
||||
match axis {
|
||||
// Wayland vertical sign convention is the inverse of winit.
|
||||
wl_pointer::Axis::VerticalScroll => y -= value as f32,
|
||||
wl_pointer::Axis::HorizontalScroll => x += value as f32,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
pointer_data.axis_data.axis_buffer = Some((x, y));
|
||||
|
||||
pointer_data.axis_data.axis_state = match pointer_data.axis_data.axis_state {
|
||||
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
|
||||
_ => TouchPhase::Started,
|
||||
}
|
||||
}
|
||||
}
|
||||
PointerEvent::AxisDiscrete { axis, discrete } => {
|
||||
let (mut x, mut y) = pointer_data
|
||||
.axis_data
|
||||
.axis_discrete_buffer
|
||||
.unwrap_or((0., 0.));
|
||||
|
||||
match axis {
|
||||
// Wayland vertical sign convention is the inverse of winit.
|
||||
wl_pointer::Axis::VerticalScroll => y -= discrete as f32,
|
||||
wl_pointer::Axis::HorizontalScroll => x += discrete as f32,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
pointer_data.axis_data.axis_discrete_buffer = Some((x, y));
|
||||
|
||||
pointer_data.axis_data.axis_state = match pointer_data.axis_data.axis_state {
|
||||
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
|
||||
_ => TouchPhase::Started,
|
||||
}
|
||||
}
|
||||
PointerEvent::AxisSource { .. } => (),
|
||||
PointerEvent::AxisStop { .. } => {
|
||||
pointer_data.axis_data.axis_state = TouchPhase::Ended;
|
||||
}
|
||||
PointerEvent::Frame => {
|
||||
let axis_buffer = pointer_data.axis_data.axis_buffer.take();
|
||||
let axis_discrete_buffer = pointer_data.axis_data.axis_discrete_buffer.take();
|
||||
|
||||
let surface = match pointer_data.surface.as_ref() {
|
||||
Some(surface) => surface,
|
||||
None => return,
|
||||
};
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
|
||||
let window_event = if let Some((x, y)) = axis_discrete_buffer {
|
||||
WindowEvent::MouseWheel {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
delta: MouseScrollDelta::LineDelta(x, y),
|
||||
phase: pointer_data.axis_data.axis_state,
|
||||
modifiers: *pointer_data.modifiers_state.borrow(),
|
||||
}
|
||||
} else if let Some((x, y)) = axis_buffer {
|
||||
let scale_factor = sctk::get_surface_scale_factor(&surface) as f64;
|
||||
let delta = LogicalPosition::new(x, y).to_physical(scale_factor);
|
||||
|
||||
WindowEvent::MouseWheel {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
delta: MouseScrollDelta::PixelDelta(delta),
|
||||
phase: pointer_data.axis_data.axis_state,
|
||||
modifiers: *pointer_data.modifiers_state.borrow(),
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
|
||||
event_sink.push_window_event(window_event, window_id);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn handle_relative_pointer(event: RelativePointerEvent, winit_state: &mut WinitState) {
|
||||
if let RelativePointerEvent::RelativeMotion { dx, dy, .. } = event {
|
||||
winit_state
|
||||
.event_sink
|
||||
.push_device_event(DeviceEvent::MouseMotion { delta: (dx, dy) }, DeviceId)
|
||||
}
|
||||
}
|
||||
242
src/platform_impl/linux/wayland/seat/pointer/mod.rs
Normal file
242
src/platform_impl/linux/wayland/seat/pointer/mod.rs
Normal file
@@ -0,0 +1,242 @@
|
||||
//! All pointer related handling.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::{Rc, Weak};
|
||||
|
||||
use sctk::reexports::client::protocol::wl_pointer::WlPointer;
|
||||
use sctk::reexports::client::protocol::wl_seat::WlSeat;
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use sctk::reexports::client::Attached;
|
||||
use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1;
|
||||
use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_v1::ZwpRelativePointerV1;
|
||||
use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::{ZwpPointerConstraintsV1, Lifetime};
|
||||
use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_confined_pointer_v1::ZwpConfinedPointerV1;
|
||||
|
||||
use sctk::seat::pointer::{ThemeManager, ThemedPointer};
|
||||
|
||||
use crate::event::ModifiersState;
|
||||
use crate::platform_impl::wayland::event_loop::WinitState;
|
||||
use crate::window::CursorIcon;
|
||||
|
||||
mod data;
|
||||
mod handlers;
|
||||
|
||||
use data::PointerData;
|
||||
|
||||
/// A proxy to Wayland pointer, which serves requests from a `WindowHandle`.
|
||||
pub struct WinitPointer {
|
||||
pointer: ThemedPointer,
|
||||
|
||||
/// Create confined pointers.
|
||||
pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>,
|
||||
|
||||
/// Cursor to handle confine requests.
|
||||
confined_pointer: Weak<RefCell<Option<ZwpConfinedPointerV1>>>,
|
||||
|
||||
/// Latest observed serial in pointer events.
|
||||
latest_serial: Rc<Cell<u32>>,
|
||||
}
|
||||
|
||||
impl PartialEq for WinitPointer {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
*self.pointer == *other.pointer
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for WinitPointer {}
|
||||
|
||||
impl WinitPointer {
|
||||
/// Set the cursor icon.
|
||||
///
|
||||
/// Providing `None` will hide the cursor.
|
||||
pub fn set_cursor(&self, cursor_icon: Option<CursorIcon>) {
|
||||
let cursor_icon = match cursor_icon {
|
||||
Some(cursor_icon) => cursor_icon,
|
||||
None => {
|
||||
// Hide the cursor.
|
||||
(*self.pointer).set_cursor(self.latest_serial.get(), None, 0, 0);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let cursors: &[&str] = match cursor_icon {
|
||||
CursorIcon::Alias => &["link"],
|
||||
CursorIcon::Arrow => &["arrow"],
|
||||
CursorIcon::Cell => &["plus"],
|
||||
CursorIcon::Copy => &["copy"],
|
||||
CursorIcon::Crosshair => &["crosshair"],
|
||||
CursorIcon::Default => &["left_ptr"],
|
||||
CursorIcon::Hand => &["hand"],
|
||||
CursorIcon::Help => &["question_arrow"],
|
||||
CursorIcon::Move => &["move"],
|
||||
CursorIcon::Grab => &["openhand", "grab"],
|
||||
CursorIcon::Grabbing => &["closedhand", "grabbing"],
|
||||
CursorIcon::Progress => &["progress"],
|
||||
CursorIcon::AllScroll => &["all-scroll"],
|
||||
CursorIcon::ContextMenu => &["context-menu"],
|
||||
|
||||
CursorIcon::NoDrop => &["no-drop", "circle"],
|
||||
CursorIcon::NotAllowed => &["crossed_circle"],
|
||||
|
||||
// Resize cursors
|
||||
CursorIcon::EResize => &["right_side"],
|
||||
CursorIcon::NResize => &["top_side"],
|
||||
CursorIcon::NeResize => &["top_right_corner"],
|
||||
CursorIcon::NwResize => &["top_left_corner"],
|
||||
CursorIcon::SResize => &["bottom_side"],
|
||||
CursorIcon::SeResize => &["bottom_right_corner"],
|
||||
CursorIcon::SwResize => &["bottom_left_corner"],
|
||||
CursorIcon::WResize => &["left_side"],
|
||||
CursorIcon::EwResize => &["h_double_arrow"],
|
||||
CursorIcon::NsResize => &["v_double_arrow"],
|
||||
CursorIcon::NwseResize => &["bd_double_arrow", "size_bdiag"],
|
||||
CursorIcon::NeswResize => &["fd_double_arrow", "size_fdiag"],
|
||||
CursorIcon::ColResize => &["split_h", "h_double_arrow"],
|
||||
CursorIcon::RowResize => &["split_v", "v_double_arrow"],
|
||||
CursorIcon::Text => &["text", "xterm"],
|
||||
CursorIcon::VerticalText => &["vertical-text"],
|
||||
|
||||
CursorIcon::Wait => &["watch"],
|
||||
|
||||
CursorIcon::ZoomIn => &["zoom-in"],
|
||||
CursorIcon::ZoomOut => &["zoom-out"],
|
||||
};
|
||||
|
||||
let serial = Some(self.latest_serial.get());
|
||||
for cursor in cursors {
|
||||
if self.pointer.set_cursor(cursor, serial).is_ok() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Confine the pointer to a surface.
|
||||
pub fn confine(&self, surface: &WlSurface) {
|
||||
let pointer_constraints = match &self.pointer_constraints {
|
||||
Some(pointer_constraints) => pointer_constraints,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let confined_pointer = match self.confined_pointer.upgrade() {
|
||||
Some(confined_pointer) => confined_pointer,
|
||||
// A pointer is gone.
|
||||
None => return,
|
||||
};
|
||||
|
||||
*confined_pointer.borrow_mut() = Some(init_confined_pointer(
|
||||
&pointer_constraints,
|
||||
&surface,
|
||||
&*self.pointer,
|
||||
));
|
||||
}
|
||||
|
||||
/// Tries to unconfine the pointer if the current pointer is confined.
|
||||
pub fn unconfine(&self) {
|
||||
let confined_pointer = match self.confined_pointer.upgrade() {
|
||||
Some(confined_pointer) => confined_pointer,
|
||||
// A pointer is gone.
|
||||
None => return,
|
||||
};
|
||||
|
||||
let mut confined_pointer = confined_pointer.borrow_mut();
|
||||
|
||||
if let Some(confined_pointer) = confined_pointer.take() {
|
||||
confined_pointer.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A pointer wrapper for easy releasing and managing pointers.
|
||||
pub(super) struct Pointers {
|
||||
/// A pointer itself.
|
||||
pointer: ThemedPointer,
|
||||
|
||||
/// A relative pointer handler.
|
||||
relative_pointer: Option<ZwpRelativePointerV1>,
|
||||
|
||||
/// Confined pointer.
|
||||
confined_pointer: Rc<RefCell<Option<ZwpConfinedPointerV1>>>,
|
||||
}
|
||||
|
||||
impl Pointers {
|
||||
pub(super) fn new(
|
||||
seat: &Attached<WlSeat>,
|
||||
theme_manager: &ThemeManager,
|
||||
relative_pointer_manager: &Option<Attached<ZwpRelativePointerManagerV1>>,
|
||||
pointer_constraints: &Option<Attached<ZwpPointerConstraintsV1>>,
|
||||
modifiers_state: Rc<RefCell<ModifiersState>>,
|
||||
) -> Self {
|
||||
let confined_pointer = Rc::new(RefCell::new(None));
|
||||
let pointer_data = Rc::new(RefCell::new(PointerData::new(
|
||||
confined_pointer.clone(),
|
||||
pointer_constraints.clone(),
|
||||
modifiers_state,
|
||||
)));
|
||||
let pointer = theme_manager.theme_pointer_with_impl(
|
||||
seat,
|
||||
move |event, pointer, mut dispatch_data| {
|
||||
let winit_state = dispatch_data.get::<WinitState>().unwrap();
|
||||
handlers::handle_pointer(pointer, event, &pointer_data, winit_state);
|
||||
},
|
||||
);
|
||||
|
||||
// Setup relative_pointer if it's available.
|
||||
let relative_pointer = match relative_pointer_manager.as_ref() {
|
||||
Some(relative_pointer_manager) => {
|
||||
Some(init_relative_pointer(&relative_pointer_manager, &*pointer))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
Self {
|
||||
pointer,
|
||||
relative_pointer,
|
||||
confined_pointer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Pointers {
|
||||
fn drop(&mut self) {
|
||||
// Drop relative pointer.
|
||||
if let Some(relative_pointer) = self.relative_pointer.take() {
|
||||
relative_pointer.destroy();
|
||||
}
|
||||
|
||||
// Drop confined pointer.
|
||||
if let Some(confined_pointer) = self.confined_pointer.borrow_mut().take() {
|
||||
confined_pointer.destroy();
|
||||
}
|
||||
|
||||
// Drop the pointer itself in case it's possible.
|
||||
if self.pointer.as_ref().version() >= 3 {
|
||||
self.pointer.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn init_relative_pointer(
|
||||
relative_pointer_manager: &ZwpRelativePointerManagerV1,
|
||||
pointer: &WlPointer,
|
||||
) -> ZwpRelativePointerV1 {
|
||||
let relative_pointer = relative_pointer_manager.get_relative_pointer(&*pointer);
|
||||
relative_pointer.quick_assign(move |_, event, mut dispatch_data| {
|
||||
let winit_state = dispatch_data.get::<WinitState>().unwrap();
|
||||
handlers::handle_relative_pointer(event, winit_state);
|
||||
});
|
||||
|
||||
relative_pointer.detach()
|
||||
}
|
||||
|
||||
pub(super) fn init_confined_pointer(
|
||||
pointer_constraints: &Attached<ZwpPointerConstraintsV1>,
|
||||
surface: &WlSurface,
|
||||
pointer: &WlPointer,
|
||||
) -> ZwpConfinedPointerV1 {
|
||||
let confined_pointer =
|
||||
pointer_constraints.confine_pointer(surface, pointer, None, Lifetime::Persistent.to_raw());
|
||||
|
||||
confined_pointer.quick_assign(move |_, _, _| {});
|
||||
|
||||
confined_pointer.detach()
|
||||
}
|
||||
78
src/platform_impl/linux/wayland/seat/text_input/handlers.rs
Normal file
78
src/platform_impl/linux/wayland/seat/text_input/handlers.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
//! Handling of IME events.
|
||||
|
||||
use sctk::reexports::client::Main;
|
||||
use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_v3::{
|
||||
Event as TextInputEvent, ZwpTextInputV3,
|
||||
};
|
||||
|
||||
use crate::event::WindowEvent;
|
||||
use crate::platform_impl::wayland;
|
||||
use crate::platform_impl::wayland::event_loop::WinitState;
|
||||
|
||||
use super::{TextInputHandler, TextInputInner};
|
||||
|
||||
#[inline]
|
||||
pub(super) fn handle_text_input(
|
||||
text_input: Main<ZwpTextInputV3>,
|
||||
inner: &mut TextInputInner,
|
||||
event: TextInputEvent,
|
||||
winit_state: &mut WinitState,
|
||||
) {
|
||||
let event_sink = &mut winit_state.event_sink;
|
||||
match event {
|
||||
TextInputEvent::Enter { surface } => {
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
|
||||
let window_handle = match winit_state.window_map.get_mut(&window_id) {
|
||||
Some(window_handle) => window_handle,
|
||||
None => return,
|
||||
};
|
||||
inner.target_window_id = Some(window_id);
|
||||
|
||||
// Enable text input on that surface.
|
||||
text_input.enable();
|
||||
text_input.commit();
|
||||
|
||||
// Notify a window we're currently over about text input handler.
|
||||
let text_input_handler = TextInputHandler {
|
||||
text_input: text_input.detach(),
|
||||
};
|
||||
window_handle.text_input_entered(text_input_handler);
|
||||
}
|
||||
TextInputEvent::Leave { surface } => {
|
||||
// Always issue a disable.
|
||||
text_input.disable();
|
||||
text_input.commit();
|
||||
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
|
||||
let window_handle = match winit_state.window_map.get_mut(&window_id) {
|
||||
Some(window_handle) => window_handle,
|
||||
None => return,
|
||||
};
|
||||
|
||||
inner.target_window_id = None;
|
||||
|
||||
// Remove text input handler from the window we're leaving.
|
||||
let text_input_handler = TextInputHandler {
|
||||
text_input: text_input.detach(),
|
||||
};
|
||||
window_handle.text_input_left(text_input_handler);
|
||||
}
|
||||
TextInputEvent::CommitString { text } => {
|
||||
// Update currenly commited string.
|
||||
inner.commit_string = text;
|
||||
}
|
||||
TextInputEvent::Done { .. } => {
|
||||
let (window_id, text) = match (inner.target_window_id, inner.commit_string.take()) {
|
||||
(Some(window_id), Some(text)) => (window_id, text),
|
||||
_ => return,
|
||||
};
|
||||
|
||||
for ch in text.chars() {
|
||||
event_sink.push_window_event(WindowEvent::ReceivedCharacter(ch), window_id);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
66
src/platform_impl/linux/wayland/seat/text_input/mod.rs
Normal file
66
src/platform_impl/linux/wayland/seat/text_input/mod.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use sctk::reexports::client::protocol::wl_seat::WlSeat;
|
||||
use sctk::reexports::client::Attached;
|
||||
use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3;
|
||||
use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_v3::ZwpTextInputV3;
|
||||
|
||||
use crate::platform_impl::wayland::event_loop::WinitState;
|
||||
use crate::platform_impl::wayland::WindowId;
|
||||
|
||||
mod handlers;
|
||||
|
||||
/// A handler for text input that we're advertising for `WindowHandle`.
|
||||
#[derive(Eq, PartialEq)]
|
||||
pub struct TextInputHandler {
|
||||
text_input: ZwpTextInputV3,
|
||||
}
|
||||
|
||||
impl TextInputHandler {
|
||||
#[inline]
|
||||
pub fn set_ime_position(&self, x: i32, y: i32) {
|
||||
self.text_input.set_cursor_rectangle(x, y, 0, 0);
|
||||
self.text_input.commit();
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper around text input to automatically destroy the object on `Drop`.
|
||||
pub struct TextInput {
|
||||
text_input: Attached<ZwpTextInputV3>,
|
||||
}
|
||||
|
||||
impl TextInput {
|
||||
pub fn new(seat: &Attached<WlSeat>, text_input_manager: &ZwpTextInputManagerV3) -> Self {
|
||||
let text_input = text_input_manager.get_text_input(seat);
|
||||
let mut text_input_inner = TextInputInner::new();
|
||||
text_input.quick_assign(move |text_input, event, mut dispatch_data| {
|
||||
let winit_state = dispatch_data.get::<WinitState>().unwrap();
|
||||
handlers::handle_text_input(text_input, &mut text_input_inner, event, winit_state);
|
||||
});
|
||||
|
||||
let text_input: Attached<ZwpTextInputV3> = text_input.into();
|
||||
|
||||
Self { text_input }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TextInput {
|
||||
fn drop(&mut self) {
|
||||
self.text_input.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
struct TextInputInner {
|
||||
/// Currently focused surface.
|
||||
target_window_id: Option<WindowId>,
|
||||
|
||||
/// Pending string to commit.
|
||||
commit_string: Option<String>,
|
||||
}
|
||||
|
||||
impl TextInputInner {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
target_window_id: None,
|
||||
commit_string: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
122
src/platform_impl/linux/wayland/seat/touch/handlers.rs
Normal file
122
src/platform_impl/linux/wayland/seat/touch/handlers.rs
Normal file
@@ -0,0 +1,122 @@
|
||||
//! Various handlers for touch events.
|
||||
|
||||
use sctk::reexports::client::protocol::wl_touch::Event as TouchEvent;
|
||||
|
||||
use crate::dpi::LogicalPosition;
|
||||
use crate::event::{TouchPhase, WindowEvent};
|
||||
|
||||
use crate::platform_impl::wayland::event_loop::WinitState;
|
||||
use crate::platform_impl::wayland::{self, DeviceId};
|
||||
|
||||
use super::{TouchInner, TouchPoint};
|
||||
|
||||
/// Handle WlTouch events.
|
||||
#[inline]
|
||||
pub(super) fn handle_touch(
|
||||
event: TouchEvent,
|
||||
inner: &mut TouchInner,
|
||||
winit_state: &mut WinitState,
|
||||
) {
|
||||
let event_sink = &mut winit_state.event_sink;
|
||||
|
||||
match event {
|
||||
TouchEvent::Down {
|
||||
surface, id, x, y, ..
|
||||
} => {
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
if !winit_state.window_map.contains_key(&window_id) {
|
||||
return;
|
||||
}
|
||||
|
||||
let scale_factor = sctk::get_surface_scale_factor(&surface) as f64;
|
||||
let position = LogicalPosition::new(x, y);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::Touch(crate::event::Touch {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
phase: TouchPhase::Started,
|
||||
location: position.to_physical(scale_factor),
|
||||
force: None, // TODO
|
||||
id: id as u64,
|
||||
}),
|
||||
window_id,
|
||||
);
|
||||
|
||||
inner
|
||||
.touch_points
|
||||
.push(TouchPoint::new(surface, position, id));
|
||||
}
|
||||
TouchEvent::Up { id, .. } => {
|
||||
let touch_point = match inner.touch_points.iter().find(|p| p.id == id) {
|
||||
Some(touch_point) => touch_point,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let scale_factor = sctk::get_surface_scale_factor(&touch_point.surface) as f64;
|
||||
let location = touch_point.position.to_physical(scale_factor);
|
||||
let window_id = wayland::make_wid(&touch_point.surface);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::Touch(crate::event::Touch {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
phase: TouchPhase::Ended,
|
||||
location,
|
||||
force: None, // TODO
|
||||
id: id as u64,
|
||||
}),
|
||||
window_id,
|
||||
);
|
||||
}
|
||||
TouchEvent::Motion { id, x, y, .. } => {
|
||||
let touch_point = match inner.touch_points.iter_mut().find(|p| p.id == id) {
|
||||
Some(touch_point) => touch_point,
|
||||
None => return,
|
||||
};
|
||||
|
||||
touch_point.position = LogicalPosition::new(x, y);
|
||||
|
||||
let scale_factor = sctk::get_surface_scale_factor(&touch_point.surface) as f64;
|
||||
let location = touch_point.position.to_physical(scale_factor);
|
||||
let window_id = wayland::make_wid(&touch_point.surface);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::Touch(crate::event::Touch {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
phase: TouchPhase::Moved,
|
||||
location,
|
||||
force: None, // TODO
|
||||
id: id as u64,
|
||||
}),
|
||||
window_id,
|
||||
);
|
||||
}
|
||||
TouchEvent::Frame => (),
|
||||
TouchEvent::Cancel => {
|
||||
for touch_point in inner.touch_points.drain(..) {
|
||||
let scale_factor = sctk::get_surface_scale_factor(&touch_point.surface) as f64;
|
||||
let location = touch_point.position.to_physical(scale_factor);
|
||||
let window_id = wayland::make_wid(&touch_point.surface);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::Touch(crate::event::Touch {
|
||||
device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(
|
||||
DeviceId,
|
||||
)),
|
||||
phase: TouchPhase::Cancelled,
|
||||
location,
|
||||
force: None, // TODO
|
||||
id: touch_point.id as u64,
|
||||
}),
|
||||
window_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
78
src/platform_impl/linux/wayland/seat/touch/mod.rs
Normal file
78
src/platform_impl/linux/wayland/seat/touch/mod.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
//! Touch handling.
|
||||
|
||||
use sctk::reexports::client::protocol::wl_seat::WlSeat;
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use sctk::reexports::client::protocol::wl_touch::WlTouch;
|
||||
use sctk::reexports::client::Attached;
|
||||
|
||||
use crate::dpi::LogicalPosition;
|
||||
|
||||
use crate::platform_impl::wayland::event_loop::WinitState;
|
||||
|
||||
mod handlers;
|
||||
|
||||
/// Wrapper around touch to handle release.
|
||||
pub struct Touch {
|
||||
/// Proxy to touch.
|
||||
touch: WlTouch,
|
||||
}
|
||||
|
||||
impl Touch {
|
||||
pub fn new(seat: &Attached<WlSeat>) -> Self {
|
||||
let touch = seat.get_touch();
|
||||
let mut inner = TouchInner::new();
|
||||
|
||||
touch.quick_assign(move |_, event, mut dispatch_data| {
|
||||
let winit_state = dispatch_data.get::<WinitState>().unwrap();
|
||||
handlers::handle_touch(event, &mut inner, winit_state);
|
||||
});
|
||||
|
||||
Self {
|
||||
touch: touch.detach(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Touch {
|
||||
fn drop(&mut self) {
|
||||
if self.touch.as_ref().version() >= 3 {
|
||||
self.touch.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The data used by touch handlers.
|
||||
pub(super) struct TouchInner {
|
||||
/// Current touch points.
|
||||
touch_points: Vec<TouchPoint>,
|
||||
}
|
||||
|
||||
impl TouchInner {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
touch_points: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Location of touch press.
|
||||
pub(super) struct TouchPoint {
|
||||
/// A surface where the touch point is located.
|
||||
surface: WlSurface,
|
||||
|
||||
/// Location of the touch point.
|
||||
position: LogicalPosition<f64>,
|
||||
|
||||
/// Id.
|
||||
id: i32,
|
||||
}
|
||||
|
||||
impl TouchPoint {
|
||||
pub fn new(surface: WlSurface, position: LogicalPosition<f64>, id: i32) -> Self {
|
||||
Self {
|
||||
surface,
|
||||
position,
|
||||
id,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::event::{TouchPhase, WindowEvent};
|
||||
|
||||
use super::{event_loop::EventsSink, window::WindowStore, DeviceId, WindowId};
|
||||
|
||||
use smithay_client_toolkit::reexports::client::protocol::{
|
||||
wl_seat,
|
||||
wl_touch::{Event as TouchEvent, WlTouch},
|
||||
};
|
||||
|
||||
struct TouchPoint {
|
||||
wid: WindowId,
|
||||
location: (f64, f64),
|
||||
id: i32,
|
||||
}
|
||||
|
||||
pub(crate) fn implement_touch(
|
||||
seat: &wl_seat::WlSeat,
|
||||
sink: EventsSink,
|
||||
store: Arc<Mutex<WindowStore>>,
|
||||
) -> WlTouch {
|
||||
let mut pending_ids = Vec::new();
|
||||
seat.get_touch(|touch| {
|
||||
touch.implement_closure(
|
||||
move |evt, _| {
|
||||
let store = store.lock().unwrap();
|
||||
match evt {
|
||||
TouchEvent::Down {
|
||||
surface, id, x, y, ..
|
||||
} => {
|
||||
let wid = store.find_wid(&surface);
|
||||
if let Some(wid) = wid {
|
||||
sink.send_window_event(
|
||||
WindowEvent::Touch(crate::event::Touch {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
phase: TouchPhase::Started,
|
||||
location: (x, y).into(),
|
||||
force: None, // TODO
|
||||
id: id as u64,
|
||||
}),
|
||||
wid,
|
||||
);
|
||||
pending_ids.push(TouchPoint {
|
||||
wid,
|
||||
location: (x, y),
|
||||
id,
|
||||
});
|
||||
}
|
||||
}
|
||||
TouchEvent::Up { id, .. } => {
|
||||
let idx = pending_ids.iter().position(|p| p.id == id);
|
||||
if let Some(idx) = idx {
|
||||
let pt = pending_ids.remove(idx);
|
||||
sink.send_window_event(
|
||||
WindowEvent::Touch(crate::event::Touch {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
phase: TouchPhase::Ended,
|
||||
location: pt.location.into(),
|
||||
force: None, // TODO
|
||||
id: id as u64,
|
||||
}),
|
||||
pt.wid,
|
||||
);
|
||||
}
|
||||
}
|
||||
TouchEvent::Motion { id, x, y, .. } => {
|
||||
let pt = pending_ids.iter_mut().find(|p| p.id == id);
|
||||
if let Some(pt) = pt {
|
||||
pt.location = (x, y);
|
||||
sink.send_window_event(
|
||||
WindowEvent::Touch(crate::event::Touch {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
phase: TouchPhase::Moved,
|
||||
location: (x, y).into(),
|
||||
force: None, // TODO
|
||||
id: id as u64,
|
||||
}),
|
||||
pt.wid,
|
||||
);
|
||||
}
|
||||
}
|
||||
TouchEvent::Frame => (),
|
||||
TouchEvent::Cancel => {
|
||||
for pt in pending_ids.drain(..) {
|
||||
sink.send_window_event(
|
||||
WindowEvent::Touch(crate::event::Touch {
|
||||
device_id: crate::event::DeviceId(
|
||||
crate::platform_impl::DeviceId::Wayland(DeviceId),
|
||||
),
|
||||
phase: TouchPhase::Cancelled,
|
||||
location: pt.location.into(),
|
||||
force: None, // TODO
|
||||
id: pt.id as u64,
|
||||
}),
|
||||
pt.wid,
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
},
|
||||
(),
|
||||
)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
@@ -1,520 +0,0 @@
|
||||
use raw_window_handle::unix::WaylandHandle;
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
mem::replace,
|
||||
sync::{Arc, Mutex, Weak},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size},
|
||||
error::{ExternalError, NotSupportedError, OsError as RootOsError},
|
||||
monitor::MonitorHandle as RootMonitorHandle,
|
||||
platform_impl::{
|
||||
platform::wayland::event_loop::{available_monitors, primary_monitor},
|
||||
MonitorHandle as PlatformMonitorHandle,
|
||||
PlatformSpecificWindowBuilderAttributes as PlAttributes,
|
||||
},
|
||||
window::{CursorIcon, Fullscreen, WindowAttributes},
|
||||
};
|
||||
|
||||
use smithay_client_toolkit::{
|
||||
output::OutputMgr,
|
||||
reexports::client::{
|
||||
protocol::{wl_seat, wl_surface},
|
||||
Display,
|
||||
},
|
||||
surface::{get_dpi_factor, get_outputs},
|
||||
window::{ConceptFrame, Event as WEvent, State as WState, Theme, Window as SWindow},
|
||||
};
|
||||
|
||||
use super::{event_loop::CursorManager, make_wid, EventLoopWindowTarget, MonitorHandle, WindowId};
|
||||
|
||||
pub struct Window {
|
||||
surface: wl_surface::WlSurface,
|
||||
frame: Arc<Mutex<SWindow<ConceptFrame>>>,
|
||||
cursor_manager: Arc<Mutex<CursorManager>>,
|
||||
outputs: OutputMgr, // Access to info for all monitors
|
||||
size: Arc<Mutex<(u32, u32)>>,
|
||||
kill_switch: (Arc<Mutex<bool>>, Arc<Mutex<bool>>),
|
||||
display: Arc<Display>,
|
||||
need_frame_refresh: Arc<Mutex<bool>>,
|
||||
need_refresh: Arc<Mutex<bool>>,
|
||||
fullscreen: Arc<Mutex<bool>>,
|
||||
cursor_grab_changed: Arc<Mutex<Option<bool>>>, // Update grab state
|
||||
}
|
||||
|
||||
impl Window {
|
||||
pub fn new<T>(
|
||||
evlp: &EventLoopWindowTarget<T>,
|
||||
attributes: WindowAttributes,
|
||||
pl_attribs: PlAttributes,
|
||||
) -> Result<Window, RootOsError> {
|
||||
// Create the surface first to get initial DPI
|
||||
let window_store = evlp.store.clone();
|
||||
let cursor_manager = evlp.cursor_manager.clone();
|
||||
let surface = evlp.env.create_surface(move |dpi, surface| {
|
||||
window_store.lock().unwrap().dpi_change(&surface, dpi);
|
||||
surface.set_buffer_scale(dpi);
|
||||
});
|
||||
|
||||
let dpi = get_dpi_factor(&surface) as f64;
|
||||
let (width, height) = attributes
|
||||
.inner_size
|
||||
.map(|size| size.to_logical::<f64>(dpi).into())
|
||||
.unwrap_or((800, 600));
|
||||
|
||||
// Create the window
|
||||
let size = Arc::new(Mutex::new((width, height)));
|
||||
let fullscreen = Arc::new(Mutex::new(false));
|
||||
|
||||
let window_store = evlp.store.clone();
|
||||
|
||||
let my_surface = surface.clone();
|
||||
let mut frame = SWindow::<ConceptFrame>::init_from_env(
|
||||
&evlp.env,
|
||||
surface.clone(),
|
||||
(width, height),
|
||||
move |event| match event {
|
||||
WEvent::Configure { new_size, states } => {
|
||||
let mut store = window_store.lock().unwrap();
|
||||
let is_fullscreen = states.contains(&WState::Fullscreen);
|
||||
|
||||
for window in &mut store.windows {
|
||||
if window.surface.as_ref().equals(&my_surface.as_ref()) {
|
||||
window.newsize = new_size;
|
||||
*(window.need_refresh.lock().unwrap()) = true;
|
||||
*(window.fullscreen.lock().unwrap()) = is_fullscreen;
|
||||
*(window.need_frame_refresh.lock().unwrap()) = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
WEvent::Refresh => {
|
||||
let store = window_store.lock().unwrap();
|
||||
for window in &store.windows {
|
||||
if window.surface.as_ref().equals(&my_surface.as_ref()) {
|
||||
*(window.need_frame_refresh.lock().unwrap()) = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
WEvent::Close => {
|
||||
let mut store = window_store.lock().unwrap();
|
||||
for window in &mut store.windows {
|
||||
if window.surface.as_ref().equals(&my_surface.as_ref()) {
|
||||
window.closed = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
if let Some(app_id) = pl_attribs.app_id {
|
||||
frame.set_app_id(app_id);
|
||||
}
|
||||
|
||||
for &(_, ref seat) in evlp.seats.lock().unwrap().iter() {
|
||||
frame.new_seat(seat);
|
||||
}
|
||||
|
||||
// Check for fullscreen requirements
|
||||
match attributes.fullscreen {
|
||||
Some(Fullscreen::Exclusive(_)) => {
|
||||
panic!("Wayland doesn't support exclusive fullscreen")
|
||||
}
|
||||
Some(Fullscreen::Borderless(RootMonitorHandle {
|
||||
inner: PlatformMonitorHandle::Wayland(ref monitor_id),
|
||||
})) => frame.set_fullscreen(Some(&monitor_id.proxy)),
|
||||
Some(Fullscreen::Borderless(_)) => unreachable!(),
|
||||
None => {
|
||||
if attributes.maximized {
|
||||
frame.set_maximized();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
frame.set_resizable(attributes.resizable);
|
||||
|
||||
// set decorations
|
||||
frame.set_decorate(attributes.decorations);
|
||||
|
||||
// set title
|
||||
frame.set_title(attributes.title);
|
||||
|
||||
// min-max dimensions
|
||||
frame.set_min_size(
|
||||
attributes
|
||||
.min_inner_size
|
||||
.map(|size| size.to_logical::<f64>(dpi).into()),
|
||||
);
|
||||
frame.set_max_size(
|
||||
attributes
|
||||
.max_inner_size
|
||||
.map(|size| size.to_logical::<f64>(dpi).into()),
|
||||
);
|
||||
|
||||
let kill_switch = Arc::new(Mutex::new(false));
|
||||
let need_frame_refresh = Arc::new(Mutex::new(true));
|
||||
let frame = Arc::new(Mutex::new(frame));
|
||||
let need_refresh = Arc::new(Mutex::new(true));
|
||||
let cursor_grab_changed = Arc::new(Mutex::new(None));
|
||||
|
||||
evlp.store.lock().unwrap().windows.push(InternalWindow {
|
||||
closed: false,
|
||||
newsize: None,
|
||||
size: size.clone(),
|
||||
need_refresh: need_refresh.clone(),
|
||||
fullscreen: fullscreen.clone(),
|
||||
cursor_grab_changed: cursor_grab_changed.clone(),
|
||||
need_frame_refresh: need_frame_refresh.clone(),
|
||||
surface: surface.clone(),
|
||||
kill_switch: kill_switch.clone(),
|
||||
frame: Arc::downgrade(&frame),
|
||||
current_dpi: 1,
|
||||
new_dpi: None,
|
||||
});
|
||||
evlp.evq.borrow_mut().sync_roundtrip().unwrap();
|
||||
|
||||
Ok(Window {
|
||||
display: evlp.display.clone(),
|
||||
surface,
|
||||
frame,
|
||||
outputs: evlp.env.outputs.clone(),
|
||||
size,
|
||||
kill_switch: (kill_switch, evlp.cleanup_needed.clone()),
|
||||
need_frame_refresh,
|
||||
need_refresh,
|
||||
cursor_manager,
|
||||
fullscreen,
|
||||
cursor_grab_changed,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn id(&self) -> WindowId {
|
||||
make_wid(&self.surface)
|
||||
}
|
||||
|
||||
pub fn set_title(&self, title: &str) {
|
||||
self.frame.lock().unwrap().set_title(title.into());
|
||||
}
|
||||
|
||||
pub fn set_visible(&self, _visible: bool) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
Err(NotSupportedError::new())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
Err(NotSupportedError::new())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_outer_position(&self, _pos: Position) {
|
||||
// Not possible with wayland
|
||||
}
|
||||
|
||||
pub fn inner_size(&self) -> PhysicalSize<u32> {
|
||||
let dpi = self.scale_factor() as f64;
|
||||
let size = LogicalSize::<f64>::from(*self.size.lock().unwrap());
|
||||
size.to_physical(dpi)
|
||||
}
|
||||
|
||||
pub fn request_redraw(&self) {
|
||||
*self.need_refresh.lock().unwrap() = true;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn outer_size(&self) -> PhysicalSize<u32> {
|
||||
let dpi = self.scale_factor() as f64;
|
||||
let (w, h) = self.size.lock().unwrap().clone();
|
||||
// let (w, h) = super::wayland_window::add_borders(w as i32, h as i32);
|
||||
let size = LogicalSize::<f64>::from((w, h));
|
||||
size.to_physical(dpi)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
// NOTE: This will only resize the borders, the contents must be updated by the user
|
||||
pub fn set_inner_size(&self, size: Size) {
|
||||
let dpi = self.scale_factor() as f64;
|
||||
let (w, h) = size.to_logical::<u32>(dpi).into();
|
||||
self.frame.lock().unwrap().resize(w, h);
|
||||
*(self.size.lock().unwrap()) = (w, h);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_min_inner_size(&self, dimensions: Option<Size>) {
|
||||
let dpi = self.scale_factor() as f64;
|
||||
self.frame
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_min_size(dimensions.map(|dim| dim.to_logical::<f64>(dpi).into()));
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_max_inner_size(&self, dimensions: Option<Size>) {
|
||||
let dpi = self.scale_factor() as f64;
|
||||
self.frame
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_max_size(dimensions.map(|dim| dim.to_logical::<f64>(dpi).into()));
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_resizable(&self, resizable: bool) {
|
||||
self.frame.lock().unwrap().set_resizable(resizable);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn scale_factor(&self) -> i32 {
|
||||
get_dpi_factor(&self.surface)
|
||||
}
|
||||
|
||||
pub fn set_decorations(&self, decorate: bool) {
|
||||
self.frame.lock().unwrap().set_decorate(decorate);
|
||||
*(self.need_frame_refresh.lock().unwrap()) = true;
|
||||
}
|
||||
|
||||
pub fn set_minimized(&self, minimized: bool) {
|
||||
// An app cannot un-minimize itself on Wayland
|
||||
if minimized {
|
||||
self.frame.lock().unwrap().set_minimized();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_maximized(&self, maximized: bool) {
|
||||
if maximized {
|
||||
self.frame.lock().unwrap().set_maximized();
|
||||
} else {
|
||||
self.frame.lock().unwrap().unset_maximized();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fullscreen(&self) -> Option<Fullscreen> {
|
||||
if *(self.fullscreen.lock().unwrap()) {
|
||||
Some(Fullscreen::Borderless(RootMonitorHandle {
|
||||
inner: PlatformMonitorHandle::Wayland(self.current_monitor()),
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
|
||||
match fullscreen {
|
||||
Some(Fullscreen::Exclusive(_)) => {
|
||||
panic!("Wayland doesn't support exclusive fullscreen")
|
||||
}
|
||||
Some(Fullscreen::Borderless(RootMonitorHandle {
|
||||
inner: PlatformMonitorHandle::Wayland(ref monitor_id),
|
||||
})) => {
|
||||
self.frame
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_fullscreen(Some(&monitor_id.proxy));
|
||||
}
|
||||
Some(Fullscreen::Borderless(_)) => unreachable!(),
|
||||
None => self.frame.lock().unwrap().unset_fullscreen(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_theme<T: Theme>(&self, theme: T) {
|
||||
self.frame.lock().unwrap().set_theme(theme)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_icon(&self, cursor: CursorIcon) {
|
||||
let mut cursor_manager = self.cursor_manager.lock().unwrap();
|
||||
cursor_manager.set_cursor_icon(cursor);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_visible(&self, visible: bool) {
|
||||
let mut cursor_manager = self.cursor_manager.lock().unwrap();
|
||||
cursor_manager.set_cursor_visible(visible);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_grab(&self, grab: bool) -> Result<(), ExternalError> {
|
||||
*self.cursor_grab_changed.lock().unwrap() = Some(grab);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_position(&self, _pos: Position) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
pub fn display(&self) -> &Display {
|
||||
&*self.display
|
||||
}
|
||||
|
||||
pub fn surface(&self) -> &wl_surface::WlSurface {
|
||||
&self.surface
|
||||
}
|
||||
|
||||
pub fn current_monitor(&self) -> MonitorHandle {
|
||||
let output = get_outputs(&self.surface).last().unwrap().clone();
|
||||
MonitorHandle {
|
||||
proxy: output,
|
||||
mgr: self.outputs.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
available_monitors(&self.outputs)
|
||||
}
|
||||
|
||||
pub fn primary_monitor(&self) -> MonitorHandle {
|
||||
primary_monitor(&self.outputs)
|
||||
}
|
||||
|
||||
pub fn raw_window_handle(&self) -> WaylandHandle {
|
||||
WaylandHandle {
|
||||
surface: self.surface().as_ref().c_ptr() as *mut _,
|
||||
display: self.display().as_ref().c_ptr() as *mut _,
|
||||
..WaylandHandle::empty()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Window {
|
||||
fn drop(&mut self) {
|
||||
*(self.kill_switch.0.lock().unwrap()) = true;
|
||||
*(self.kill_switch.1.lock().unwrap()) = true;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Internal store for windows
|
||||
*/
|
||||
|
||||
struct InternalWindow {
|
||||
surface: wl_surface::WlSurface,
|
||||
// TODO: CONVERT TO LogicalSize<u32>s
|
||||
newsize: Option<(u32, u32)>,
|
||||
size: Arc<Mutex<(u32, u32)>>,
|
||||
need_refresh: Arc<Mutex<bool>>,
|
||||
fullscreen: Arc<Mutex<bool>>,
|
||||
need_frame_refresh: Arc<Mutex<bool>>,
|
||||
cursor_grab_changed: Arc<Mutex<Option<bool>>>,
|
||||
closed: bool,
|
||||
kill_switch: Arc<Mutex<bool>>,
|
||||
frame: Weak<Mutex<SWindow<ConceptFrame>>>,
|
||||
current_dpi: i32,
|
||||
new_dpi: Option<i32>,
|
||||
}
|
||||
|
||||
pub struct WindowStore {
|
||||
windows: Vec<InternalWindow>,
|
||||
}
|
||||
|
||||
pub struct WindowStoreForEach<'a> {
|
||||
pub newsize: Option<(u32, u32)>,
|
||||
pub size: &'a mut (u32, u32),
|
||||
pub prev_dpi: i32,
|
||||
pub new_dpi: Option<i32>,
|
||||
pub closed: bool,
|
||||
pub grab_cursor: Option<bool>,
|
||||
pub surface: &'a wl_surface::WlSurface,
|
||||
pub wid: WindowId,
|
||||
pub frame: Option<&'a mut SWindow<ConceptFrame>>,
|
||||
}
|
||||
|
||||
impl WindowStore {
|
||||
pub fn new() -> WindowStore {
|
||||
WindowStore {
|
||||
windows: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_wid(&self, surface: &wl_surface::WlSurface) -> Option<WindowId> {
|
||||
for window in &self.windows {
|
||||
if surface.as_ref().equals(&window.surface.as_ref()) {
|
||||
return Some(make_wid(surface));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn cleanup(&mut self) -> Vec<WindowId> {
|
||||
let mut pruned = Vec::new();
|
||||
self.windows.retain(|w| {
|
||||
if *w.kill_switch.lock().unwrap() {
|
||||
// window is dead, cleanup
|
||||
pruned.push(make_wid(&w.surface));
|
||||
w.surface.destroy();
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
pruned
|
||||
}
|
||||
|
||||
pub fn new_seat(&self, seat: &wl_seat::WlSeat) {
|
||||
for window in &self.windows {
|
||||
if let Some(w) = window.frame.upgrade() {
|
||||
w.lock().unwrap().new_seat(seat);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dpi_change(&mut self, surface: &wl_surface::WlSurface, new: i32) {
|
||||
for window in &mut self.windows {
|
||||
if surface.as_ref().equals(&window.surface.as_ref()) {
|
||||
window.new_dpi = Some(new);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn for_each<F>(&mut self, mut f: F)
|
||||
where
|
||||
F: FnMut(WindowStoreForEach<'_>),
|
||||
{
|
||||
for window in &mut self.windows {
|
||||
let opt_arc = window.frame.upgrade();
|
||||
let mut opt_mutex_lock = opt_arc.as_ref().map(|m| m.lock().unwrap());
|
||||
let mut size = { *window.size.lock().unwrap() };
|
||||
f(WindowStoreForEach {
|
||||
newsize: window.newsize.take(),
|
||||
size: &mut size,
|
||||
prev_dpi: window.current_dpi,
|
||||
new_dpi: window.new_dpi,
|
||||
closed: window.closed,
|
||||
grab_cursor: window.cursor_grab_changed.lock().unwrap().take(),
|
||||
surface: &window.surface,
|
||||
wid: make_wid(&window.surface),
|
||||
frame: opt_mutex_lock.as_mut().map(|m| &mut **m),
|
||||
});
|
||||
*window.size.lock().unwrap() = size;
|
||||
if let Some(dpi) = window.new_dpi.take() {
|
||||
window.current_dpi = dpi;
|
||||
}
|
||||
// avoid re-spamming the event
|
||||
window.closed = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn for_each_redraw_trigger<F>(&mut self, mut f: F)
|
||||
where
|
||||
F: FnMut(bool, bool, WindowId, Option<&mut SWindow<ConceptFrame>>),
|
||||
{
|
||||
for window in &mut self.windows {
|
||||
let opt_arc = window.frame.upgrade();
|
||||
let mut opt_mutex_lock = opt_arc.as_ref().map(|m| m.lock().unwrap());
|
||||
f(
|
||||
replace(&mut *window.need_refresh.lock().unwrap(), false),
|
||||
replace(&mut *window.need_frame_refresh.lock().unwrap(), false),
|
||||
make_wid(&window.surface),
|
||||
opt_mutex_lock.as_mut().map(|m| &mut **m),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
656
src/platform_impl/linux/wayland/window/mod.rs
Normal file
656
src/platform_impl/linux/wayland/window/mod.rs
Normal file
@@ -0,0 +1,656 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use sctk::reexports::client::Display;
|
||||
|
||||
use sctk::reexports::calloop;
|
||||
|
||||
use sctk::window::{
|
||||
ARGBColor, ButtonColorSpec, ColorSpec, ConceptConfig, ConceptFrame, Decorations,
|
||||
};
|
||||
|
||||
use raw_window_handle::unix::WaylandHandle;
|
||||
|
||||
use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size};
|
||||
use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError};
|
||||
use crate::monitor::MonitorHandle as RootMonitorHandle;
|
||||
use crate::platform::unix::{ARGBColor as LocalARGBColor, Button, ButtonState, Element, Theme};
|
||||
use crate::platform_impl::{
|
||||
MonitorHandle as PlatformMonitorHandle, OsError,
|
||||
PlatformSpecificWindowBuilderAttributes as PlatformAttributes,
|
||||
};
|
||||
use crate::window::{CursorIcon, Fullscreen, WindowAttributes};
|
||||
|
||||
use super::env::WindowingFeatures;
|
||||
use super::event_loop::WinitState;
|
||||
use super::output::{MonitorHandle, OutputManagerHandle};
|
||||
use super::{EventLoopWindowTarget, WindowId};
|
||||
|
||||
pub mod shim;
|
||||
|
||||
use shim::{WindowHandle, WindowRequest, WindowUpdate};
|
||||
|
||||
pub struct Window {
|
||||
/// Window id.
|
||||
window_id: WindowId,
|
||||
|
||||
/// The Wayland display.
|
||||
display: Display,
|
||||
|
||||
/// The underlying wl_surface.
|
||||
surface: WlSurface,
|
||||
|
||||
/// The current window size.
|
||||
size: Arc<Mutex<LogicalSize<u32>>>,
|
||||
|
||||
/// A handle to output manager.
|
||||
output_manager_handle: OutputManagerHandle,
|
||||
|
||||
/// Event loop proxy to wake it up.
|
||||
event_loop_awakener: calloop::ping::Ping,
|
||||
|
||||
/// Fullscreen state.
|
||||
fullscreen: Arc<AtomicBool>,
|
||||
|
||||
/// Available windowing features.
|
||||
windowing_features: WindowingFeatures,
|
||||
|
||||
/// Requests that SCTK window should perform.
|
||||
window_requests: Arc<Mutex<Vec<WindowRequest>>>,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
pub fn new<T>(
|
||||
event_loop_window_target: &EventLoopWindowTarget<T>,
|
||||
attributes: WindowAttributes,
|
||||
platform_attributes: PlatformAttributes,
|
||||
) -> Result<Self, RootOsError> {
|
||||
let surface = event_loop_window_target
|
||||
.env
|
||||
.create_surface_with_scale_callback(move |scale, surface, mut dispatch_data| {
|
||||
let winit_state = dispatch_data.get::<WinitState>().unwrap();
|
||||
|
||||
// Get the window that receiced the event.
|
||||
let window_id = super::make_wid(&surface);
|
||||
let mut window_update = winit_state.window_updates.get_mut(&window_id).unwrap();
|
||||
|
||||
// Set pending scale factor.
|
||||
window_update.scale_factor = Some(scale);
|
||||
window_update.redraw_requested = true;
|
||||
|
||||
surface.set_buffer_scale(scale);
|
||||
})
|
||||
.detach();
|
||||
|
||||
let scale_factor = sctk::get_surface_scale_factor(&surface);
|
||||
|
||||
let window_id = super::make_wid(&surface);
|
||||
let fullscreen = Arc::new(AtomicBool::new(false));
|
||||
let fullscreen_clone = fullscreen.clone();
|
||||
|
||||
let (width, height) = attributes
|
||||
.inner_size
|
||||
.map(|size| size.to_logical::<f64>(scale_factor as f64).into())
|
||||
.unwrap_or((800, 600));
|
||||
|
||||
let theme_manager = event_loop_window_target.theme_manager.clone();
|
||||
let mut window = event_loop_window_target
|
||||
.env
|
||||
.create_window::<ConceptFrame, _>(
|
||||
surface.clone(),
|
||||
Some(theme_manager),
|
||||
(width, height),
|
||||
move |event, mut dispatch_data| {
|
||||
use sctk::window::{Event, State};
|
||||
|
||||
let winit_state = dispatch_data.get::<WinitState>().unwrap();
|
||||
let mut window_update = winit_state.window_updates.get_mut(&window_id).unwrap();
|
||||
|
||||
match event {
|
||||
Event::Refresh => {
|
||||
window_update.refresh_frame = true;
|
||||
}
|
||||
Event::Configure { new_size, states } => {
|
||||
let is_fullscreen = states.contains(&State::Fullscreen);
|
||||
fullscreen_clone.store(is_fullscreen, Ordering::Relaxed);
|
||||
|
||||
window_update.refresh_frame = true;
|
||||
window_update.redraw_requested = true;
|
||||
if let Some((w, h)) = new_size {
|
||||
window_update.size = Some(LogicalSize::new(w, h));
|
||||
}
|
||||
}
|
||||
Event::Close => {
|
||||
window_update.close_window = true;
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.map_err(|_| os_error!(OsError::WaylandMisc("failed to create window.")))?;
|
||||
|
||||
// Set decorations.
|
||||
if attributes.decorations {
|
||||
window.set_decorate(Decorations::FollowServer);
|
||||
} else {
|
||||
window.set_decorate(Decorations::None);
|
||||
}
|
||||
|
||||
// Min dimensions.
|
||||
let min_size = attributes
|
||||
.min_inner_size
|
||||
.map(|size| size.to_logical::<f64>(scale_factor as f64).into());
|
||||
window.set_min_size(min_size);
|
||||
|
||||
// Max dimensions.
|
||||
let max_size = attributes
|
||||
.min_inner_size
|
||||
.map(|size| size.to_logical::<f64>(scale_factor as f64).into());
|
||||
window.set_max_size(max_size);
|
||||
|
||||
// Set Wayland specific window attributes.
|
||||
if let Some(app_id) = platform_attributes.app_id {
|
||||
window.set_app_id(app_id);
|
||||
}
|
||||
|
||||
// Set common window attributes.
|
||||
//
|
||||
// We set resizable after other attributes, since it touches min and max size under
|
||||
// the hood.
|
||||
window.set_resizable(attributes.resizable);
|
||||
window.set_title(attributes.title);
|
||||
|
||||
// Set fullscreen/maximized if so was requested.
|
||||
match attributes.fullscreen {
|
||||
Some(Fullscreen::Exclusive(_)) => {
|
||||
warn!("`Fullscreen::Exclusive` is ignored on Wayland")
|
||||
}
|
||||
Some(Fullscreen::Borderless(monitor)) => {
|
||||
let monitor =
|
||||
monitor.and_then(|RootMonitorHandle { inner: monitor }| match monitor {
|
||||
PlatformMonitorHandle::Wayland(monitor) => Some(monitor.proxy),
|
||||
#[cfg(feature = "x11")]
|
||||
PlatformMonitorHandle::X(_) => None,
|
||||
});
|
||||
|
||||
window.set_fullscreen(monitor.as_ref());
|
||||
}
|
||||
None => {
|
||||
if attributes.maximized {
|
||||
window.set_maximized();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let size = Arc::new(Mutex::new(LogicalSize::new(width, height)));
|
||||
|
||||
// We should trigger redraw and commit the surface for the newly created window.
|
||||
let mut window_update = WindowUpdate::new();
|
||||
window_update.refresh_frame = true;
|
||||
window_update.redraw_requested = true;
|
||||
|
||||
let window_id = super::make_wid(&surface);
|
||||
let window_requests = Arc::new(Mutex::new(Vec::with_capacity(64)));
|
||||
|
||||
// Create a handle that performs all the requests on underlying sctk a window.
|
||||
let window_handle = WindowHandle::new(window, size.clone(), window_requests.clone());
|
||||
|
||||
let mut winit_state = event_loop_window_target.state.borrow_mut();
|
||||
|
||||
winit_state.window_map.insert(window_id, window_handle);
|
||||
|
||||
winit_state
|
||||
.window_updates
|
||||
.insert(window_id, WindowUpdate::new());
|
||||
|
||||
let windowing_features = event_loop_window_target.windowing_features;
|
||||
|
||||
// Send all updates to the server.
|
||||
let wayland_source = &event_loop_window_target.wayland_source;
|
||||
let event_loop_handle = &event_loop_window_target.event_loop_handle;
|
||||
|
||||
// To make our window usable for drawing right away we must `ack` a `configure`
|
||||
// from the server, the acking part here is done by SCTK window frame, so we just
|
||||
// need to sync with server so it'll be done automatically for us.
|
||||
event_loop_handle.with_source(&wayland_source, |event_queue| {
|
||||
let event_queue = event_queue.queue();
|
||||
let _ = event_queue.sync_roundtrip(&mut *winit_state, |_, _, _| unreachable!());
|
||||
});
|
||||
|
||||
// We all praise GNOME for these 3 lines of pure magic. If we don't do that,
|
||||
// GNOME will shrink our window a bit for the size of the decorations. I guess it
|
||||
// happens because we haven't committed them with buffers to the server.
|
||||
let window_handle = winit_state.window_map.get_mut(&window_id).unwrap();
|
||||
window_handle.window.refresh();
|
||||
|
||||
let output_manager_handle = event_loop_window_target.output_manager.handle();
|
||||
|
||||
let window = Self {
|
||||
window_id,
|
||||
surface,
|
||||
display: event_loop_window_target.display.clone(),
|
||||
output_manager_handle,
|
||||
size,
|
||||
window_requests,
|
||||
event_loop_awakener: event_loop_window_target.event_loop_awakener.clone(),
|
||||
fullscreen,
|
||||
windowing_features,
|
||||
};
|
||||
|
||||
Ok(window)
|
||||
}
|
||||
}
|
||||
|
||||
impl Window {
|
||||
#[inline]
|
||||
pub fn id(&self) -> WindowId {
|
||||
self.window_id
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_title(&self, title: &str) {
|
||||
let title_request = WindowRequest::Title(title.to_owned());
|
||||
self.window_requests.lock().unwrap().push(title_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_visible(&self, _visible: bool) {
|
||||
// Not possible on Wayland.
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
Err(NotSupportedError::new())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
Err(NotSupportedError::new())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_outer_position(&self, _: Position) {
|
||||
// Not possible on Wayland.
|
||||
}
|
||||
|
||||
pub fn inner_size(&self) -> PhysicalSize<u32> {
|
||||
self.size
|
||||
.lock()
|
||||
.unwrap()
|
||||
.to_physical(self.scale_factor() as f64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn request_redraw(&self) {
|
||||
let redraw_request = WindowRequest::Redraw;
|
||||
self.window_requests.lock().unwrap().push(redraw_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn outer_size(&self) -> PhysicalSize<u32> {
|
||||
self.size
|
||||
.lock()
|
||||
.unwrap()
|
||||
.to_physical(self.scale_factor() as f64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_inner_size(&self, size: Size) {
|
||||
let scale_factor = self.scale_factor() as f64;
|
||||
|
||||
let size = size.to_logical::<u32>(scale_factor);
|
||||
*self.size.lock().unwrap() = size;
|
||||
|
||||
let frame_size_request = WindowRequest::FrameSize(size);
|
||||
self.window_requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(frame_size_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_min_inner_size(&self, dimensions: Option<Size>) {
|
||||
let scale_factor = self.scale_factor() as f64;
|
||||
let size = dimensions.map(|size| size.to_logical::<u32>(scale_factor));
|
||||
|
||||
let min_size_request = WindowRequest::MinSize(size);
|
||||
self.window_requests.lock().unwrap().push(min_size_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_max_inner_size(&self, dimensions: Option<Size>) {
|
||||
let scale_factor = self.scale_factor() as f64;
|
||||
let size = dimensions.map(|size| size.to_logical::<u32>(scale_factor));
|
||||
|
||||
let max_size_request = WindowRequest::MaxSize(size);
|
||||
self.window_requests.lock().unwrap().push(max_size_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_resizable(&self, resizable: bool) {
|
||||
let resizeable_request = WindowRequest::Resizeable(resizable);
|
||||
self.window_requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(resizeable_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn scale_factor(&self) -> u32 {
|
||||
// The scale factor from `get_surface_scale_factor` is always greater than zero, so
|
||||
// u32 conversion is safe.
|
||||
sctk::get_surface_scale_factor(&self.surface) as u32
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_decorations(&self, decorate: bool) {
|
||||
let decorate_request = WindowRequest::Decorate(decorate);
|
||||
self.window_requests.lock().unwrap().push(decorate_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_minimized(&self, minimized: bool) {
|
||||
// You can't unminimize the window on Wayland.
|
||||
if !minimized {
|
||||
return;
|
||||
}
|
||||
|
||||
let minimize_request = WindowRequest::Minimize;
|
||||
self.window_requests.lock().unwrap().push(minimize_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_maximized(&self, maximized: bool) {
|
||||
let maximize_request = WindowRequest::Maximize(maximized);
|
||||
self.window_requests.lock().unwrap().push(maximize_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn fullscreen(&self) -> Option<Fullscreen> {
|
||||
if self.fullscreen.load(Ordering::Relaxed) {
|
||||
let current_monitor = self.current_monitor().map(|monitor| RootMonitorHandle {
|
||||
inner: PlatformMonitorHandle::Wayland(monitor),
|
||||
});
|
||||
|
||||
Some(Fullscreen::Borderless(current_monitor))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
|
||||
let fullscreen_request = match fullscreen {
|
||||
Some(Fullscreen::Exclusive(_)) => {
|
||||
warn!("`Fullscreen::Exclusive` is ignored on Wayland");
|
||||
return;
|
||||
}
|
||||
Some(Fullscreen::Borderless(monitor)) => {
|
||||
let monitor =
|
||||
monitor.and_then(|RootMonitorHandle { inner: monitor }| match monitor {
|
||||
PlatformMonitorHandle::Wayland(monitor) => Some(monitor.proxy),
|
||||
#[cfg(feature = "x11")]
|
||||
PlatformMonitorHandle::X(_) => None,
|
||||
});
|
||||
|
||||
WindowRequest::Fullscreen(monitor)
|
||||
}
|
||||
None => WindowRequest::UnsetFullscreen,
|
||||
};
|
||||
|
||||
self.window_requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(fullscreen_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_theme<T: Theme>(&self, theme: T) {
|
||||
// First buttons is minimize, then maximize, and then close.
|
||||
let buttons: Vec<(ButtonColorSpec, ButtonColorSpec)> =
|
||||
[Button::Minimize, Button::Maximize, Button::Close]
|
||||
.iter()
|
||||
.map(|button| {
|
||||
let button = *button;
|
||||
let idle_active_bg = theme
|
||||
.button_color(button, ButtonState::Idle, false, true)
|
||||
.into();
|
||||
let idle_inactive_bg = theme
|
||||
.button_color(button, ButtonState::Idle, false, false)
|
||||
.into();
|
||||
let idle_active_icon = theme
|
||||
.button_color(button, ButtonState::Idle, true, true)
|
||||
.into();
|
||||
let idle_inactive_icon = theme
|
||||
.button_color(button, ButtonState::Idle, true, false)
|
||||
.into();
|
||||
let idle_bg = ColorSpec {
|
||||
active: idle_active_bg,
|
||||
inactive: idle_inactive_bg,
|
||||
};
|
||||
let idle_icon = ColorSpec {
|
||||
active: idle_active_icon,
|
||||
inactive: idle_inactive_icon,
|
||||
};
|
||||
|
||||
let hovered_active_bg = theme
|
||||
.button_color(button, ButtonState::Hovered, false, true)
|
||||
.into();
|
||||
let hovered_inactive_bg = theme
|
||||
.button_color(button, ButtonState::Hovered, false, false)
|
||||
.into();
|
||||
let hovered_active_icon = theme
|
||||
.button_color(button, ButtonState::Hovered, true, true)
|
||||
.into();
|
||||
let hovered_inactive_icon = theme
|
||||
.button_color(button, ButtonState::Hovered, true, false)
|
||||
.into();
|
||||
let hovered_bg = ColorSpec {
|
||||
active: hovered_active_bg,
|
||||
inactive: hovered_inactive_bg,
|
||||
};
|
||||
let hovered_icon = ColorSpec {
|
||||
active: hovered_active_icon,
|
||||
inactive: hovered_inactive_icon,
|
||||
};
|
||||
|
||||
let disabled_active_bg = theme
|
||||
.button_color(button, ButtonState::Disabled, false, true)
|
||||
.into();
|
||||
let disabled_inactive_bg = theme
|
||||
.button_color(button, ButtonState::Disabled, false, false)
|
||||
.into();
|
||||
let disabled_active_icon = theme
|
||||
.button_color(button, ButtonState::Disabled, true, true)
|
||||
.into();
|
||||
let disabled_inactive_icon = theme
|
||||
.button_color(button, ButtonState::Disabled, true, false)
|
||||
.into();
|
||||
let disabled_bg = ColorSpec {
|
||||
active: disabled_active_bg,
|
||||
inactive: disabled_inactive_bg,
|
||||
};
|
||||
let disabled_icon = ColorSpec {
|
||||
active: disabled_active_icon,
|
||||
inactive: disabled_inactive_icon,
|
||||
};
|
||||
|
||||
let button_bg = ButtonColorSpec {
|
||||
idle: idle_bg,
|
||||
hovered: hovered_bg,
|
||||
disabled: disabled_bg,
|
||||
};
|
||||
let button_icon = ButtonColorSpec {
|
||||
idle: idle_icon,
|
||||
hovered: hovered_icon,
|
||||
disabled: disabled_icon,
|
||||
};
|
||||
|
||||
(button_icon, button_bg)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let minimize_button = Some(buttons[0]);
|
||||
let maximize_button = Some(buttons[1]);
|
||||
let close_button = Some(buttons[2]);
|
||||
|
||||
// The first color is bar, then separator, and then text color.
|
||||
let titlebar_colors: Vec<ColorSpec> = [Element::Bar, Element::Separator, Element::Text]
|
||||
.iter()
|
||||
.map(|element| {
|
||||
let element = *element;
|
||||
let active = theme.element_color(element, true).into();
|
||||
let inactive = theme.element_color(element, false).into();
|
||||
|
||||
ColorSpec { active, inactive }
|
||||
})
|
||||
.collect();
|
||||
|
||||
let primary_color = titlebar_colors[0];
|
||||
let secondary_color = titlebar_colors[1];
|
||||
let title_color = titlebar_colors[2];
|
||||
|
||||
let title_font = theme.font();
|
||||
|
||||
let concept_config = ConceptConfig {
|
||||
primary_color,
|
||||
secondary_color,
|
||||
title_color,
|
||||
title_font,
|
||||
minimize_button,
|
||||
maximize_button,
|
||||
close_button,
|
||||
};
|
||||
|
||||
let theme_request = WindowRequest::Theme(concept_config);
|
||||
self.window_requests.lock().unwrap().push(theme_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_icon(&self, cursor: CursorIcon) {
|
||||
let cursor_icon_request = WindowRequest::NewCursorIcon(cursor);
|
||||
self.window_requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(cursor_icon_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_visible(&self, visible: bool) {
|
||||
let cursor_visible_request = WindowRequest::ShowCursor(visible);
|
||||
self.window_requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(cursor_visible_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_grab(&self, grab: bool) -> Result<(), ExternalError> {
|
||||
if !self.windowing_features.cursor_grab() {
|
||||
return Err(ExternalError::NotSupported(NotSupportedError::new()));
|
||||
}
|
||||
|
||||
let cursor_grab_request = WindowRequest::GrabCursor(grab);
|
||||
self.window_requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(cursor_grab_request);
|
||||
self.event_loop_awakener.ping();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_position(&self, _: Position) -> Result<(), ExternalError> {
|
||||
// XXX This is possible if the locked pointer is being used. We don't have any
|
||||
// API for that right now, but it could be added in
|
||||
// https://github.com/rust-windowing/winit/issues/1677.
|
||||
//
|
||||
// This function is essential for the locked pointer API.
|
||||
//
|
||||
// See pointer-constraints-unstable-v1.xml.
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_ime_position(&self, position: Position) {
|
||||
let scale_factor = self.scale_factor() as f64;
|
||||
let position = position.to_logical(scale_factor);
|
||||
let ime_position_request = WindowRequest::IMEPosition(position);
|
||||
self.window_requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(ime_position_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn display(&self) -> &Display {
|
||||
&self.display
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn surface(&self) -> &WlSurface {
|
||||
&self.surface
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn current_monitor(&self) -> Option<MonitorHandle> {
|
||||
let output = sctk::get_surface_outputs(&self.surface).last()?.clone();
|
||||
Some(MonitorHandle::new(output))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
self.output_manager_handle.available_outputs()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn raw_window_handle(&self) -> WaylandHandle {
|
||||
let display = self.display.get_display_ptr() as *mut _;
|
||||
let surface = self.surface.as_ref().c_ptr() as *mut _;
|
||||
|
||||
WaylandHandle {
|
||||
display,
|
||||
surface,
|
||||
..WaylandHandle::empty()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<LocalARGBColor> for ARGBColor {
|
||||
fn from(color: LocalARGBColor) -> Self {
|
||||
let a = color.a;
|
||||
let r = color.r;
|
||||
let g = color.g;
|
||||
let b = color.b;
|
||||
Self { a, r, g, b }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Window {
|
||||
fn drop(&mut self) {
|
||||
let close_request = WindowRequest::Close;
|
||||
self.window_requests.lock().unwrap().push(close_request);
|
||||
self.event_loop_awakener.ping();
|
||||
}
|
||||
}
|
||||
388
src/platform_impl/linux/wayland/window/shim.rs
Normal file
388
src/platform_impl/linux/wayland/window/shim.rs
Normal file
@@ -0,0 +1,388 @@
|
||||
use std::cell::Cell;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use sctk::reexports::client::protocol::wl_output::WlOutput;
|
||||
|
||||
use sctk::window::{ConceptConfig, ConceptFrame, Decorations, Window};
|
||||
|
||||
use crate::dpi::{LogicalPosition, LogicalSize};
|
||||
|
||||
use crate::event::WindowEvent;
|
||||
use crate::platform_impl::wayland::event_loop::WinitState;
|
||||
use crate::platform_impl::wayland::seat::pointer::WinitPointer;
|
||||
use crate::platform_impl::wayland::seat::text_input::TextInputHandler;
|
||||
use crate::platform_impl::wayland::WindowId;
|
||||
use crate::window::CursorIcon;
|
||||
|
||||
/// A request to SCTK window from Winit window.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum WindowRequest {
|
||||
/// Set fullscreen.
|
||||
///
|
||||
/// Passing `None` will set it on the current monitor.
|
||||
Fullscreen(Option<WlOutput>),
|
||||
|
||||
/// Unset fullscreen.
|
||||
UnsetFullscreen,
|
||||
|
||||
/// Show cursor for the certain window or not.
|
||||
ShowCursor(bool),
|
||||
|
||||
/// Change the cursor icon.
|
||||
NewCursorIcon(CursorIcon),
|
||||
|
||||
/// Grab cursor.
|
||||
GrabCursor(bool),
|
||||
|
||||
/// Maximize the window.
|
||||
Maximize(bool),
|
||||
|
||||
/// Minimize the window.
|
||||
Minimize,
|
||||
|
||||
/// Request decorations change.
|
||||
Decorate(bool),
|
||||
|
||||
/// Make the window resizeable.
|
||||
Resizeable(bool),
|
||||
|
||||
/// Set the title for window.
|
||||
Title(String),
|
||||
|
||||
/// Min size.
|
||||
MinSize(Option<LogicalSize<u32>>),
|
||||
|
||||
/// Max size.
|
||||
MaxSize(Option<LogicalSize<u32>>),
|
||||
|
||||
/// New frame size.
|
||||
FrameSize(LogicalSize<u32>),
|
||||
|
||||
/// Set IME window position.
|
||||
IMEPosition(LogicalPosition<u32>),
|
||||
|
||||
/// Redraw was requested.
|
||||
Redraw,
|
||||
|
||||
/// A new theme for a concept frame was requested.
|
||||
Theme(ConceptConfig),
|
||||
|
||||
/// Window should be closed.
|
||||
Close,
|
||||
}
|
||||
|
||||
/// Pending update to a window from SCTK window.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct WindowUpdate {
|
||||
/// New window size.
|
||||
pub size: Option<LogicalSize<u32>>,
|
||||
|
||||
/// New scale factor.
|
||||
pub scale_factor: Option<i32>,
|
||||
|
||||
/// Whether `redraw` was requested.
|
||||
pub redraw_requested: bool,
|
||||
|
||||
/// Wether the frame should be refreshed.
|
||||
pub refresh_frame: bool,
|
||||
|
||||
/// Close the window.
|
||||
pub close_window: bool,
|
||||
}
|
||||
|
||||
impl WindowUpdate {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
size: None,
|
||||
scale_factor: None,
|
||||
redraw_requested: false,
|
||||
refresh_frame: false,
|
||||
close_window: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take(&mut self) -> Self {
|
||||
let size = self.size.take();
|
||||
let scale_factor = self.scale_factor.take();
|
||||
|
||||
let redraw_requested = self.redraw_requested;
|
||||
self.redraw_requested = false;
|
||||
|
||||
let refresh_frame = self.refresh_frame;
|
||||
self.refresh_frame = false;
|
||||
|
||||
let close_window = self.close_window;
|
||||
self.close_window = false;
|
||||
|
||||
Self {
|
||||
size,
|
||||
scale_factor,
|
||||
redraw_requested,
|
||||
refresh_frame,
|
||||
close_window,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A handle to perform operations on SCTK window
|
||||
/// and react to events.
|
||||
pub struct WindowHandle {
|
||||
/// An actual window.
|
||||
pub window: Window<ConceptFrame>,
|
||||
|
||||
/// The current size of the window.
|
||||
pub size: Arc<Mutex<LogicalSize<u32>>>,
|
||||
|
||||
/// A pending requests to SCTK window.
|
||||
pub pending_window_requests: Arc<Mutex<Vec<WindowRequest>>>,
|
||||
|
||||
/// Current cursor icon.
|
||||
pub cursor_icon: Cell<CursorIcon>,
|
||||
|
||||
/// Visible cursor or not.
|
||||
cursor_visible: Cell<bool>,
|
||||
|
||||
/// Cursor confined to the surface.
|
||||
confined: Cell<bool>,
|
||||
|
||||
/// Pointers over the current surface.
|
||||
pointers: Vec<WinitPointer>,
|
||||
|
||||
/// Text inputs on the current surface.
|
||||
text_inputs: Vec<TextInputHandler>,
|
||||
}
|
||||
|
||||
impl WindowHandle {
|
||||
pub fn new(
|
||||
window: Window<ConceptFrame>,
|
||||
size: Arc<Mutex<LogicalSize<u32>>>,
|
||||
pending_window_requests: Arc<Mutex<Vec<WindowRequest>>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
window,
|
||||
size,
|
||||
pending_window_requests,
|
||||
cursor_icon: Cell::new(CursorIcon::Default),
|
||||
confined: Cell::new(false),
|
||||
cursor_visible: Cell::new(true),
|
||||
pointers: Vec::new(),
|
||||
text_inputs: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_cursor_grab(&self, grab: bool) {
|
||||
// The new requested state matches the current confine status, return.
|
||||
if self.confined.get() == grab {
|
||||
return;
|
||||
}
|
||||
|
||||
self.confined.replace(grab);
|
||||
|
||||
for pointer in self.pointers.iter() {
|
||||
if self.confined.get() {
|
||||
let surface = self.window.surface();
|
||||
pointer.confine(&surface);
|
||||
} else {
|
||||
pointer.unconfine();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pointer appeared over the window.
|
||||
pub fn pointer_entered(&mut self, pointer: WinitPointer) {
|
||||
let position = self.pointers.iter().position(|p| *p == pointer);
|
||||
|
||||
if position.is_none() {
|
||||
if self.confined.get() {
|
||||
let surface = self.window.surface();
|
||||
pointer.confine(&surface);
|
||||
}
|
||||
self.pointers.push(pointer);
|
||||
}
|
||||
|
||||
// Apply the current cursor style.
|
||||
self.set_cursor_visible(self.cursor_visible.get());
|
||||
}
|
||||
|
||||
/// Pointer left the window.
|
||||
pub fn pointer_left(&mut self, pointer: WinitPointer) {
|
||||
let position = self.pointers.iter().position(|p| *p == pointer);
|
||||
|
||||
if let Some(position) = position {
|
||||
let pointer = self.pointers.remove(position);
|
||||
|
||||
// Drop the confined pointer.
|
||||
if self.confined.get() {
|
||||
pointer.unconfine();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text_input_entered(&mut self, text_input: TextInputHandler) {
|
||||
if self
|
||||
.text_inputs
|
||||
.iter()
|
||||
.find(|t| *t == &text_input)
|
||||
.is_none()
|
||||
{
|
||||
self.text_inputs.push(text_input);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text_input_left(&mut self, text_input: TextInputHandler) {
|
||||
if let Some(position) = self.text_inputs.iter().position(|t| *t == text_input) {
|
||||
self.text_inputs.remove(position);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_ime_position(&self, position: LogicalPosition<u32>) {
|
||||
// XXX This won't fly unless user will have a way to request IME window per seat, since
|
||||
// the ime windows will be overlapping, but winit doesn't expose API to specify for
|
||||
// which seat we're setting IME position.
|
||||
let (x, y) = (position.x as i32, position.y as i32);
|
||||
for text_input in self.text_inputs.iter() {
|
||||
text_input.set_ime_position(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_cursor_visible(&self, visible: bool) {
|
||||
self.cursor_visible.replace(visible);
|
||||
let cursor_icon = match visible {
|
||||
true => Some(self.cursor_icon.get()),
|
||||
false => None,
|
||||
};
|
||||
|
||||
for pointer in self.pointers.iter() {
|
||||
pointer.set_cursor(cursor_icon)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_cursor_icon(&self, cursor_icon: CursorIcon) {
|
||||
self.cursor_icon.replace(cursor_icon);
|
||||
|
||||
if !self.cursor_visible.get() {
|
||||
return;
|
||||
}
|
||||
|
||||
for pointer in self.pointers.iter() {
|
||||
pointer.set_cursor(Some(cursor_icon));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn handle_window_requests(winit_state: &mut WinitState) {
|
||||
let window_map = &mut winit_state.window_map;
|
||||
let window_updates = &mut winit_state.window_updates;
|
||||
let mut windows_to_close: Vec<WindowId> = Vec::new();
|
||||
|
||||
// Process the rest of the events.
|
||||
for (window_id, window_handle) in window_map.iter_mut() {
|
||||
let mut requests = window_handle.pending_window_requests.lock().unwrap();
|
||||
for request in requests.drain(..) {
|
||||
match request {
|
||||
WindowRequest::Fullscreen(fullscreen) => {
|
||||
window_handle.window.set_fullscreen(fullscreen.as_ref());
|
||||
}
|
||||
WindowRequest::UnsetFullscreen => {
|
||||
window_handle.window.unset_fullscreen();
|
||||
}
|
||||
WindowRequest::ShowCursor(show_cursor) => {
|
||||
window_handle.set_cursor_visible(show_cursor);
|
||||
}
|
||||
WindowRequest::NewCursorIcon(cursor_icon) => {
|
||||
window_handle.set_cursor_icon(cursor_icon);
|
||||
}
|
||||
WindowRequest::IMEPosition(position) => {
|
||||
window_handle.set_ime_position(position);
|
||||
}
|
||||
WindowRequest::GrabCursor(grab) => {
|
||||
window_handle.set_cursor_grab(grab);
|
||||
}
|
||||
WindowRequest::Maximize(maximize) => {
|
||||
if maximize {
|
||||
window_handle.window.set_maximized();
|
||||
} else {
|
||||
window_handle.window.unset_maximized();
|
||||
}
|
||||
}
|
||||
WindowRequest::Minimize => {
|
||||
window_handle.window.set_minimized();
|
||||
}
|
||||
WindowRequest::Decorate(decorate) => {
|
||||
let decorations = match decorate {
|
||||
true => Decorations::FollowServer,
|
||||
false => Decorations::None,
|
||||
};
|
||||
|
||||
window_handle.window.set_decorate(decorations);
|
||||
|
||||
// We should refresh the frame to apply decorations change.
|
||||
let window_update = window_updates.get_mut(&window_id).unwrap();
|
||||
window_update.refresh_frame = true;
|
||||
}
|
||||
WindowRequest::Resizeable(resizeable) => {
|
||||
window_handle.window.set_resizable(resizeable);
|
||||
|
||||
// We should refresh the frame to update button state.
|
||||
let window_update = window_updates.get_mut(&window_id).unwrap();
|
||||
window_update.refresh_frame = true;
|
||||
}
|
||||
WindowRequest::Title(title) => {
|
||||
window_handle.window.set_title(title);
|
||||
|
||||
// We should refresh the frame to draw new title.
|
||||
let window_update = window_updates.get_mut(&window_id).unwrap();
|
||||
window_update.refresh_frame = true;
|
||||
}
|
||||
WindowRequest::MinSize(size) => {
|
||||
let size = size.map(|size| (size.width, size.height));
|
||||
window_handle.window.set_min_size(size);
|
||||
|
||||
let window_update = window_updates.get_mut(&window_id).unwrap();
|
||||
window_update.redraw_requested = true;
|
||||
}
|
||||
WindowRequest::MaxSize(size) => {
|
||||
let size = size.map(|size| (size.width, size.height));
|
||||
window_handle.window.set_max_size(size);
|
||||
|
||||
let window_update = window_updates.get_mut(&window_id).unwrap();
|
||||
window_update.redraw_requested = true;
|
||||
}
|
||||
WindowRequest::FrameSize(size) => {
|
||||
// Set new size.
|
||||
window_handle.window.resize(size.width, size.height);
|
||||
|
||||
// We should refresh the frame after resize.
|
||||
let window_update = window_updates.get_mut(&window_id).unwrap();
|
||||
window_update.refresh_frame = true;
|
||||
}
|
||||
WindowRequest::Redraw => {
|
||||
let window_update = window_updates.get_mut(&window_id).unwrap();
|
||||
window_update.redraw_requested = true;
|
||||
}
|
||||
WindowRequest::Theme(concept_config) => {
|
||||
window_handle.window.set_frame_config(concept_config);
|
||||
|
||||
// We should refresh the frame to apply new theme.
|
||||
let window_update = window_updates.get_mut(&window_id).unwrap();
|
||||
window_update.refresh_frame = true;
|
||||
}
|
||||
WindowRequest::Close => {
|
||||
// The window was requested to be closed.
|
||||
windows_to_close.push(*window_id);
|
||||
|
||||
// Send event that the window was destroyed.
|
||||
let event_sink = &mut winit_state.event_sink;
|
||||
event_sink.push_window_event(WindowEvent::Destroyed, *window_id);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Close the windows.
|
||||
for window in windows_to_close {
|
||||
let _ = window_map.remove(&window);
|
||||
let _ = window_updates.remove(&window);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,9 @@ use crate::{
|
||||
event_loop::EventLoopWindowTarget as RootELW,
|
||||
};
|
||||
|
||||
/// The X11 documentation states: "Keycodes lie in the inclusive range [8,255]".
|
||||
const KEYCODE_OFFSET: u8 = 8;
|
||||
|
||||
pub(super) struct EventProcessor<T: 'static> {
|
||||
pub(super) dnd: Dnd,
|
||||
pub(super) ime_receiver: ImeReceiver,
|
||||
@@ -32,6 +35,8 @@ pub(super) struct EventProcessor<T: 'static> {
|
||||
// Number of touch events currently in progress
|
||||
pub(super) num_touch: u32,
|
||||
pub(super) first_touch: Option<u64>,
|
||||
// Currently focused window belonging to this process
|
||||
pub(super) active_window: Option<ffi::Window>,
|
||||
}
|
||||
|
||||
impl<T: 'static> EventProcessor<T> {
|
||||
@@ -136,11 +141,12 @@ impl<T: 'static> EventProcessor<T> {
|
||||
if let Some(modifiers) =
|
||||
self.device_mod_state.update_state(&state, modifier)
|
||||
{
|
||||
let device_id = mkdid(util::VIRTUAL_CORE_KEYBOARD);
|
||||
callback(Event::DeviceEvent {
|
||||
device_id,
|
||||
event: DeviceEvent::ModifiersChanged(modifiers),
|
||||
});
|
||||
if let Some(window_id) = self.active_window {
|
||||
callback(Event::WindowEvent {
|
||||
window_id: mkwid(window_id),
|
||||
event: WindowEvent::ModifiersChanged(modifiers),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -562,7 +568,7 @@ impl<T: 'static> EventProcessor<T> {
|
||||
// When a compose sequence or IME pre-edit is finished, it ends in a KeyPress with
|
||||
// a keycode of 0.
|
||||
if keycode != 0 {
|
||||
let scancode = keycode - 8;
|
||||
let scancode = keycode - KEYCODE_OFFSET as u32;
|
||||
let keysym = wt.xconn.lookup_keysym(xkev);
|
||||
let virtual_keycode = events::keysym_to_element(keysym as c_uint);
|
||||
|
||||
@@ -872,44 +878,61 @@ impl<T: 'static> EventProcessor<T> {
|
||||
ffi::XI_FocusIn => {
|
||||
let xev: &ffi::XIFocusInEvent = unsafe { &*(xev.data as *const _) };
|
||||
|
||||
let window_id = mkwid(xev.event);
|
||||
|
||||
wt.ime
|
||||
.borrow_mut()
|
||||
.focus(xev.event)
|
||||
.expect("Failed to focus input context");
|
||||
|
||||
callback(Event::WindowEvent {
|
||||
window_id,
|
||||
event: Focused(true),
|
||||
});
|
||||
|
||||
let modifiers = ModifiersState::from_x11(&xev.mods);
|
||||
|
||||
update_modifiers!(modifiers, None);
|
||||
self.device_mod_state.update_state(&modifiers, None);
|
||||
|
||||
// The deviceid for this event is for a keyboard instead of a pointer,
|
||||
// so we have to do a little extra work.
|
||||
let pointer_id = self
|
||||
.devices
|
||||
.borrow()
|
||||
.get(&DeviceId(xev.deviceid))
|
||||
.map(|device| device.attachment)
|
||||
.unwrap_or(2);
|
||||
if self.active_window != Some(xev.event) {
|
||||
self.active_window = Some(xev.event);
|
||||
|
||||
let position = PhysicalPosition::new(xev.event_x, xev.event_y);
|
||||
let window_id = mkwid(xev.event);
|
||||
let position = PhysicalPosition::new(xev.event_x, xev.event_y);
|
||||
|
||||
callback(Event::WindowEvent {
|
||||
window_id,
|
||||
event: CursorMoved {
|
||||
device_id: mkdid(pointer_id),
|
||||
position,
|
||||
modifiers,
|
||||
},
|
||||
});
|
||||
callback(Event::WindowEvent {
|
||||
window_id,
|
||||
event: Focused(true),
|
||||
});
|
||||
|
||||
// Issue key press events for all pressed keys
|
||||
self.handle_pressed_keys(window_id, ElementState::Pressed, &mut callback);
|
||||
if !modifiers.is_empty() {
|
||||
callback(Event::WindowEvent {
|
||||
window_id,
|
||||
event: WindowEvent::ModifiersChanged(modifiers),
|
||||
});
|
||||
}
|
||||
|
||||
// The deviceid for this event is for a keyboard instead of a pointer,
|
||||
// so we have to do a little extra work.
|
||||
let pointer_id = self
|
||||
.devices
|
||||
.borrow()
|
||||
.get(&DeviceId(xev.deviceid))
|
||||
.map(|device| device.attachment)
|
||||
.unwrap_or(2);
|
||||
|
||||
callback(Event::WindowEvent {
|
||||
window_id,
|
||||
event: CursorMoved {
|
||||
device_id: mkdid(pointer_id),
|
||||
position,
|
||||
modifiers,
|
||||
},
|
||||
});
|
||||
|
||||
// Issue key press events for all pressed keys
|
||||
Self::handle_pressed_keys(
|
||||
&wt,
|
||||
window_id,
|
||||
ElementState::Pressed,
|
||||
&self.mod_keymap,
|
||||
&mut self.device_mod_state,
|
||||
&mut callback,
|
||||
);
|
||||
}
|
||||
}
|
||||
ffi::XI_FocusOut => {
|
||||
let xev: &ffi::XIFocusOutEvent = unsafe { &*(xev.data as *const _) };
|
||||
@@ -921,15 +944,29 @@ impl<T: 'static> EventProcessor<T> {
|
||||
.unfocus(xev.event)
|
||||
.expect("Failed to unfocus input context");
|
||||
|
||||
let window_id = mkwid(xev.event);
|
||||
if self.active_window.take() == Some(xev.event) {
|
||||
let window_id = mkwid(xev.event);
|
||||
|
||||
// Issue key release events for all pressed keys
|
||||
self.handle_pressed_keys(window_id, ElementState::Released, &mut callback);
|
||||
// Issue key release events for all pressed keys
|
||||
Self::handle_pressed_keys(
|
||||
&wt,
|
||||
window_id,
|
||||
ElementState::Released,
|
||||
&self.mod_keymap,
|
||||
&mut self.device_mod_state,
|
||||
&mut callback,
|
||||
);
|
||||
|
||||
callback(Event::WindowEvent {
|
||||
window_id,
|
||||
event: Focused(false),
|
||||
})
|
||||
callback(Event::WindowEvent {
|
||||
window_id,
|
||||
event: WindowEvent::ModifiersChanged(ModifiersState::empty()),
|
||||
});
|
||||
|
||||
callback(Event::WindowEvent {
|
||||
window_id,
|
||||
event: Focused(false),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
ffi::XI_TouchBegin | ffi::XI_TouchUpdate | ffi::XI_TouchEnd => {
|
||||
@@ -1053,10 +1090,10 @@ impl<T: 'static> EventProcessor<T> {
|
||||
|
||||
let device_id = mkdid(xev.sourceid);
|
||||
let keycode = xev.detail;
|
||||
if keycode < 8 {
|
||||
let scancode = keycode - KEYCODE_OFFSET as i32;
|
||||
if scancode < 0 {
|
||||
return;
|
||||
}
|
||||
let scancode = (keycode - 8) as u32;
|
||||
let keysym = wt.xconn.keycode_to_keysym(keycode as ffi::KeyCode);
|
||||
let virtual_keycode = events::keysym_to_element(keysym as c_uint);
|
||||
let modifiers = self.device_mod_state.modifiers();
|
||||
@@ -1065,7 +1102,7 @@ impl<T: 'static> EventProcessor<T> {
|
||||
callback(Event::DeviceEvent {
|
||||
device_id,
|
||||
event: DeviceEvent::Key(KeyboardInput {
|
||||
scancode,
|
||||
scancode: scancode as u32,
|
||||
virtual_keycode,
|
||||
state,
|
||||
modifiers,
|
||||
@@ -1084,10 +1121,12 @@ impl<T: 'static> EventProcessor<T> {
|
||||
let new_modifiers = self.device_mod_state.modifiers();
|
||||
|
||||
if modifiers != new_modifiers {
|
||||
callback(Event::DeviceEvent {
|
||||
device_id,
|
||||
event: DeviceEvent::ModifiersChanged(new_modifiers),
|
||||
});
|
||||
if let Some(window_id) = self.active_window {
|
||||
callback(Event::WindowEvent {
|
||||
window_id: mkwid(window_id),
|
||||
event: WindowEvent::ModifiersChanged(new_modifiers),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1191,30 +1230,37 @@ impl<T: 'static> EventProcessor<T> {
|
||||
}
|
||||
|
||||
fn handle_pressed_keys<F>(
|
||||
&self,
|
||||
wt: &super::EventLoopWindowTarget<T>,
|
||||
window_id: crate::window::WindowId,
|
||||
state: ElementState,
|
||||
mod_keymap: &ModifierKeymap,
|
||||
device_mod_state: &mut ModifierKeyState,
|
||||
callback: &mut F,
|
||||
) where
|
||||
F: FnMut(Event<'_, T>),
|
||||
{
|
||||
let wt = get_xtarget(&self.target);
|
||||
|
||||
let device_id = mkdid(util::VIRTUAL_CORE_KEYBOARD);
|
||||
let modifiers = self.device_mod_state.modifiers();
|
||||
let modifiers = device_mod_state.modifiers();
|
||||
|
||||
// Get the set of keys currently pressed and apply Key events to each
|
||||
let keys = wt.xconn.query_keymap();
|
||||
|
||||
for keycode in &keys {
|
||||
if keycode < 8 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let scancode = (keycode - 8) as u32;
|
||||
// Update modifiers state and emit key events based on which keys are currently pressed.
|
||||
for keycode in wt
|
||||
.xconn
|
||||
.query_keymap()
|
||||
.into_iter()
|
||||
.filter(|k| *k >= KEYCODE_OFFSET)
|
||||
{
|
||||
let scancode = (keycode - KEYCODE_OFFSET) as u32;
|
||||
let keysym = wt.xconn.keycode_to_keysym(keycode);
|
||||
let virtual_keycode = events::keysym_to_element(keysym as c_uint);
|
||||
|
||||
if let Some(modifier) = mod_keymap.get_modifier(keycode as ffi::KeyCode) {
|
||||
device_mod_state.key_event(
|
||||
ElementState::Pressed,
|
||||
keycode as ffi::KeyCode,
|
||||
modifier,
|
||||
);
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
callback(Event::WindowEvent {
|
||||
window_id,
|
||||
|
||||
@@ -81,12 +81,12 @@ pub fn keysym_to_element(keysym: libc::c_uint) -> Option<VirtualKeyCode> {
|
||||
ffi::XK_KP_Insert => VirtualKeyCode::Insert,
|
||||
ffi::XK_KP_Delete => VirtualKeyCode::Delete,
|
||||
ffi::XK_KP_Equal => VirtualKeyCode::NumpadEquals,
|
||||
//ffi::XK_KP_Multiply => VirtualKeyCode::NumpadMultiply,
|
||||
ffi::XK_KP_Add => VirtualKeyCode::Add,
|
||||
ffi::XK_KP_Multiply => VirtualKeyCode::NumpadMultiply,
|
||||
ffi::XK_KP_Add => VirtualKeyCode::NumpadAdd,
|
||||
//ffi::XK_KP_Separator => VirtualKeyCode::Kp_separator,
|
||||
ffi::XK_KP_Subtract => VirtualKeyCode::Subtract,
|
||||
//ffi::XK_KP_Decimal => VirtualKeyCode::Kp_decimal,
|
||||
ffi::XK_KP_Divide => VirtualKeyCode::Divide,
|
||||
ffi::XK_KP_Subtract => VirtualKeyCode::NumpadSubtract,
|
||||
ffi::XK_KP_Decimal => VirtualKeyCode::NumpadDecimal,
|
||||
ffi::XK_KP_Divide => VirtualKeyCode::NumpadDivide,
|
||||
ffi::XK_KP_0 => VirtualKeyCode::Numpad0,
|
||||
ffi::XK_KP_1 => VirtualKeyCode::Numpad1,
|
||||
ffi::XK_KP_2 => VirtualKeyCode::Numpad2,
|
||||
@@ -183,10 +183,10 @@ pub fn keysym_to_element(keysym: libc::c_uint) -> Option<VirtualKeyCode> {
|
||||
//ffi::XK_quoteright => VirtualKeyCode::Quoteright,
|
||||
//ffi::XK_parenleft => VirtualKeyCode::Parenleft,
|
||||
//ffi::XK_parenright => VirtualKeyCode::Parenright,
|
||||
//ffi::XK_asterisk => VirtualKeyCode::Asterisk,
|
||||
ffi::XK_plus => VirtualKeyCode::Add,
|
||||
ffi::XK_asterisk => VirtualKeyCode::Asterisk,
|
||||
ffi::XK_plus => VirtualKeyCode::Plus,
|
||||
ffi::XK_comma => VirtualKeyCode::Comma,
|
||||
ffi::XK_minus => VirtualKeyCode::Subtract,
|
||||
ffi::XK_minus => VirtualKeyCode::Minus,
|
||||
ffi::XK_period => VirtualKeyCode::Period,
|
||||
ffi::XK_slash => VirtualKeyCode::Slash,
|
||||
ffi::XK_0 => VirtualKeyCode::Key0,
|
||||
|
||||
@@ -21,7 +21,8 @@ unsafe fn open_im(xconn: &Arc<XConnection>, locale_modifiers: &CStr) -> Option<f
|
||||
// XSetLocaleModifiers returns...
|
||||
// * The current locale modifiers if it's given a NULL pointer.
|
||||
// * The new locale modifiers if we succeeded in setting them.
|
||||
// * NULL if the locale modifiers string is malformed.
|
||||
// * NULL if the locale modifiers string is malformed or if the
|
||||
// current locale is not supported by Xlib.
|
||||
(xconn.xlib.XSetLocaleModifiers)(locale_modifiers.as_ptr());
|
||||
|
||||
let im = (xconn.xlib.XOpenIM)(
|
||||
|
||||
@@ -29,6 +29,7 @@ use std::{
|
||||
mem::{self, MaybeUninit},
|
||||
ops::Deref,
|
||||
os::raw::*,
|
||||
ptr,
|
||||
rc::Rc,
|
||||
slice,
|
||||
sync::{mpsc, Arc, Mutex, Weak},
|
||||
@@ -105,7 +106,25 @@ impl<T: 'static> EventLoop<T> {
|
||||
// Input methods will open successfully without setting the locale, but it won't be
|
||||
// possible to actually commit pre-edit sequences.
|
||||
unsafe {
|
||||
// Remember default locale to restore it if target locale is unsupported
|
||||
// by Xlib
|
||||
let default_locale = setlocale(LC_CTYPE, ptr::null());
|
||||
setlocale(LC_CTYPE, b"\0".as_ptr() as *const _);
|
||||
|
||||
// Check if set locale is supported by Xlib.
|
||||
// If not, calls to some Xlib functions like `XSetLocaleModifiers`
|
||||
// will fail.
|
||||
let locale_supported = (xconn.xlib.XSupportsLocale)() == 1;
|
||||
if !locale_supported {
|
||||
let unsupported_locale = setlocale(LC_CTYPE, ptr::null());
|
||||
warn!(
|
||||
"Unsupported locale \"{}\". Restoring default locale \"{}\".",
|
||||
CStr::from_ptr(unsupported_locale).to_string_lossy(),
|
||||
CStr::from_ptr(default_locale).to_string_lossy()
|
||||
);
|
||||
// Restore default locale
|
||||
setlocale(LC_CTYPE, default_locale);
|
||||
}
|
||||
}
|
||||
let ime = RefCell::new({
|
||||
let result = Ime::new(Arc::clone(&xconn));
|
||||
@@ -206,6 +225,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
device_mod_state: Default::default(),
|
||||
num_touch: 0,
|
||||
first_touch: None,
|
||||
active_window: None,
|
||||
};
|
||||
|
||||
// Register for device hotplug events
|
||||
@@ -238,24 +258,22 @@ impl<T: 'static> EventLoop<T> {
|
||||
&self.target
|
||||
}
|
||||
|
||||
pub(crate) fn x_connection(&self) -> &Arc<XConnection> {
|
||||
get_xtarget(&self.target).x_connection()
|
||||
}
|
||||
|
||||
pub fn run_return<F>(&mut self, mut callback: F)
|
||||
where
|
||||
F: FnMut(Event<'_, T>, &RootELW<T>, &mut ControlFlow),
|
||||
{
|
||||
let mut control_flow = ControlFlow::default();
|
||||
let mut events = Events::with_capacity(8);
|
||||
|
||||
callback(
|
||||
crate::event::Event::NewEvents(crate::event::StartCause::Init),
|
||||
&self.target,
|
||||
&mut control_flow,
|
||||
);
|
||||
let mut cause = StartCause::Init;
|
||||
|
||||
loop {
|
||||
sticky_exit_callback(
|
||||
crate::event::Event::NewEvents(cause),
|
||||
&self.target,
|
||||
&mut control_flow,
|
||||
&mut callback,
|
||||
);
|
||||
|
||||
// Process all pending events
|
||||
self.drain_events(&mut callback, &mut control_flow);
|
||||
|
||||
@@ -306,7 +324,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
}
|
||||
|
||||
let start = Instant::now();
|
||||
let (mut cause, deadline, timeout);
|
||||
let (deadline, timeout);
|
||||
|
||||
match control_flow {
|
||||
ControlFlow::Exit => break,
|
||||
@@ -337,38 +355,20 @@ impl<T: 'static> EventLoop<T> {
|
||||
}
|
||||
}
|
||||
|
||||
if self.event_processor.poll() {
|
||||
// If the XConnection already contains buffered events, we don't
|
||||
// need to wait for data on the socket.
|
||||
// However, we still need to check for user events.
|
||||
self.poll
|
||||
.poll(&mut events, Some(Duration::from_millis(0)))
|
||||
.unwrap();
|
||||
events.clear();
|
||||
|
||||
callback(
|
||||
crate::event::Event::NewEvents(cause),
|
||||
&self.target,
|
||||
&mut control_flow,
|
||||
);
|
||||
} else {
|
||||
// If the XConnection already contains buffered events, we don't
|
||||
// need to wait for data on the socket.
|
||||
if !self.event_processor.poll() {
|
||||
self.poll.poll(&mut events, timeout).unwrap();
|
||||
events.clear();
|
||||
}
|
||||
|
||||
let wait_cancelled = deadline.map_or(false, |deadline| Instant::now() < deadline);
|
||||
let wait_cancelled = deadline.map_or(false, |deadline| Instant::now() < deadline);
|
||||
|
||||
if wait_cancelled {
|
||||
cause = StartCause::WaitCancelled {
|
||||
start,
|
||||
requested_resume: deadline,
|
||||
};
|
||||
}
|
||||
|
||||
callback(
|
||||
crate::event::Event::NewEvents(cause),
|
||||
&self.target,
|
||||
&mut control_flow,
|
||||
);
|
||||
if wait_cancelled {
|
||||
cause = StartCause::WaitCancelled {
|
||||
start,
|
||||
requested_resume: deadline,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -422,6 +422,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
pub(crate) fn get_xtarget<T>(target: &RootELW<T>) -> &EventLoopWindowTarget<T> {
|
||||
match target.p {
|
||||
super::EventLoopWindowTarget::X(ref target) => target,
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
@@ -489,9 +490,21 @@ impl<'a> Deref for DeviceInfo<'a> {
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct WindowId(ffi::Window);
|
||||
|
||||
impl WindowId {
|
||||
pub unsafe fn dummy() -> Self {
|
||||
WindowId(0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId(c_int);
|
||||
|
||||
impl DeviceId {
|
||||
pub unsafe fn dummy() -> Self {
|
||||
DeviceId(0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Window(Arc<UnownedWindow>);
|
||||
|
||||
impl Deref for Window {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use crate::window::{Icon, Pixel, PIXEL_SIZE};
|
||||
use crate::icon::{Icon, Pixel, PIXEL_SIZE};
|
||||
|
||||
impl Pixel {
|
||||
pub fn to_packed_argb(&self) -> Cardinal {
|
||||
@@ -18,13 +18,14 @@ impl Pixel {
|
||||
|
||||
impl Icon {
|
||||
pub(crate) fn to_cardinals(&self) -> Vec<Cardinal> {
|
||||
assert_eq!(self.rgba.len() % PIXEL_SIZE, 0);
|
||||
let pixel_count = self.rgba.len() / PIXEL_SIZE;
|
||||
assert_eq!(pixel_count, (self.width * self.height) as usize);
|
||||
let rgba_icon = &self.inner;
|
||||
assert_eq!(rgba_icon.rgba.len() % PIXEL_SIZE, 0);
|
||||
let pixel_count = rgba_icon.rgba.len() / PIXEL_SIZE;
|
||||
assert_eq!(pixel_count, (rgba_icon.width * rgba_icon.height) as usize);
|
||||
let mut data = Vec::with_capacity(pixel_count);
|
||||
data.push(self.width as Cardinal);
|
||||
data.push(self.height as Cardinal);
|
||||
let pixels = self.rgba.as_ptr() as *const Pixel;
|
||||
data.push(rgba_icon.width as Cardinal);
|
||||
data.push(rgba_icon.height as Cardinal);
|
||||
let pixels = rgba_icon.rgba.as_ptr() as *const Pixel;
|
||||
for pixel_index in 0..pixel_count {
|
||||
let pixel = unsafe { &*pixels.offset(pixel_index as isize) };
|
||||
data.push(pixel.to_packed_argb());
|
||||
|
||||
@@ -136,23 +136,23 @@ impl UnownedWindow {
|
||||
})
|
||||
.unwrap_or_else(|| monitors.swap_remove(0))
|
||||
};
|
||||
let dpi_factor = guessed_monitor.scale_factor();
|
||||
let scale_factor = guessed_monitor.scale_factor();
|
||||
|
||||
info!("Guessed window scale factor: {}", dpi_factor);
|
||||
info!("Guessed window scale factor: {}", scale_factor);
|
||||
|
||||
let max_inner_size: Option<(u32, u32)> = window_attrs
|
||||
.max_inner_size
|
||||
.map(|size| size.to_physical::<u32>(dpi_factor).into());
|
||||
.map(|size| size.to_physical::<u32>(scale_factor).into());
|
||||
let min_inner_size: Option<(u32, u32)> = window_attrs
|
||||
.min_inner_size
|
||||
.map(|size| size.to_physical::<u32>(dpi_factor).into());
|
||||
.map(|size| size.to_physical::<u32>(scale_factor).into());
|
||||
|
||||
let dimensions = {
|
||||
// x11 only applies constraints when the window is actively resized
|
||||
// by the user, so we have to manually apply the initial constraints
|
||||
let mut dimensions: (u32, u32) = window_attrs
|
||||
.inner_size
|
||||
.map(|size| size.to_physical::<u32>(dpi_factor))
|
||||
.map(|size| size.to_physical::<u32>(scale_factor))
|
||||
.or_else(|| Some((800, 600).into()))
|
||||
.map(Into::into)
|
||||
.unwrap();
|
||||
@@ -227,7 +227,7 @@ impl UnownedWindow {
|
||||
// is > 0, like we do in glutin.
|
||||
//
|
||||
// It is non obvious which masks, if any, we should pass to
|
||||
// `XGetVisualInfo`. winit doesn't recieve any info about what
|
||||
// `XGetVisualInfo`. winit doesn't receive any info about what
|
||||
// properties the user wants. Users should consider choosing the
|
||||
// visual themselves as glutin does.
|
||||
match pl_attribs.visual_infos {
|
||||
@@ -324,10 +324,10 @@ impl UnownedWindow {
|
||||
{
|
||||
let mut min_inner_size = window_attrs
|
||||
.min_inner_size
|
||||
.map(|size| size.to_physical::<u32>(dpi_factor));
|
||||
.map(|size| size.to_physical::<u32>(scale_factor));
|
||||
let mut max_inner_size = window_attrs
|
||||
.max_inner_size
|
||||
.map(|size| size.to_physical::<u32>(dpi_factor));
|
||||
.map(|size| size.to_physical::<u32>(scale_factor));
|
||||
|
||||
if !window_attrs.resizable {
|
||||
if util::wm_name_is_one_of(&["Xfwm4"]) {
|
||||
@@ -351,12 +351,12 @@ impl UnownedWindow {
|
||||
normal_hints.set_resize_increments(
|
||||
pl_attribs
|
||||
.resize_increments
|
||||
.map(|size| size.to_physical::<u32>(dpi_factor).into()),
|
||||
.map(|size| size.to_physical::<u32>(scale_factor).into()),
|
||||
);
|
||||
normal_hints.set_base_size(
|
||||
pl_attribs
|
||||
.base_size
|
||||
.map(|size| size.to_physical::<u32>(dpi_factor).into()),
|
||||
.map(|size| size.to_physical::<u32>(scale_factor).into()),
|
||||
);
|
||||
xconn.set_normal_hints(window.xwindow, normal_hints).queue();
|
||||
}
|
||||
@@ -640,6 +640,7 @@ impl UnownedWindow {
|
||||
let flusher = self.set_fullscreen_hint(false);
|
||||
let mut shared_state_lock = self.shared_state.lock();
|
||||
if let Some(position) = shared_state_lock.restore_position.take() {
|
||||
drop(shared_state_lock);
|
||||
self.set_position_inner(position.0, position.1).queue();
|
||||
}
|
||||
Some(flusher)
|
||||
@@ -648,10 +649,12 @@ impl UnownedWindow {
|
||||
let (video_mode, monitor) = match fullscreen {
|
||||
Fullscreen::Exclusive(RootVideoMode {
|
||||
video_mode: PlatformVideoMode::X(ref video_mode),
|
||||
}) => (Some(video_mode), video_mode.monitor.as_ref().unwrap()),
|
||||
Fullscreen::Borderless(RootMonitorHandle {
|
||||
inner: PlatformMonitorHandle::X(ref monitor),
|
||||
}) => (None, monitor),
|
||||
}) => (Some(video_mode), video_mode.monitor.clone().unwrap()),
|
||||
Fullscreen::Borderless(Some(RootMonitorHandle {
|
||||
inner: PlatformMonitorHandle::X(monitor),
|
||||
})) => (None, monitor),
|
||||
Fullscreen::Borderless(None) => (None, self.current_monitor()),
|
||||
#[cfg(feature = "wayland")]
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
@@ -1053,8 +1056,8 @@ impl UnownedWindow {
|
||||
|
||||
#[inline]
|
||||
pub fn set_inner_size(&self, size: Size) {
|
||||
let dpi_factor = self.scale_factor();
|
||||
let (width, height) = size.to_physical::<u32>(dpi_factor).into();
|
||||
let scale_factor = self.scale_factor();
|
||||
let (width, height) = size.to_physical::<u32>(scale_factor).into();
|
||||
self.set_inner_size_physical(width, height);
|
||||
}
|
||||
|
||||
@@ -1097,16 +1100,16 @@ impl UnownedWindow {
|
||||
|
||||
pub(crate) fn adjust_for_dpi(
|
||||
&self,
|
||||
old_dpi_factor: f64,
|
||||
new_dpi_factor: f64,
|
||||
old_scale_factor: f64,
|
||||
new_scale_factor: f64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
shared_state: &SharedState,
|
||||
) -> (u32, u32) {
|
||||
let scale_factor = new_dpi_factor / old_dpi_factor;
|
||||
let scale_factor = new_scale_factor / old_scale_factor;
|
||||
self.update_normal_hints(|normal_hints| {
|
||||
let dpi_adjuster =
|
||||
|size: Size| -> (u32, u32) { size.to_physical::<u32>(new_dpi_factor).into() };
|
||||
|size: Size| -> (u32, u32) { size.to_physical::<u32>(new_scale_factor).into() };
|
||||
let max_size = shared_state.max_inner_size.map(&dpi_adjuster);
|
||||
let min_size = shared_state.min_inner_size.map(&dpi_adjuster);
|
||||
let resize_increments = shared_state.resize_increments.map(&dpi_adjuster);
|
||||
@@ -1146,12 +1149,12 @@ impl UnownedWindow {
|
||||
|
||||
self.set_maximizable_inner(resizable).queue();
|
||||
|
||||
let dpi_factor = self.scale_factor();
|
||||
let scale_factor = self.scale_factor();
|
||||
let min_inner_size = min_size
|
||||
.map(|size| size.to_physical::<u32>(dpi_factor))
|
||||
.map(|size| size.to_physical::<u32>(scale_factor))
|
||||
.map(Into::into);
|
||||
let max_inner_size = max_size
|
||||
.map(|size| size.to_physical::<u32>(dpi_factor))
|
||||
.map(|size| size.to_physical::<u32>(scale_factor))
|
||||
.map(Into::into);
|
||||
self.update_normal_hints(|normal_hints| {
|
||||
normal_hints.set_min_size(min_inner_size);
|
||||
|
||||
@@ -92,6 +92,7 @@ impl<T> EventHandler for EventLoopHandler<T> {
|
||||
struct Handler {
|
||||
ready: AtomicBool,
|
||||
in_callback: AtomicBool,
|
||||
dialog_is_closing: AtomicBool,
|
||||
control_flow: Mutex<ControlFlow>,
|
||||
control_flow_prev: Mutex<ControlFlow>,
|
||||
start_time: Mutex<Option<Instant>>,
|
||||
@@ -223,6 +224,8 @@ impl Handler {
|
||||
}
|
||||
}
|
||||
|
||||
pub static INTERRUPT_EVENT_LOOP_EXIT: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
pub enum AppState {}
|
||||
|
||||
impl AppState {
|
||||
@@ -336,29 +339,51 @@ impl AppState {
|
||||
}
|
||||
if HANDLER.should_exit() {
|
||||
unsafe {
|
||||
let _: () = msg_send![NSApp(), stop: nil];
|
||||
|
||||
let pool = NSAutoreleasePool::new(nil);
|
||||
|
||||
let windows: id = msg_send![NSApp(), windows];
|
||||
let app: id = NSApp();
|
||||
let windows: id = msg_send![app, windows];
|
||||
let window: id = msg_send![windows, objectAtIndex:0];
|
||||
let window_count: usize = msg_send![windows, count];
|
||||
assert_ne!(window, nil);
|
||||
|
||||
let dummy_event: id = msg_send![class!(NSEvent),
|
||||
otherEventWithType: NSApplicationDefined
|
||||
location: NSPoint::new(0.0, 0.0)
|
||||
modifierFlags: 0
|
||||
timestamp: 0
|
||||
windowNumber: 0
|
||||
context: nil
|
||||
subtype: 0
|
||||
data1: 0
|
||||
data2: 0
|
||||
];
|
||||
// To stop event loop immediately, we need to post some event here.
|
||||
let _: () = msg_send![window, postEvent: dummy_event atStart: YES];
|
||||
let dialog_open = if window_count > 1 {
|
||||
let dialog: id = msg_send![windows, lastObject];
|
||||
let is_main_window: bool = msg_send![dialog, isMainWindow];
|
||||
msg_send![dialog, isVisible] && !is_main_window
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
let dialog_is_closing = HANDLER.dialog_is_closing.load(Ordering::SeqCst);
|
||||
let pool = NSAutoreleasePool::new(nil);
|
||||
if !INTERRUPT_EVENT_LOOP_EXIT.load(Ordering::SeqCst)
|
||||
&& !dialog_open
|
||||
&& !dialog_is_closing
|
||||
{
|
||||
let _: () = msg_send![app, stop: nil];
|
||||
|
||||
let dummy_event: id = msg_send![class!(NSEvent),
|
||||
otherEventWithType: NSApplicationDefined
|
||||
location: NSPoint::new(0.0, 0.0)
|
||||
modifierFlags: 0
|
||||
timestamp: 0
|
||||
windowNumber: 0
|
||||
context: nil
|
||||
subtype: 0
|
||||
data1: 0
|
||||
data2: 0
|
||||
];
|
||||
// To stop event loop immediately, we need to post some event here.
|
||||
let _: () = msg_send![window, postEvent: dummy_event atStart: YES];
|
||||
}
|
||||
pool.drain();
|
||||
|
||||
let window_has_focus = msg_send![window, isKeyWindow];
|
||||
if !dialog_open && window_has_focus && dialog_is_closing {
|
||||
HANDLER.dialog_is_closing.store(false, Ordering::SeqCst);
|
||||
}
|
||||
if dialog_open {
|
||||
HANDLER.dialog_is_closing.store(true, Ordering::SeqCst);
|
||||
}
|
||||
};
|
||||
}
|
||||
HANDLER.update_start_time();
|
||||
|
||||
@@ -156,20 +156,20 @@ pub fn scancode_to_keycode(scancode: c_ushort) -> Option<VirtualKeyCode> {
|
||||
0x3e => VirtualKeyCode::RControl,
|
||||
//0x3f => Fn key,
|
||||
0x40 => VirtualKeyCode::F17,
|
||||
0x41 => VirtualKeyCode::Decimal,
|
||||
0x41 => VirtualKeyCode::NumpadDecimal,
|
||||
//0x42 -> unkown,
|
||||
0x43 => VirtualKeyCode::Multiply,
|
||||
0x43 => VirtualKeyCode::NumpadMultiply,
|
||||
//0x44 => unkown,
|
||||
0x45 => VirtualKeyCode::Add,
|
||||
0x45 => VirtualKeyCode::NumpadAdd,
|
||||
//0x46 => unkown,
|
||||
0x47 => VirtualKeyCode::Numlock,
|
||||
//0x48 => KeypadClear,
|
||||
0x49 => VirtualKeyCode::VolumeUp,
|
||||
0x4a => VirtualKeyCode::VolumeDown,
|
||||
0x4b => VirtualKeyCode::Divide,
|
||||
0x4b => VirtualKeyCode::NumpadDivide,
|
||||
0x4c => VirtualKeyCode::NumpadEnter,
|
||||
//0x4d => unkown,
|
||||
0x4e => VirtualKeyCode::Subtract,
|
||||
0x4e => VirtualKeyCode::NumpadSubtract,
|
||||
0x4f => VirtualKeyCode::F18,
|
||||
0x50 => VirtualKeyCode::F19,
|
||||
0x51 => VirtualKeyCode::NumpadEquals,
|
||||
|
||||
@@ -12,6 +12,7 @@ use cocoa::{
|
||||
use crate::{
|
||||
event::Event,
|
||||
event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootWindowTarget},
|
||||
monitor::MonitorHandle as RootMonitorHandle,
|
||||
platform_impl::platform::{
|
||||
app::APP_CLASS,
|
||||
app_delegate::APP_DELEGATE_CLASS,
|
||||
@@ -34,6 +35,19 @@ impl<T> Default for EventLoopWindowTarget<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoopWindowTarget<T> {
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
monitor::available_monitors()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
let monitor = monitor::primary_monitor();
|
||||
Some(RootMonitorHandle { inner: monitor })
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoop<T: 'static> {
|
||||
window_target: Rc<RootWindowTarget<T>>,
|
||||
_delegate: IdRef,
|
||||
@@ -68,16 +82,6 @@ impl<T> EventLoop<T> {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
monitor::available_monitors()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> MonitorHandle {
|
||||
monitor::primary_monitor()
|
||||
}
|
||||
|
||||
pub fn window_target(&self) -> &RootWindowTarget<T> {
|
||||
&self.window_target
|
||||
}
|
||||
@@ -117,6 +121,14 @@ pub struct Proxy<T> {
|
||||
|
||||
unsafe impl<T: Send> Send for Proxy<T> {}
|
||||
|
||||
impl<T> Drop for Proxy<T> {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
CFRelease(self.source as _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Proxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Proxy::new(self.sender.clone())
|
||||
|
||||
@@ -25,6 +25,8 @@ use crate::{
|
||||
error::OsError as RootOsError, event::DeviceId as RootDeviceId, window::WindowAttributes,
|
||||
};
|
||||
|
||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId;
|
||||
|
||||
|
||||
@@ -50,13 +50,13 @@ impl Default for CursorState {
|
||||
}
|
||||
}
|
||||
|
||||
struct ViewState {
|
||||
pub(super) struct ViewState {
|
||||
ns_window: id,
|
||||
pub cursor_state: Arc<Mutex<CursorState>>,
|
||||
ime_spot: Option<(f64, f64)>,
|
||||
raw_characters: Option<String>,
|
||||
is_key_down: bool,
|
||||
modifiers: ModifiersState,
|
||||
pub(super) modifiers: ModifiersState,
|
||||
tracking_rect: Option<NSInteger>,
|
||||
}
|
||||
|
||||
@@ -383,8 +383,13 @@ extern "C" fn reset_cursor_rects(this: &Object, _sel: Sel) {
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn has_marked_text(_this: &Object, _sel: Sel) -> BOOL {
|
||||
YES
|
||||
extern "C" fn has_marked_text(this: &Object, _sel: Sel) -> BOOL {
|
||||
unsafe {
|
||||
trace!("Triggered `hasMarkedText`");
|
||||
let marked_text: id = *this.get_ivar("markedText");
|
||||
trace!("Completed `hasMarkedText`");
|
||||
(marked_text.length() > 0) as i8
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn marked_range(this: &Object, _sel: Sel) -> NSRange {
|
||||
@@ -618,6 +623,19 @@ fn retrieve_keycode(event: id) -> Option<VirtualKeyCode> {
|
||||
})
|
||||
}
|
||||
|
||||
// Update `state.modifiers` if `event` has something different
|
||||
fn update_potentially_stale_modifiers(state: &mut ViewState, event: id) {
|
||||
let event_modifiers = event_mods(event);
|
||||
if state.modifiers != event_modifiers {
|
||||
state.modifiers = event_modifiers;
|
||||
|
||||
AppState::queue_event(EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: WindowId(get_window_id(state.ns_window)),
|
||||
event: WindowEvent::ModifiersChanged(state.modifiers),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn key_down(this: &Object, _sel: Sel, event: id) {
|
||||
trace!("Triggered `keyDown`");
|
||||
unsafe {
|
||||
@@ -633,6 +651,8 @@ extern "C" fn key_down(this: &Object, _sel: Sel, event: id) {
|
||||
|
||||
let is_repeat = msg_send![event, isARepeat];
|
||||
|
||||
update_potentially_stale_modifiers(state, event);
|
||||
|
||||
#[allow(deprecated)]
|
||||
let window_event = Event::WindowEvent {
|
||||
window_id,
|
||||
@@ -686,6 +706,8 @@ extern "C" fn key_up(this: &Object, _sel: Sel, event: id) {
|
||||
let scancode = get_scancode(event) as u32;
|
||||
let virtual_keycode = retrieve_keycode(event);
|
||||
|
||||
update_potentially_stale_modifiers(state, event);
|
||||
|
||||
#[allow(deprecated)]
|
||||
let window_event = Event::WindowEvent {
|
||||
window_id: WindowId(get_window_id(state.ns_window)),
|
||||
@@ -750,16 +772,18 @@ extern "C" fn flags_changed(this: &Object, _sel: Sel, event: id) {
|
||||
events.push_back(window_event);
|
||||
}
|
||||
|
||||
let window_id = WindowId(get_window_id(state.ns_window));
|
||||
|
||||
for event in events {
|
||||
AppState::queue_event(EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: WindowId(get_window_id(state.ns_window)),
|
||||
window_id,
|
||||
event,
|
||||
}));
|
||||
}
|
||||
|
||||
AppState::queue_event(EventWrapper::StaticEvent(Event::DeviceEvent {
|
||||
device_id: DEVICE_ID,
|
||||
event: DeviceEvent::ModifiersChanged(state.modifiers),
|
||||
AppState::queue_event(EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id,
|
||||
event: WindowEvent::ModifiersChanged(state.modifiers),
|
||||
}));
|
||||
}
|
||||
trace!("Completed `flagsChanged`");
|
||||
@@ -801,6 +825,8 @@ extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
|
||||
|
||||
let event: id = msg_send![NSApp(), currentEvent];
|
||||
|
||||
update_potentially_stale_modifiers(state, event);
|
||||
|
||||
#[allow(deprecated)]
|
||||
let window_event = Event::WindowEvent {
|
||||
window_id: WindowId(get_window_id(state.ns_window)),
|
||||
@@ -826,6 +852,8 @@ fn mouse_click(this: &Object, event: id, button: MouseButton, button_state: Elem
|
||||
let state_ptr: *mut c_void = *this.get_ivar("winitState");
|
||||
let state = &mut *(state_ptr as *mut ViewState);
|
||||
|
||||
update_potentially_stale_modifiers(state, event);
|
||||
|
||||
let window_event = Event::WindowEvent {
|
||||
window_id: WindowId(get_window_id(state.ns_window)),
|
||||
event: WindowEvent::MouseInput {
|
||||
@@ -841,26 +869,32 @@ fn mouse_click(this: &Object, event: id, button: MouseButton, button_state: Elem
|
||||
}
|
||||
|
||||
extern "C" fn mouse_down(this: &Object, _sel: Sel, event: id) {
|
||||
mouse_motion(this, event);
|
||||
mouse_click(this, event, MouseButton::Left, ElementState::Pressed);
|
||||
}
|
||||
|
||||
extern "C" fn mouse_up(this: &Object, _sel: Sel, event: id) {
|
||||
mouse_motion(this, event);
|
||||
mouse_click(this, event, MouseButton::Left, ElementState::Released);
|
||||
}
|
||||
|
||||
extern "C" fn right_mouse_down(this: &Object, _sel: Sel, event: id) {
|
||||
mouse_motion(this, event);
|
||||
mouse_click(this, event, MouseButton::Right, ElementState::Pressed);
|
||||
}
|
||||
|
||||
extern "C" fn right_mouse_up(this: &Object, _sel: Sel, event: id) {
|
||||
mouse_motion(this, event);
|
||||
mouse_click(this, event, MouseButton::Right, ElementState::Released);
|
||||
}
|
||||
|
||||
extern "C" fn other_mouse_down(this: &Object, _sel: Sel, event: id) {
|
||||
mouse_motion(this, event);
|
||||
mouse_click(this, event, MouseButton::Middle, ElementState::Pressed);
|
||||
}
|
||||
|
||||
extern "C" fn other_mouse_up(this: &Object, _sel: Sel, event: id) {
|
||||
mouse_motion(this, event);
|
||||
mouse_click(this, event, MouseButton::Middle, ElementState::Released);
|
||||
}
|
||||
|
||||
@@ -881,14 +915,19 @@ fn mouse_motion(this: &Object, event: id) {
|
||||
|| view_point.x > view_rect.size.width
|
||||
|| view_point.y > view_rect.size.height
|
||||
{
|
||||
// Point is outside of the client area (view)
|
||||
return;
|
||||
let mouse_buttons_down: NSInteger = msg_send![class!(NSEvent), pressedMouseButtons];
|
||||
if mouse_buttons_down == 0 {
|
||||
// Point is outside of the client area (view) and no buttons are pressed
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let x = view_point.x as f64;
|
||||
let y = view_rect.size.height as f64 - view_point.y as f64;
|
||||
let logical_position = LogicalPosition::new(x, y);
|
||||
|
||||
update_potentially_stale_modifiers(state, event);
|
||||
|
||||
let window_event = Event::WindowEvent {
|
||||
window_id: WindowId(get_window_id(state.ns_window)),
|
||||
event: WindowEvent::CursorMoved {
|
||||
@@ -918,7 +957,7 @@ extern "C" fn other_mouse_dragged(this: &Object, _sel: Sel, event: id) {
|
||||
mouse_motion(this, event);
|
||||
}
|
||||
|
||||
extern "C" fn mouse_entered(this: &Object, _sel: Sel, event: id) {
|
||||
extern "C" fn mouse_entered(this: &Object, _sel: Sel, _event: id) {
|
||||
trace!("Triggered `mouseEntered`");
|
||||
unsafe {
|
||||
let state_ptr: *mut c_void = *this.get_ivar("winitState");
|
||||
@@ -932,7 +971,6 @@ extern "C" fn mouse_entered(this: &Object, _sel: Sel, event: id) {
|
||||
};
|
||||
|
||||
AppState::queue_event(EventWrapper::StaticEvent(enter_event));
|
||||
mouse_motion(this, event);
|
||||
}
|
||||
trace!("Completed `mouseEntered`");
|
||||
}
|
||||
@@ -957,11 +995,19 @@ extern "C" fn mouse_exited(this: &Object, _sel: Sel, _event: id) {
|
||||
|
||||
extern "C" fn scroll_wheel(this: &Object, _sel: Sel, event: id) {
|
||||
trace!("Triggered `scrollWheel`");
|
||||
|
||||
mouse_motion(this, event);
|
||||
|
||||
unsafe {
|
||||
let state_ptr: *mut c_void = *this.get_ivar("winitState");
|
||||
let state = &mut *(state_ptr as *mut ViewState);
|
||||
|
||||
let delta = {
|
||||
let (x, y) = (event.scrollingDeltaX(), event.scrollingDeltaY());
|
||||
// macOS horizontal sign convention is the inverse of winit.
|
||||
let (x, y) = (event.scrollingDeltaX() * -1.0, event.scrollingDeltaY());
|
||||
if event.hasPreciseScrollingDeltas() == YES {
|
||||
MouseScrollDelta::PixelDelta((x as f64, y as f64).into())
|
||||
let delta = LogicalPosition::new(x, y).to_physical(state.get_scale_factor());
|
||||
MouseScrollDelta::PixelDelta(delta)
|
||||
} else {
|
||||
MouseScrollDelta::LineDelta(x as f32, y as f32)
|
||||
}
|
||||
@@ -982,6 +1028,8 @@ extern "C" fn scroll_wheel(this: &Object, _sel: Sel, event: id) {
|
||||
let state_ptr: *mut c_void = *this.get_ivar("winitState");
|
||||
let state = &mut *(state_ptr as *mut ViewState);
|
||||
|
||||
update_potentially_stale_modifiers(state, event);
|
||||
|
||||
let window_event = Event::WindowEvent {
|
||||
window_id: WindowId(get_window_id(state.ns_window)),
|
||||
event: WindowEvent::MouseWheel {
|
||||
@@ -1000,6 +1048,9 @@ extern "C" fn scroll_wheel(this: &Object, _sel: Sel, event: id) {
|
||||
|
||||
extern "C" fn pressure_change_with_event(this: &Object, _sel: Sel, event: id) {
|
||||
trace!("Triggered `pressureChangeWithEvent`");
|
||||
|
||||
mouse_motion(this, event);
|
||||
|
||||
unsafe {
|
||||
let state_ptr: *mut c_void = *this.get_ivar("winitState");
|
||||
let state = &mut *(state_ptr as *mut ViewState);
|
||||
|
||||
@@ -19,6 +19,7 @@ use crate::{
|
||||
platform::macos::{ActivationPolicy, RequestUserAttentionType, WindowExtMacOS},
|
||||
platform_impl::platform::{
|
||||
app_state::AppState,
|
||||
app_state::INTERRUPT_EVENT_LOOP_EXIT,
|
||||
ffi,
|
||||
monitor::{self, MonitorHandle, VideoMode},
|
||||
util::{self, IdRef},
|
||||
@@ -59,7 +60,7 @@ pub fn get_window_id(window_cocoa_id: id) -> Id {
|
||||
Id(window_cocoa_id as *const Object as _)
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Clone)]
|
||||
pub struct PlatformSpecificWindowBuilderAttributes {
|
||||
pub activation_policy: ActivationPolicy,
|
||||
pub movable_by_window_background: bool,
|
||||
@@ -70,6 +71,25 @@ pub struct PlatformSpecificWindowBuilderAttributes {
|
||||
pub fullsize_content_view: bool,
|
||||
pub resize_increments: Option<LogicalSize<f64>>,
|
||||
pub disallow_hidpi: bool,
|
||||
pub has_shadow: bool,
|
||||
}
|
||||
|
||||
impl Default for PlatformSpecificWindowBuilderAttributes {
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
activation_policy: Default::default(),
|
||||
movable_by_window_background: false,
|
||||
titlebar_transparent: false,
|
||||
title_hidden: false,
|
||||
titlebar_hidden: false,
|
||||
titlebar_buttons_hidden: false,
|
||||
fullsize_content_view: false,
|
||||
resize_increments: None,
|
||||
disallow_hidpi: false,
|
||||
has_shadow: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_app(activation_policy: ActivationPolicy) -> Option<id> {
|
||||
@@ -122,13 +142,14 @@ fn create_window(
|
||||
unsafe {
|
||||
let pool = NSAutoreleasePool::new(nil);
|
||||
let screen = match attrs.fullscreen {
|
||||
Some(Fullscreen::Borderless(RootMonitorHandle { inner: ref monitor }))
|
||||
Some(Fullscreen::Borderless(Some(RootMonitorHandle { inner: ref monitor })))
|
||||
| Some(Fullscreen::Exclusive(RootVideoMode {
|
||||
video_mode: VideoMode { ref monitor, .. },
|
||||
})) => {
|
||||
let monitor_screen = monitor.ns_screen();
|
||||
Some(monitor_screen.unwrap_or(appkit::NSScreen::mainScreen(nil)))
|
||||
}
|
||||
Some(Fullscreen::Borderless(None)) => Some(appkit::NSScreen::mainScreen(nil)),
|
||||
None => None,
|
||||
};
|
||||
let frame = match screen {
|
||||
@@ -223,6 +244,10 @@ fn create_window(
|
||||
}
|
||||
}
|
||||
|
||||
if !pl_attrs.has_shadow {
|
||||
ns_window.setHasShadow_(NO);
|
||||
}
|
||||
|
||||
ns_window.center();
|
||||
ns_window
|
||||
});
|
||||
@@ -340,7 +365,7 @@ impl UnownedWindow {
|
||||
|
||||
let input_context = unsafe { util::create_input_context(*ns_view) };
|
||||
|
||||
let dpi_factor = unsafe { NSWindow::backingScaleFactor(*ns_window) as f64 };
|
||||
let scale_factor = unsafe { NSWindow::backingScaleFactor(*ns_window) as f64 };
|
||||
|
||||
unsafe {
|
||||
if win_attribs.transparent {
|
||||
@@ -350,11 +375,11 @@ impl UnownedWindow {
|
||||
|
||||
ns_app.activateIgnoringOtherApps_(YES);
|
||||
win_attribs.min_inner_size.map(|dim| {
|
||||
let logical_dim = dim.to_logical(dpi_factor);
|
||||
let logical_dim = dim.to_logical(scale_factor);
|
||||
set_min_inner_size(*ns_window, logical_dim)
|
||||
});
|
||||
win_attribs.max_inner_size.map(|dim| {
|
||||
let logical_dim = dim.to_logical(dpi_factor);
|
||||
let logical_dim = dim.to_logical(scale_factor);
|
||||
set_max_inner_size(*ns_window, logical_dim)
|
||||
});
|
||||
|
||||
@@ -378,7 +403,7 @@ impl UnownedWindow {
|
||||
let decorations = win_attribs.decorations;
|
||||
let inner_rect = win_attribs
|
||||
.inner_size
|
||||
.map(|size| size.to_physical(dpi_factor));
|
||||
.map(|size| size.to_physical(scale_factor));
|
||||
|
||||
let window = Arc::new(UnownedWindow {
|
||||
ns_view,
|
||||
@@ -450,8 +475,8 @@ impl UnownedWindow {
|
||||
frame_rect.origin.x as f64,
|
||||
util::bottom_left_to_top_left(frame_rect),
|
||||
);
|
||||
let dpi_factor = self.scale_factor();
|
||||
Ok(position.to_physical(dpi_factor))
|
||||
let scale_factor = self.scale_factor();
|
||||
Ok(position.to_physical(scale_factor))
|
||||
}
|
||||
|
||||
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
@@ -462,13 +487,13 @@ impl UnownedWindow {
|
||||
content_rect.origin.x as f64,
|
||||
util::bottom_left_to_top_left(content_rect),
|
||||
);
|
||||
let dpi_factor = self.scale_factor();
|
||||
Ok(position.to_physical(dpi_factor))
|
||||
let scale_factor = self.scale_factor();
|
||||
Ok(position.to_physical(scale_factor))
|
||||
}
|
||||
|
||||
pub fn set_outer_position(&self, position: Position) {
|
||||
let dpi_factor = self.scale_factor();
|
||||
let position = position.to_logical(dpi_factor);
|
||||
let scale_factor = self.scale_factor();
|
||||
let position = position.to_logical(scale_factor);
|
||||
let dummy = NSRect::new(
|
||||
NSPoint::new(
|
||||
position.x,
|
||||
@@ -488,8 +513,8 @@ impl UnownedWindow {
|
||||
let view_frame = unsafe { NSView::frame(*self.ns_view) };
|
||||
let logical: LogicalSize<f64> =
|
||||
(view_frame.size.width as f64, view_frame.size.height as f64).into();
|
||||
let dpi_factor = self.scale_factor();
|
||||
logical.to_physical(dpi_factor)
|
||||
let scale_factor = self.scale_factor();
|
||||
logical.to_physical(scale_factor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -497,15 +522,15 @@ impl UnownedWindow {
|
||||
let view_frame = unsafe { NSWindow::frame(*self.ns_window) };
|
||||
let logical: LogicalSize<f64> =
|
||||
(view_frame.size.width as f64, view_frame.size.height as f64).into();
|
||||
let dpi_factor = self.scale_factor();
|
||||
logical.to_physical(dpi_factor)
|
||||
let scale_factor = self.scale_factor();
|
||||
logical.to_physical(scale_factor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_inner_size(&self, size: Size) {
|
||||
unsafe {
|
||||
let dpi_factor = self.scale_factor();
|
||||
util::set_content_size_async(*self.ns_window, size.to_logical(dpi_factor));
|
||||
let scale_factor = self.scale_factor();
|
||||
util::set_content_size_async(*self.ns_window, size.to_logical(scale_factor));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -515,8 +540,8 @@ impl UnownedWindow {
|
||||
width: 0.0,
|
||||
height: 0.0,
|
||||
}));
|
||||
let dpi_factor = self.scale_factor();
|
||||
set_min_inner_size(*self.ns_window, dimensions.to_logical(dpi_factor));
|
||||
let scale_factor = self.scale_factor();
|
||||
set_min_inner_size(*self.ns_window, dimensions.to_logical(scale_factor));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -526,8 +551,8 @@ impl UnownedWindow {
|
||||
width: std::f32::MAX as f64,
|
||||
height: std::f32::MAX as f64,
|
||||
}));
|
||||
let dpi_factor = self.scale_factor();
|
||||
set_max_inner_size(*self.ns_window, dimensions.to_logical(dpi_factor));
|
||||
let scale_factor = self.scale_factor();
|
||||
set_max_inner_size(*self.ns_window, dimensions.to_logical(scale_factor));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -594,9 +619,9 @@ impl UnownedWindow {
|
||||
#[inline]
|
||||
pub fn set_cursor_position(&self, cursor_position: Position) -> Result<(), ExternalError> {
|
||||
let physical_window_position = self.inner_position().unwrap();
|
||||
let dpi_factor = self.scale_factor();
|
||||
let window_position = physical_window_position.to_logical::<CGFloat>(dpi_factor);
|
||||
let logical_cursor_position = cursor_position.to_logical::<CGFloat>(dpi_factor);
|
||||
let scale_factor = self.scale_factor();
|
||||
let window_position = physical_window_position.to_logical::<CGFloat>(scale_factor);
|
||||
let logical_cursor_position = cursor_position.to_logical::<CGFloat>(scale_factor);
|
||||
let point = appkit::CGPoint {
|
||||
x: logical_cursor_position.x + window_position.x,
|
||||
y: logical_cursor_position.y + window_position.y,
|
||||
@@ -731,10 +756,15 @@ impl UnownedWindow {
|
||||
// does not take a screen parameter, but uses the current screen)
|
||||
if let Some(ref fullscreen) = fullscreen {
|
||||
let new_screen = match fullscreen {
|
||||
Fullscreen::Borderless(RootMonitorHandle { inner: ref monitor }) => monitor,
|
||||
Fullscreen::Borderless(borderless) => {
|
||||
let RootMonitorHandle { inner: monitor } = borderless
|
||||
.clone()
|
||||
.unwrap_or_else(|| self.current_monitor_inner());
|
||||
monitor
|
||||
}
|
||||
Fullscreen::Exclusive(RootVideoMode {
|
||||
video_mode: VideoMode { ref monitor, .. },
|
||||
}) => monitor,
|
||||
}) => monitor.clone(),
|
||||
}
|
||||
.ns_screen()
|
||||
.unwrap();
|
||||
@@ -820,6 +850,8 @@ impl UnownedWindow {
|
||||
shared_state_lock.fullscreen = fullscreen.clone();
|
||||
trace!("Unlocked shared state in `set_fullscreen`");
|
||||
|
||||
INTERRUPT_EVENT_LOOP_EXIT.store(true, Ordering::SeqCst);
|
||||
|
||||
match (&old_fullscreen, &fullscreen) {
|
||||
(&None, &Some(_)) => unsafe {
|
||||
util::toggle_full_screen_async(
|
||||
@@ -865,7 +897,7 @@ impl UnownedWindow {
|
||||
) => unsafe {
|
||||
util::restore_display_mode_async(video_mode.monitor().inner.native_identifier());
|
||||
},
|
||||
_ => (),
|
||||
_ => INTERRUPT_EVENT_LOOP_EXIT.store(false, Ordering::SeqCst),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -933,8 +965,8 @@ impl UnownedWindow {
|
||||
|
||||
#[inline]
|
||||
pub fn set_ime_position(&self, spot: Position) {
|
||||
let dpi_factor = self.scale_factor();
|
||||
let logical_spot = spot.to_logical(dpi_factor);
|
||||
let scale_factor = self.scale_factor();
|
||||
let logical_spot = spot.to_logical(scale_factor);
|
||||
unsafe {
|
||||
view::set_ime_position(
|
||||
*self.ns_view,
|
||||
@@ -946,7 +978,8 @@ impl UnownedWindow {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn current_monitor(&self) -> RootMonitorHandle {
|
||||
// Allow directly accessing the current monitor internally without unwrapping.
|
||||
pub(crate) fn current_monitor_inner(&self) -> RootMonitorHandle {
|
||||
unsafe {
|
||||
let screen: id = msg_send![*self.ns_window, screen];
|
||||
let desc = NSScreen::deviceDescription(screen);
|
||||
@@ -959,14 +992,20 @@ impl UnownedWindow {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn current_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
Some(self.current_monitor_inner())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
monitor::available_monitors()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> MonitorHandle {
|
||||
monitor::primary_monitor()
|
||||
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
|
||||
let monitor = monitor::primary_monitor();
|
||||
Some(RootMonitorHandle { inner: monitor })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -1028,7 +1067,11 @@ impl WindowExtMacOS for UnownedWindow {
|
||||
|
||||
if fullscreen {
|
||||
// Remember the original window's settings
|
||||
shared_state_lock.standard_frame = Some(NSWindow::frame(*self.ns_window));
|
||||
// Exclude title bar
|
||||
shared_state_lock.standard_frame = Some(NSWindow::contentRectForFrameRect_(
|
||||
*self.ns_window,
|
||||
NSWindow::frame(*self.ns_window),
|
||||
));
|
||||
shared_state_lock.saved_style = Some(self.ns_window.styleMask());
|
||||
shared_state_lock.save_presentation_opts = Some(app.presentationOptions_());
|
||||
|
||||
@@ -1087,6 +1130,19 @@ impl WindowExtMacOS for UnownedWindow {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn has_shadow(&self) -> bool {
|
||||
unsafe { self.ns_window.hasShadow() == YES }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_has_shadow(&self, has_shadow: bool) {
|
||||
unsafe {
|
||||
self.ns_window
|
||||
.setHasShadow_(if has_shadow { YES } else { NO })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for UnownedWindow {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::{
|
||||
f64,
|
||||
os::raw::c_void,
|
||||
sync::{Arc, Weak},
|
||||
sync::{atomic::Ordering, Arc, Weak},
|
||||
};
|
||||
|
||||
use cocoa::{
|
||||
@@ -15,12 +15,14 @@ use objc::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
dpi::LogicalSize,
|
||||
event::{Event, WindowEvent},
|
||||
dpi::{LogicalPosition, LogicalSize},
|
||||
event::{Event, ModifiersState, WindowEvent},
|
||||
platform_impl::platform::{
|
||||
app_state::AppState,
|
||||
app_state::INTERRUPT_EVENT_LOOP_EXIT,
|
||||
event::{EventProxy, EventWrapper},
|
||||
util::{self, IdRef},
|
||||
view::ViewState,
|
||||
window::{get_window_id, UnownedWindow},
|
||||
},
|
||||
window::{Fullscreen, WindowId},
|
||||
@@ -43,7 +45,7 @@ pub struct WindowDelegateState {
|
||||
previous_position: Option<(f64, f64)>,
|
||||
|
||||
// Used to prevent redundant events.
|
||||
previous_dpi_factor: f64,
|
||||
previous_scale_factor: f64,
|
||||
}
|
||||
|
||||
impl WindowDelegateState {
|
||||
@@ -55,7 +57,7 @@ impl WindowDelegateState {
|
||||
window: Arc::downgrade(&window),
|
||||
initial_fullscreen,
|
||||
previous_position: None,
|
||||
previous_dpi_factor: scale_factor,
|
||||
previous_scale_factor: scale_factor,
|
||||
};
|
||||
|
||||
if scale_factor != 1.0 {
|
||||
@@ -82,11 +84,11 @@ impl WindowDelegateState {
|
||||
|
||||
pub fn emit_static_scale_factor_changed_event(&mut self) {
|
||||
let scale_factor = self.get_scale_factor();
|
||||
if scale_factor == self.previous_dpi_factor {
|
||||
if scale_factor == self.previous_scale_factor {
|
||||
return ();
|
||||
};
|
||||
|
||||
self.previous_dpi_factor = scale_factor;
|
||||
self.previous_scale_factor = scale_factor;
|
||||
let wrapper = EventWrapper::EventProxy(EventProxy::DpiChangedProxy {
|
||||
ns_window: IdRef::retain(*self.ns_window),
|
||||
suggested_size: self.view_size(),
|
||||
@@ -110,7 +112,9 @@ impl WindowDelegateState {
|
||||
let moved = self.previous_position != Some((x, y));
|
||||
if moved {
|
||||
self.previous_position = Some((x, y));
|
||||
self.emit_event(WindowEvent::Moved((x, y).into()));
|
||||
let scale_factor = self.get_scale_factor();
|
||||
let physical_pos = LogicalPosition::<f64>::from((x, y)).to_physical(scale_factor);
|
||||
self.emit_event(WindowEvent::Moved(physical_pos));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,6 +323,29 @@ extern "C" fn window_did_become_key(this: &Object, _: Sel, _: id) {
|
||||
extern "C" fn window_did_resign_key(this: &Object, _: Sel, _: id) {
|
||||
trace!("Triggered `windowDidResignKey:`");
|
||||
with_state(this, |state| {
|
||||
// It happens rather often, e.g. when the user is Cmd+Tabbing, that the
|
||||
// NSWindowDelegate will receive a didResignKey event despite no event
|
||||
// being received when the modifiers are released. This is because
|
||||
// flagsChanged events are received by the NSView instead of the
|
||||
// NSWindowDelegate, and as a result a tracked modifiers state can quite
|
||||
// easily fall out of synchrony with reality. This requires us to emit
|
||||
// a synthetic ModifiersChanged event when we lose focus.
|
||||
//
|
||||
// Here we (very unsafely) acquire the winitState (a ViewState) from the
|
||||
// Object referenced by state.ns_view (an IdRef, which is dereferenced
|
||||
// to an id)
|
||||
let view_state: &mut ViewState = unsafe {
|
||||
let ns_view: &Object = (*state.ns_view).as_ref().expect("failed to deref");
|
||||
let state_ptr: *mut c_void = *ns_view.get_ivar("winitState");
|
||||
&mut *(state_ptr as *mut ViewState)
|
||||
};
|
||||
|
||||
// Both update the state and emit a ModifiersChanged event.
|
||||
if !view_state.modifiers.is_empty() {
|
||||
view_state.modifiers = ModifiersState::empty();
|
||||
state.emit_event(WindowEvent::ModifiersChanged(view_state.modifiers));
|
||||
}
|
||||
|
||||
state.emit_event(WindowEvent::Focused(false));
|
||||
});
|
||||
trace!("Completed `windowDidResignKey:`");
|
||||
@@ -405,6 +432,9 @@ extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
|
||||
/// Invoked when before enter fullscreen
|
||||
extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
|
||||
trace!("Triggered `windowWillEnterFullscreen:`");
|
||||
|
||||
INTERRUPT_EVENT_LOOP_EXIT.store(true, Ordering::SeqCst);
|
||||
|
||||
with_state(this, |state| {
|
||||
state.with_window(|window| {
|
||||
trace!("Locked shared state in `window_will_enter_fullscreen`");
|
||||
@@ -422,7 +452,8 @@ extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
|
||||
// Otherwise, we must've reached fullscreen by the user clicking
|
||||
// on the green fullscreen button. Update state!
|
||||
None => {
|
||||
shared_state.fullscreen = Some(Fullscreen::Borderless(window.current_monitor()))
|
||||
let current_monitor = Some(window.current_monitor_inner());
|
||||
shared_state.fullscreen = Some(Fullscreen::Borderless(current_monitor))
|
||||
}
|
||||
}
|
||||
shared_state.in_fullscreen_transition = true;
|
||||
@@ -435,6 +466,9 @@ extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
|
||||
/// Invoked when before exit fullscreen
|
||||
extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
|
||||
trace!("Triggered `windowWillExitFullScreen:`");
|
||||
|
||||
INTERRUPT_EVENT_LOOP_EXIT.store(true, Ordering::SeqCst);
|
||||
|
||||
with_state(this, |state| {
|
||||
state.with_window(|window| {
|
||||
trace!("Locked shared state in `window_will_exit_fullscreen`");
|
||||
@@ -468,6 +502,8 @@ extern "C" fn window_will_use_fullscreen_presentation_options(
|
||||
|
||||
/// Invoked when entered fullscreen
|
||||
extern "C" fn window_did_enter_fullscreen(this: &Object, _: Sel, _: id) {
|
||||
INTERRUPT_EVENT_LOOP_EXIT.store(false, Ordering::SeqCst);
|
||||
|
||||
trace!("Triggered `windowDidEnterFullscreen:`");
|
||||
with_state(this, |state| {
|
||||
state.initial_fullscreen = false;
|
||||
@@ -488,6 +524,8 @@ extern "C" fn window_did_enter_fullscreen(this: &Object, _: Sel, _: id) {
|
||||
|
||||
/// Invoked when exited fullscreen
|
||||
extern "C" fn window_did_exit_fullscreen(this: &Object, _: Sel, _: id) {
|
||||
INTERRUPT_EVENT_LOOP_EXIT.store(false, Ordering::SeqCst);
|
||||
|
||||
trace!("Triggered `windowDidExitFullscreen:`");
|
||||
with_state(this, |state| {
|
||||
state.with_window(|window| {
|
||||
|
||||
@@ -6,11 +6,10 @@ mod window_target;
|
||||
pub use self::proxy::Proxy;
|
||||
pub use self::window_target::WindowTarget;
|
||||
|
||||
use super::{backend, device, monitor, window};
|
||||
use super::{backend, device, window};
|
||||
use crate::event::Event;
|
||||
use crate::event_loop as root;
|
||||
|
||||
use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
pub struct EventLoop<T: 'static> {
|
||||
@@ -27,18 +26,9 @@ impl<T> EventLoop<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDequeIter<monitor::Handle> {
|
||||
VecDeque::new().into_iter()
|
||||
}
|
||||
|
||||
pub fn primary_monitor(&self) -> monitor::Handle {
|
||||
monitor::Handle
|
||||
}
|
||||
|
||||
pub fn run<F>(self, mut event_handler: F) -> !
|
||||
where
|
||||
F: 'static
|
||||
+ FnMut(Event<'static, T>, &root::EventLoopWindowTarget<T>, &mut root::ControlFlow),
|
||||
F: 'static + FnMut(Event<'_, T>, &root::EventLoopWindowTarget<T>, &mut root::ControlFlow),
|
||||
{
|
||||
let target = root::EventLoopWindowTarget {
|
||||
p: self.elw.p.clone(),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{backend, state::State};
|
||||
use super::{super::ScaleChangeArgs, backend, state::State};
|
||||
use crate::event::{Event, StartCause};
|
||||
use crate::event_loop as root;
|
||||
use crate::window::WindowId;
|
||||
@@ -9,7 +9,8 @@ use std::{
|
||||
clone::Clone,
|
||||
collections::{HashSet, VecDeque},
|
||||
iter,
|
||||
rc::Rc,
|
||||
ops::Deref,
|
||||
rc::{Rc, Weak},
|
||||
};
|
||||
|
||||
pub struct Shared<T: 'static>(Rc<Execution<T>>);
|
||||
@@ -21,50 +22,129 @@ impl<T> Clone for Shared<T> {
|
||||
}
|
||||
|
||||
pub struct Execution<T: 'static> {
|
||||
runner: RefCell<Option<Runner<T>>>,
|
||||
runner: RefCell<RunnerEnum<T>>,
|
||||
events: RefCell<VecDeque<Event<'static, T>>>,
|
||||
id: RefCell<u32>,
|
||||
all_canvases: RefCell<Vec<(WindowId, Weak<RefCell<backend::Canvas>>)>>,
|
||||
redraw_pending: RefCell<HashSet<WindowId>>,
|
||||
destroy_pending: RefCell<VecDeque<WindowId>>,
|
||||
scale_change_detector: RefCell<Option<backend::ScaleChangeDetector>>,
|
||||
unload_event_handle: RefCell<Option<backend::UnloadEventHandle>>,
|
||||
}
|
||||
|
||||
enum RunnerEnum<T: 'static> {
|
||||
/// The `EventLoop` is created but not being run.
|
||||
Pending,
|
||||
/// The `EventLoop` is being run.
|
||||
Running(Runner<T>),
|
||||
/// The `EventLoop` is exited after being started with `EventLoop::run`. Since
|
||||
/// `EventLoop::run` takes ownership of the `EventLoop`, we can be certain
|
||||
/// that this event loop will never be run again.
|
||||
Destroyed,
|
||||
}
|
||||
|
||||
impl<T: 'static> RunnerEnum<T> {
|
||||
fn maybe_runner(&self) -> Option<&Runner<T>> {
|
||||
match self {
|
||||
RunnerEnum::Running(runner) => Some(runner),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Runner<T: 'static> {
|
||||
state: State,
|
||||
is_busy: bool,
|
||||
event_handler: Box<dyn FnMut(Event<'static, T>, &mut root::ControlFlow)>,
|
||||
event_handler: Box<dyn FnMut(Event<'_, T>, &mut root::ControlFlow)>,
|
||||
}
|
||||
|
||||
impl<T: 'static> Runner<T> {
|
||||
pub fn new(event_handler: Box<dyn FnMut(Event<'static, T>, &mut root::ControlFlow)>) -> Self {
|
||||
pub fn new(event_handler: Box<dyn FnMut(Event<'_, T>, &mut root::ControlFlow)>) -> Self {
|
||||
Runner {
|
||||
state: State::Init,
|
||||
is_busy: false,
|
||||
event_handler,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the cooresponding `StartCause` for the current `state`, or `None`
|
||||
/// when in `Exit` state.
|
||||
fn maybe_start_cause(&self) -> Option<StartCause> {
|
||||
Some(match self.state {
|
||||
State::Init => StartCause::Init,
|
||||
State::Poll { .. } => StartCause::Poll,
|
||||
State::Wait { start } => StartCause::WaitCancelled {
|
||||
start,
|
||||
requested_resume: None,
|
||||
},
|
||||
State::WaitUntil { start, end, .. } => StartCause::WaitCancelled {
|
||||
start,
|
||||
requested_resume: Some(end),
|
||||
},
|
||||
State::Exit => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn handle_single_event(&mut self, event: Event<'_, T>, control: &mut root::ControlFlow) {
|
||||
let is_closed = *control == root::ControlFlow::Exit;
|
||||
|
||||
(self.event_handler)(event, control);
|
||||
|
||||
// Maintain closed state, even if the callback changes it
|
||||
if is_closed {
|
||||
*control = root::ControlFlow::Exit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> Shared<T> {
|
||||
pub fn new() -> Self {
|
||||
Shared(Rc::new(Execution {
|
||||
runner: RefCell::new(None),
|
||||
runner: RefCell::new(RunnerEnum::Pending),
|
||||
events: RefCell::new(VecDeque::new()),
|
||||
id: RefCell::new(0),
|
||||
all_canvases: RefCell::new(Vec::new()),
|
||||
redraw_pending: RefCell::new(HashSet::new()),
|
||||
destroy_pending: RefCell::new(VecDeque::new()),
|
||||
scale_change_detector: RefCell::new(None),
|
||||
unload_event_handle: RefCell::new(None),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn add_canvas(&self, id: WindowId, canvas: &Rc<RefCell<backend::Canvas>>) {
|
||||
self.0
|
||||
.all_canvases
|
||||
.borrow_mut()
|
||||
.push((id, Rc::downgrade(canvas)));
|
||||
}
|
||||
|
||||
pub fn notify_destroy_window(&self, id: WindowId) {
|
||||
self.0.destroy_pending.borrow_mut().push_back(id);
|
||||
}
|
||||
|
||||
// Set the event callback to use for the event loop runner
|
||||
// This the event callback is a fairly thin layer over the user-provided callback that closes
|
||||
// over a RootEventLoopWindowTarget reference
|
||||
pub fn set_listener(
|
||||
&self,
|
||||
event_handler: Box<dyn FnMut(Event<'static, T>, &mut root::ControlFlow)>,
|
||||
event_handler: Box<dyn FnMut(Event<'_, T>, &mut root::ControlFlow)>,
|
||||
) {
|
||||
self.0.runner.replace(Some(Runner::new(event_handler)));
|
||||
{
|
||||
let mut runner = self.0.runner.borrow_mut();
|
||||
assert!(matches!(*runner, RunnerEnum::Pending));
|
||||
*runner = RunnerEnum::Running(Runner::new(event_handler));
|
||||
}
|
||||
self.init();
|
||||
|
||||
let close_instance = self.clone();
|
||||
backend::on_unload(move || close_instance.handle_unload());
|
||||
*self.0.unload_event_handle.borrow_mut() =
|
||||
Some(backend::on_unload(move || close_instance.handle_unload()));
|
||||
}
|
||||
|
||||
pub(crate) fn set_on_scale_change<F>(&self, handler: F)
|
||||
where
|
||||
F: 'static + FnMut(ScaleChangeArgs),
|
||||
{
|
||||
*self.0.scale_change_detector.borrow_mut() =
|
||||
Some(backend::ScaleChangeDetector::new(handler));
|
||||
}
|
||||
|
||||
// Generate a strictly increasing ID
|
||||
@@ -118,18 +198,25 @@ impl<T: 'static> Shared<T> {
|
||||
}
|
||||
// If we can run the event processing right now, or need to queue this and wait for later
|
||||
let mut process_immediately = true;
|
||||
if let Some(ref runner) = &*self.0.runner.borrow() {
|
||||
// If we're currently polling, queue this and wait for the poll() method to be called
|
||||
if let State::Poll { .. } = runner.state {
|
||||
match self.0.runner.try_borrow().as_ref().map(Deref::deref) {
|
||||
Ok(RunnerEnum::Running(ref runner)) => {
|
||||
// If we're currently polling, queue this and wait for the poll() method to be called
|
||||
if let State::Poll { .. } = runner.state {
|
||||
process_immediately = false;
|
||||
}
|
||||
}
|
||||
Ok(RunnerEnum::Pending) => {
|
||||
// The runner still hasn't been attached: queue this event and wait for it to be
|
||||
process_immediately = false;
|
||||
}
|
||||
// If the runner is busy, queue this and wait for it to process it later
|
||||
if runner.is_busy {
|
||||
// Some other code is mutating the runner, which most likely means
|
||||
// the event loop is running and busy. So we queue this event for
|
||||
// it to be processed later.
|
||||
Err(_) => {
|
||||
process_immediately = false;
|
||||
}
|
||||
} else {
|
||||
// The runner still hasn't been attached: queue this event and wait for it to be
|
||||
process_immediately = false;
|
||||
// This is unreachable since `self.is_closed() == true`.
|
||||
Ok(RunnerEnum::Destroyed) => unreachable!(),
|
||||
}
|
||||
if !process_immediately {
|
||||
// Queue these events to look at later
|
||||
@@ -138,25 +225,15 @@ impl<T: 'static> Shared<T> {
|
||||
}
|
||||
// At this point, we know this is a fresh set of events
|
||||
// Now we determine why new events are incoming, and handle the events
|
||||
let start_cause = if let Some(runner) = &*self.0.runner.borrow() {
|
||||
match runner.state {
|
||||
State::Init => StartCause::Init,
|
||||
State::Poll { .. } => StartCause::Poll,
|
||||
State::Wait { start } => StartCause::WaitCancelled {
|
||||
start,
|
||||
requested_resume: None,
|
||||
},
|
||||
State::WaitUntil { start, end, .. } => StartCause::WaitCancelled {
|
||||
start,
|
||||
requested_resume: Some(end),
|
||||
},
|
||||
State::Exit => {
|
||||
// If we're in the exit state, don't do event processing
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unreachable!("The runner cannot process events when it is not attached");
|
||||
let start_cause = match (self.0.runner.borrow().maybe_runner())
|
||||
.unwrap_or_else(|| {
|
||||
unreachable!("The runner cannot process events when it is not attached")
|
||||
})
|
||||
.maybe_start_cause()
|
||||
{
|
||||
Some(c) => c,
|
||||
// If we're in the exit state, don't do event processing
|
||||
None => return,
|
||||
};
|
||||
// Take the start event, then the events provided to this function, and run an iteration of
|
||||
// the event loop
|
||||
@@ -165,6 +242,26 @@ impl<T: 'static> Shared<T> {
|
||||
self.run_until_cleared(events);
|
||||
}
|
||||
|
||||
// Process the destroy-pending windows. This should only be called from
|
||||
// `run_until_cleared` and `handle_scale_changed`, somewhere between emitting
|
||||
// `NewEvents` and `MainEventsCleared`.
|
||||
fn process_destroy_pending_windows(&self, control: &mut root::ControlFlow) {
|
||||
while let Some(id) = self.0.destroy_pending.borrow_mut().pop_front() {
|
||||
self.0
|
||||
.all_canvases
|
||||
.borrow_mut()
|
||||
.retain(|&(item_id, _)| item_id != id);
|
||||
self.handle_event(
|
||||
Event::WindowEvent {
|
||||
window_id: id,
|
||||
event: crate::event::WindowEvent::Destroyed,
|
||||
},
|
||||
control,
|
||||
);
|
||||
self.0.redraw_pending.borrow_mut().remove(&id);
|
||||
}
|
||||
}
|
||||
|
||||
// Given the set of new events, run the event loop until the main events and redraw events are
|
||||
// cleared
|
||||
//
|
||||
@@ -174,6 +271,7 @@ impl<T: 'static> Shared<T> {
|
||||
for event in events {
|
||||
self.handle_event(event, &mut control);
|
||||
}
|
||||
self.process_destroy_pending_windows(&mut control);
|
||||
self.handle_event(Event::MainEventsCleared, &mut control);
|
||||
|
||||
// Collect all of the redraw events to avoid double-locking the RefCell
|
||||
@@ -187,47 +285,139 @@ impl<T: 'static> Shared<T> {
|
||||
// If the event loop is closed, it has been closed this iteration and now the closing
|
||||
// event should be emitted
|
||||
if self.is_closed() {
|
||||
self.handle_event(Event::LoopDestroyed, &mut control);
|
||||
self.handle_loop_destroyed(&mut control);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_scale_changed(&self, old_scale: f64, new_scale: f64) {
|
||||
// If there aren't any windows, then there is nothing to do here.
|
||||
if self.0.all_canvases.borrow().is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let start_cause = match (self.0.runner.borrow().maybe_runner())
|
||||
.unwrap_or_else(|| unreachable!("`scale_changed` should not happen without a runner"))
|
||||
.maybe_start_cause()
|
||||
{
|
||||
Some(c) => c,
|
||||
// If we're in the exit state, don't do event processing
|
||||
None => return,
|
||||
};
|
||||
let mut control = self.current_control_flow();
|
||||
|
||||
// Handle the start event and all other events in the queue.
|
||||
self.handle_event(Event::NewEvents(start_cause), &mut control);
|
||||
|
||||
// It is possible for windows to be dropped before this point. We don't
|
||||
// want to send `ScaleFactorChanged` for destroyed windows, so we process
|
||||
// the destroy-pending windows here.
|
||||
self.process_destroy_pending_windows(&mut control);
|
||||
|
||||
// Now handle the `ScaleFactorChanged` events.
|
||||
for &(id, ref canvas) in &*self.0.all_canvases.borrow() {
|
||||
let canvas = match canvas.upgrade() {
|
||||
Some(rc) => rc.borrow().raw().clone(),
|
||||
// This shouldn't happen, but just in case...
|
||||
None => continue,
|
||||
};
|
||||
// First, we send the `ScaleFactorChanged` event:
|
||||
let current_size = crate::dpi::PhysicalSize {
|
||||
width: canvas.width() as u32,
|
||||
height: canvas.height() as u32,
|
||||
};
|
||||
let logical_size = current_size.to_logical::<f64>(old_scale);
|
||||
let mut new_size = logical_size.to_physical(new_scale);
|
||||
self.handle_single_event_sync(
|
||||
Event::WindowEvent {
|
||||
window_id: id,
|
||||
event: crate::event::WindowEvent::ScaleFactorChanged {
|
||||
scale_factor: new_scale,
|
||||
new_inner_size: &mut new_size,
|
||||
},
|
||||
},
|
||||
&mut control,
|
||||
);
|
||||
|
||||
// Then we resize the canvas to the new size and send a `Resized` event:
|
||||
backend::set_canvas_size(&canvas, crate::dpi::Size::Physical(new_size));
|
||||
self.handle_single_event_sync(
|
||||
Event::WindowEvent {
|
||||
window_id: id,
|
||||
event: crate::event::WindowEvent::Resized(new_size),
|
||||
},
|
||||
&mut control,
|
||||
);
|
||||
}
|
||||
|
||||
// Process the destroy-pending windows again.
|
||||
self.process_destroy_pending_windows(&mut control);
|
||||
self.handle_event(Event::MainEventsCleared, &mut control);
|
||||
|
||||
// Discard all the pending redraw as we shall just redraw all windows.
|
||||
self.0.redraw_pending.borrow_mut().clear();
|
||||
for &(window_id, _) in &*self.0.all_canvases.borrow() {
|
||||
self.handle_event(Event::RedrawRequested(window_id), &mut control);
|
||||
}
|
||||
self.handle_event(Event::RedrawEventsCleared, &mut control);
|
||||
|
||||
self.apply_control_flow(control);
|
||||
// If the event loop is closed, it has been closed this iteration and now the closing
|
||||
// event should be emitted
|
||||
if self.is_closed() {
|
||||
self.handle_loop_destroyed(&mut control);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_unload(&self) {
|
||||
self.apply_control_flow(root::ControlFlow::Exit);
|
||||
let mut control = self.current_control_flow();
|
||||
// We don't call `handle_loop_destroyed` here because we don't need to
|
||||
// perform cleanup when the web browser is going to destroy the page.
|
||||
self.handle_event(Event::LoopDestroyed, &mut control);
|
||||
}
|
||||
|
||||
// handle_single_event_sync takes in an event and handles it synchronously.
|
||||
//
|
||||
// It should only ever be called from `scale_changed`.
|
||||
fn handle_single_event_sync(&self, event: Event<'_, T>, control: &mut root::ControlFlow) {
|
||||
if self.is_closed() {
|
||||
*control = root::ControlFlow::Exit;
|
||||
}
|
||||
match *self.0.runner.borrow_mut() {
|
||||
RunnerEnum::Running(ref mut runner) => {
|
||||
runner.handle_single_event(event, control);
|
||||
}
|
||||
_ => panic!("Cannot handle event synchronously without a runner"),
|
||||
}
|
||||
}
|
||||
|
||||
// handle_event takes in events and either queues them or applies a callback
|
||||
//
|
||||
// It should only ever be called from send_event
|
||||
// It should only ever be called from `run_until_cleared` and `scale_changed`.
|
||||
fn handle_event(&self, event: Event<'static, T>, control: &mut root::ControlFlow) {
|
||||
let is_closed = self.is_closed();
|
||||
|
||||
if self.is_closed() {
|
||||
*control = root::ControlFlow::Exit;
|
||||
}
|
||||
match *self.0.runner.borrow_mut() {
|
||||
Some(ref mut runner) => {
|
||||
// An event is being processed, so the runner should be marked busy
|
||||
runner.is_busy = true;
|
||||
|
||||
(runner.event_handler)(event, control);
|
||||
|
||||
// Maintain closed state, even if the callback changes it
|
||||
if is_closed {
|
||||
*control = root::ControlFlow::Exit;
|
||||
}
|
||||
|
||||
// An event is no longer being processed
|
||||
runner.is_busy = false;
|
||||
RunnerEnum::Running(ref mut runner) => {
|
||||
runner.handle_single_event(event, control);
|
||||
}
|
||||
// If an event is being handled without a runner somehow, add it to the event queue so
|
||||
// it will eventually be processed
|
||||
_ => self.0.events.borrow_mut().push_back(event),
|
||||
RunnerEnum::Pending => self.0.events.borrow_mut().push_back(event),
|
||||
// If the Runner has been destroyed, there is nothing to do.
|
||||
RunnerEnum::Destroyed => return,
|
||||
}
|
||||
|
||||
let is_closed = *control == root::ControlFlow::Exit;
|
||||
|
||||
// Don't take events out of the queue if the loop is closed or the runner doesn't exist
|
||||
// If the runner doesn't exist and this method recurses, it will recurse infinitely
|
||||
if !is_closed && self.0.runner.borrow().is_some() {
|
||||
if !is_closed && self.0.runner.borrow().maybe_runner().is_some() {
|
||||
// Take an event out of the queue and handle it
|
||||
if let Some(event) = self.0.events.borrow_mut().pop_front() {
|
||||
// Make sure not to let the borrow_mut live during the next handle_event
|
||||
let event = { self.0.events.borrow_mut().pop_front() };
|
||||
if let Some(event) = event {
|
||||
self.handle_event(event, control);
|
||||
}
|
||||
}
|
||||
@@ -240,7 +430,7 @@ impl<T: 'static> Shared<T> {
|
||||
root::ControlFlow::Poll => {
|
||||
let cloned = self.clone();
|
||||
State::Poll {
|
||||
timeout: backend::Timeout::new(move || cloned.poll(), Duration::from_millis(0)),
|
||||
request: backend::AnimationFrameRequest::new(move || cloned.poll()),
|
||||
}
|
||||
}
|
||||
root::ControlFlow::Wait => State::Wait {
|
||||
@@ -270,26 +460,61 @@ impl<T: 'static> Shared<T> {
|
||||
};
|
||||
|
||||
match *self.0.runner.borrow_mut() {
|
||||
Some(ref mut runner) => {
|
||||
RunnerEnum::Running(ref mut runner) => {
|
||||
runner.state = new_state;
|
||||
}
|
||||
None => (),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_loop_destroyed(&self, control: &mut root::ControlFlow) {
|
||||
self.handle_event(Event::LoopDestroyed, control);
|
||||
let all_canvases = std::mem::take(&mut *self.0.all_canvases.borrow_mut());
|
||||
*self.0.scale_change_detector.borrow_mut() = None;
|
||||
*self.0.unload_event_handle.borrow_mut() = None;
|
||||
// Dropping the `Runner` drops the event handler closure, which will in
|
||||
// turn drop all `Window`s moved into the closure.
|
||||
*self.0.runner.borrow_mut() = RunnerEnum::Destroyed;
|
||||
for (_, canvas) in all_canvases {
|
||||
// In case any remaining `Window`s are still not dropped, we will need
|
||||
// to explicitly remove the event handlers associated with their canvases.
|
||||
if let Some(canvas) = canvas.upgrade() {
|
||||
let mut canvas = canvas.borrow_mut();
|
||||
canvas.remove_listeners();
|
||||
}
|
||||
}
|
||||
// At this point, the `self.0` `Rc` should only be strongly referenced
|
||||
// by the following:
|
||||
// * `self`, i.e. the item which triggered this event loop wakeup, which
|
||||
// is usually a `wasm-bindgen` `Closure`, which will be dropped after
|
||||
// returning to the JS glue code.
|
||||
// * The `EventLoopWindowTarget` leaked inside `EventLoop::run` due to the
|
||||
// JS exception thrown at the end.
|
||||
// * For each undropped `Window`:
|
||||
// * The `register_redraw_request` closure.
|
||||
// * The `destroy_fn` closure.
|
||||
}
|
||||
|
||||
// Check if the event loop is currently closed
|
||||
fn is_closed(&self) -> bool {
|
||||
match *self.0.runner.borrow() {
|
||||
Some(ref runner) => runner.state.is_exit(),
|
||||
None => false, // If the event loop is None, it has not been intialised yet, so it cannot be closed
|
||||
match self.0.runner.try_borrow().as_ref().map(Deref::deref) {
|
||||
Ok(RunnerEnum::Running(runner)) => runner.state.is_exit(),
|
||||
// The event loop is not closed since it is not initialized.
|
||||
Ok(RunnerEnum::Pending) => false,
|
||||
// The event loop is closed since it has been destroyed.
|
||||
Ok(RunnerEnum::Destroyed) => true,
|
||||
// Some other code is mutating the runner, which most likely means
|
||||
// the event loop is running and busy.
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
// Get the current control flow state
|
||||
fn current_control_flow(&self) -> root::ControlFlow {
|
||||
match *self.0.runner.borrow() {
|
||||
Some(ref runner) => runner.state.control_flow(),
|
||||
None => root::ControlFlow::Poll,
|
||||
RunnerEnum::Running(ref runner) => runner.state.control_flow(),
|
||||
RunnerEnum::Pending => root::ControlFlow::Poll,
|
||||
RunnerEnum::Destroyed => root::ControlFlow::Exit,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ pub enum State {
|
||||
start: Instant,
|
||||
},
|
||||
Poll {
|
||||
timeout: backend::Timeout,
|
||||
request: backend::AnimationFrameRequest,
|
||||
},
|
||||
Exit,
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
use super::{backend, device, proxy::Proxy, runner, window};
|
||||
use super::{super::monitor, backend, device, proxy::Proxy, runner, window};
|
||||
use crate::dpi::{PhysicalSize, Size};
|
||||
use crate::event::{DeviceId, ElementState, Event, KeyboardInput, TouchPhase, WindowEvent};
|
||||
use crate::event_loop::ControlFlow;
|
||||
use crate::window::WindowId;
|
||||
use crate::monitor::MonitorHandle as RootMH;
|
||||
use crate::window::{Theme, WindowId};
|
||||
use std::cell::RefCell;
|
||||
use std::clone::Clone;
|
||||
use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque};
|
||||
use std::rc::Rc;
|
||||
|
||||
pub struct WindowTarget<T: 'static> {
|
||||
pub(crate) runner: runner::Shared<T>,
|
||||
@@ -28,18 +32,24 @@ impl<T> WindowTarget<T> {
|
||||
Proxy::new(self.runner.clone())
|
||||
}
|
||||
|
||||
pub fn run(&self, event_handler: Box<dyn FnMut(Event<'static, T>, &mut ControlFlow)>) {
|
||||
pub fn run(&self, event_handler: Box<dyn FnMut(Event<'_, T>, &mut ControlFlow)>) {
|
||||
self.runner.set_listener(event_handler);
|
||||
let runner = self.runner.clone();
|
||||
self.runner.set_on_scale_change(move |arg| {
|
||||
runner.handle_scale_changed(arg.old_scale, arg.new_scale)
|
||||
});
|
||||
}
|
||||
|
||||
pub fn generate_id(&self) -> window::Id {
|
||||
window::Id(self.runner.generate_id())
|
||||
}
|
||||
|
||||
pub fn register(&self, canvas: &mut backend::Canvas, id: window::Id) {
|
||||
let runner = self.runner.clone();
|
||||
pub fn register(&self, canvas: &Rc<RefCell<backend::Canvas>>, id: window::Id) {
|
||||
self.runner.add_canvas(WindowId(id), canvas);
|
||||
let mut canvas = canvas.borrow_mut();
|
||||
canvas.set_attribute("data-raw-handle", &id.0.to_string());
|
||||
|
||||
let runner = self.runner.clone();
|
||||
canvas.on_blur(move || {
|
||||
runner.send_event(Event::WindowEvent {
|
||||
window_id: WindowId(id),
|
||||
@@ -132,16 +142,29 @@ impl<T> WindowTarget<T> {
|
||||
});
|
||||
|
||||
let runner = self.runner.clone();
|
||||
canvas.on_mouse_press(move |pointer_id, button, modifiers| {
|
||||
runner.send_event(Event::WindowEvent {
|
||||
window_id: WindowId(id),
|
||||
event: WindowEvent::MouseInput {
|
||||
device_id: DeviceId(device::Id(pointer_id)),
|
||||
state: ElementState::Pressed,
|
||||
button,
|
||||
modifiers,
|
||||
},
|
||||
});
|
||||
canvas.on_mouse_press(move |pointer_id, position, button, modifiers| {
|
||||
// A mouse down event may come in without any prior CursorMoved events,
|
||||
// therefore we should send a CursorMoved event to make sure that the
|
||||
// user code has the correct cursor position.
|
||||
runner.send_events(
|
||||
std::iter::once(Event::WindowEvent {
|
||||
window_id: WindowId(id),
|
||||
event: WindowEvent::CursorMoved {
|
||||
device_id: DeviceId(device::Id(pointer_id)),
|
||||
position,
|
||||
modifiers,
|
||||
},
|
||||
})
|
||||
.chain(std::iter::once(Event::WindowEvent {
|
||||
window_id: WindowId(id),
|
||||
event: WindowEvent::MouseInput {
|
||||
device_id: DeviceId(device::Id(pointer_id)),
|
||||
state: ElementState::Pressed,
|
||||
button,
|
||||
modifiers,
|
||||
},
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
let runner = self.runner.clone();
|
||||
@@ -199,5 +222,28 @@ impl<T> WindowTarget<T> {
|
||||
});
|
||||
runner.request_redraw(WindowId(id));
|
||||
});
|
||||
|
||||
let runner = self.runner.clone();
|
||||
canvas.on_dark_mode(move |is_dark_mode| {
|
||||
let theme = if is_dark_mode {
|
||||
Theme::Dark
|
||||
} else {
|
||||
Theme::Light
|
||||
};
|
||||
runner.send_event(Event::WindowEvent {
|
||||
window_id: WindowId(id),
|
||||
event: WindowEvent::ThemeChanged(theme),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDequeIter<monitor::Handle> {
|
||||
VecDeque::new().into_iter()
|
||||
}
|
||||
|
||||
pub fn primary_monitor(&self) -> Option<RootMH> {
|
||||
Some(RootMH {
|
||||
inner: monitor::Handle,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,3 +44,11 @@ pub use self::window::{
|
||||
Id as WindowId, PlatformSpecificBuilderAttributes as PlatformSpecificWindowBuilderAttributes,
|
||||
Window,
|
||||
};
|
||||
|
||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ScaleChangeArgs {
|
||||
old_scale: f64,
|
||||
new_scale: f64,
|
||||
}
|
||||
|
||||
@@ -6,12 +6,13 @@ use crate::platform_impl::{OsError, PlatformSpecificWindowBuilderAttributes};
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use stdweb::js;
|
||||
use stdweb::traits::IPointerEvent;
|
||||
use stdweb::unstable::TryInto;
|
||||
use stdweb::web::event::{
|
||||
BlurEvent, ConcreteEvent, FocusEvent, FullscreenChangeEvent, KeyDownEvent, KeyPressEvent,
|
||||
KeyUpEvent, MouseWheelEvent, PointerDownEvent, PointerMoveEvent, PointerOutEvent,
|
||||
PointerOverEvent, PointerUpEvent,
|
||||
BlurEvent, ConcreteEvent, FocusEvent, FullscreenChangeEvent, IEvent, KeyDownEvent,
|
||||
KeyPressEvent, KeyUpEvent, MouseWheelEvent, PointerDownEvent, PointerMoveEvent,
|
||||
PointerOutEvent, PointerOverEvent, PointerUpEvent,
|
||||
};
|
||||
use stdweb::web::html_element::CanvasElement;
|
||||
use stdweb::web::{
|
||||
@@ -36,12 +37,6 @@ pub struct Canvas {
|
||||
wants_fullscreen: Rc<RefCell<bool>>,
|
||||
}
|
||||
|
||||
impl Drop for Canvas {
|
||||
fn drop(&mut self) {
|
||||
self.raw.remove();
|
||||
}
|
||||
}
|
||||
|
||||
impl Canvas {
|
||||
pub fn create(attr: PlatformSpecificWindowBuilderAttributes) -> Result<Self, RootOE> {
|
||||
let canvas = match attr.canvas {
|
||||
@@ -129,6 +124,7 @@ impl Canvas {
|
||||
F: 'static + FnMut(ScanCode, Option<VirtualKeyCode>, ModifiersState),
|
||||
{
|
||||
self.on_keyboard_release = Some(self.add_user_event(move |event: KeyUpEvent| {
|
||||
event.prevent_default();
|
||||
handler(
|
||||
event::scan_code(&event),
|
||||
event::virtual_key_code(&event),
|
||||
@@ -142,6 +138,7 @@ impl Canvas {
|
||||
F: 'static + FnMut(ScanCode, Option<VirtualKeyCode>, ModifiersState),
|
||||
{
|
||||
self.on_keyboard_press = Some(self.add_user_event(move |event: KeyDownEvent| {
|
||||
event.prevent_default();
|
||||
handler(
|
||||
event::scan_code(&event),
|
||||
event::virtual_key_code(&event),
|
||||
@@ -197,14 +194,19 @@ impl Canvas {
|
||||
|
||||
pub fn on_mouse_press<F>(&mut self, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, MouseButton, ModifiersState),
|
||||
F: 'static + FnMut(i32, PhysicalPosition<f64>, MouseButton, ModifiersState),
|
||||
{
|
||||
let canvas = self.raw.clone();
|
||||
self.on_mouse_press = Some(self.add_user_event(move |event: PointerDownEvent| {
|
||||
handler(
|
||||
event.pointer_id(),
|
||||
event::mouse_position(&event).to_physical(super::scale_factor()),
|
||||
event::mouse_button(&event),
|
||||
event::mouse_modifiers(&event),
|
||||
);
|
||||
canvas
|
||||
.set_pointer_capture(event.pointer_id())
|
||||
.expect("Failed to set pointer capture");
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -227,6 +229,7 @@ impl Canvas {
|
||||
F: 'static + FnMut(i32, MouseScrollDelta, ModifiersState),
|
||||
{
|
||||
self.on_mouse_wheel = Some(self.add_event(move |event: MouseWheelEvent| {
|
||||
event.prevent_default();
|
||||
if let Some(delta) = event::mouse_scroll_delta(&event) {
|
||||
handler(0, delta, event::mouse_modifiers(&event));
|
||||
}
|
||||
@@ -240,6 +243,22 @@ impl Canvas {
|
||||
self.on_fullscreen_change = Some(self.add_event(move |_: FullscreenChangeEvent| handler()));
|
||||
}
|
||||
|
||||
pub fn on_dark_mode<F>(&mut self, handler: F)
|
||||
where
|
||||
F: 'static + FnMut(bool),
|
||||
{
|
||||
// TODO: upstream to stdweb
|
||||
js! {
|
||||
var handler = @{handler};
|
||||
|
||||
if (window.matchMedia) {
|
||||
window.matchMedia("(prefers-color-scheme: dark)").addListener(function(e) {
|
||||
handler(event.matches)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn add_event<E, F>(&self, mut handler: F) -> EventListenerHandle
|
||||
where
|
||||
E: ConcreteEvent,
|
||||
@@ -281,4 +300,8 @@ impl Canvas {
|
||||
pub fn is_fullscreen(&self) -> bool {
|
||||
super::is_fullscreen(&self.raw)
|
||||
}
|
||||
|
||||
pub fn remove_listeners(&mut self) {
|
||||
// TODO: Stub, unimplemented (see web_sys for reference).
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,11 +32,14 @@ pub fn mouse_position(event: &impl IMouseEvent) -> LogicalPosition<f64> {
|
||||
|
||||
pub fn mouse_scroll_delta(event: &MouseWheelEvent) -> Option<MouseScrollDelta> {
|
||||
let x = event.delta_x();
|
||||
let y = event.delta_y();
|
||||
let y = -event.delta_y();
|
||||
|
||||
match event.delta_mode() {
|
||||
MouseWheelDeltaMode::Line => Some(MouseScrollDelta::LineDelta(x as f32, y as f32)),
|
||||
MouseWheelDeltaMode::Pixel => Some(MouseScrollDelta::PixelDelta(LogicalPosition { x, y })),
|
||||
MouseWheelDeltaMode::Pixel => {
|
||||
let delta = LogicalPosition::new(x, y).to_physical(super::scale_factor());
|
||||
Some(MouseScrollDelta::PixelDelta(delta))
|
||||
}
|
||||
MouseWheelDeltaMode::Page => None,
|
||||
}
|
||||
}
|
||||
@@ -143,7 +146,7 @@ pub fn virtual_key_code(event: &impl IKeyboardEvent) -> Option<VirtualKeyCode> {
|
||||
"Numpad9" => VirtualKeyCode::Numpad9,
|
||||
"AbntC1" => VirtualKeyCode::AbntC1,
|
||||
"AbntC2" => VirtualKeyCode::AbntC2,
|
||||
"NumpadAdd" => VirtualKeyCode::Add,
|
||||
"NumpadAdd" => VirtualKeyCode::NumpadAdd,
|
||||
"Quote" => VirtualKeyCode::Apostrophe,
|
||||
"Apps" => VirtualKeyCode::Apps,
|
||||
"At" => VirtualKeyCode::At,
|
||||
@@ -154,8 +157,8 @@ pub fn virtual_key_code(event: &impl IKeyboardEvent) -> Option<VirtualKeyCode> {
|
||||
"Semicolon" => VirtualKeyCode::Semicolon,
|
||||
"Comma" => VirtualKeyCode::Comma,
|
||||
"Convert" => VirtualKeyCode::Convert,
|
||||
"NumpadDecimal" => VirtualKeyCode::Decimal,
|
||||
"NumpadDivide" => VirtualKeyCode::Divide,
|
||||
"NumpadDecimal" => VirtualKeyCode::NumpadDecimal,
|
||||
"NumpadDivide" => VirtualKeyCode::NumpadDivide,
|
||||
"Equal" => VirtualKeyCode::Equals,
|
||||
"Backquote" => VirtualKeyCode::Grave,
|
||||
"Kana" => VirtualKeyCode::Kana,
|
||||
@@ -169,7 +172,7 @@ pub fn virtual_key_code(event: &impl IKeyboardEvent) -> Option<VirtualKeyCode> {
|
||||
"MediaSelect" => VirtualKeyCode::MediaSelect,
|
||||
"MediaStop" => VirtualKeyCode::MediaStop,
|
||||
"Minus" => VirtualKeyCode::Minus,
|
||||
"NumpadMultiply" => VirtualKeyCode::Multiply,
|
||||
"NumpadMultiply" => VirtualKeyCode::NumpadMultiply,
|
||||
"Mute" => VirtualKeyCode::Mute,
|
||||
"LaunchMyComputer" => VirtualKeyCode::MyComputer,
|
||||
"NavigateForward" => VirtualKeyCode::NavigateForward,
|
||||
@@ -192,7 +195,7 @@ pub fn virtual_key_code(event: &impl IKeyboardEvent) -> Option<VirtualKeyCode> {
|
||||
"Slash" => VirtualKeyCode::Slash,
|
||||
"Sleep" => VirtualKeyCode::Sleep,
|
||||
"Stop" => VirtualKeyCode::Stop,
|
||||
"NumpadSubtract" => VirtualKeyCode::Subtract,
|
||||
"NumpadSubtract" => VirtualKeyCode::NumpadSubtract,
|
||||
"Sysrq" => VirtualKeyCode::Sysrq,
|
||||
"Tab" => VirtualKeyCode::Tab,
|
||||
"Underline" => VirtualKeyCode::Underline,
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
#![deprecated(since = "0.23.0", note = "Please migrate to web-sys over stdweb")]
|
||||
|
||||
mod canvas;
|
||||
mod event;
|
||||
mod scaling;
|
||||
mod timeout;
|
||||
|
||||
pub use self::canvas::Canvas;
|
||||
pub use self::timeout::Timeout;
|
||||
pub use self::scaling::ScaleChangeDetector;
|
||||
pub use self::timeout::{AnimationFrameRequest, Timeout};
|
||||
|
||||
use crate::dpi::{LogicalSize, Size};
|
||||
use crate::platform::web::WindowExtStdweb;
|
||||
use crate::window::Window;
|
||||
|
||||
use stdweb::js;
|
||||
use stdweb::unstable::TryInto;
|
||||
use stdweb::web::event::BeforeUnloadEvent;
|
||||
use stdweb::web::window;
|
||||
use stdweb::web::IEventTarget;
|
||||
@@ -23,7 +28,9 @@ pub fn exit_fullscreen() {
|
||||
document().exit_fullscreen();
|
||||
}
|
||||
|
||||
pub fn on_unload(mut handler: impl FnMut() + 'static) {
|
||||
pub type UnloadEventHandle = ();
|
||||
|
||||
pub fn on_unload(mut handler: impl FnMut() + 'static) -> UnloadEventHandle {
|
||||
window().add_event_listener(move |_: BeforeUnloadEvent| handler());
|
||||
}
|
||||
|
||||
@@ -31,6 +38,15 @@ impl WindowExtStdweb for Window {
|
||||
fn canvas(&self) -> CanvasElement {
|
||||
self.window.canvas().raw().clone()
|
||||
}
|
||||
|
||||
fn is_dark_mode(&self) -> bool {
|
||||
// TODO: upstream to stdweb
|
||||
let is_dark_mode = js! {
|
||||
return (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches)
|
||||
};
|
||||
|
||||
is_dark_mode.try_into().expect("should return a bool")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn window_size() -> LogicalSize<f64> {
|
||||
@@ -57,9 +73,13 @@ pub fn set_canvas_size(raw: &CanvasElement, size: Size) {
|
||||
raw.set_width(physical_size.width);
|
||||
raw.set_height(physical_size.height);
|
||||
|
||||
set_canvas_style_property(raw, "width", &format!("{}px", logical_size.width));
|
||||
set_canvas_style_property(raw, "height", &format!("{}px", logical_size.height));
|
||||
}
|
||||
|
||||
pub fn set_canvas_style_property(raw: &CanvasElement, style_attribute: &str, value: &str) {
|
||||
js! {
|
||||
@{raw.as_ref()}.style.width = @{logical_size.width} + "px";
|
||||
@{raw.as_ref()}.style.height = @{logical_size.height} + "px";
|
||||
@{raw.as_ref()}.style[@{style_attribute}] = @{value};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
13
src/platform_impl/web/stdweb/scaling.rs
Normal file
13
src/platform_impl/web/stdweb/scaling.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use super::super::ScaleChangeArgs;
|
||||
|
||||
pub struct ScaleChangeDetector(());
|
||||
|
||||
impl ScaleChangeDetector {
|
||||
pub(crate) fn new<F>(_handler: F) -> Self
|
||||
where
|
||||
F: 'static + FnMut(ScaleChangeArgs),
|
||||
{
|
||||
// TODO: Stub, unimplemented (see web_sys for reference).
|
||||
Self(())
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
use stdweb::web::{window, IWindowOrWorker, TimeoutHandle};
|
||||
use stdweb::web::{window, IWindowOrWorker, RequestAnimationFrameHandle, TimeoutHandle};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Timeout {
|
||||
@@ -23,3 +25,39 @@ impl Drop for Timeout {
|
||||
handle.clear();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AnimationFrameRequest {
|
||||
handle: Option<RequestAnimationFrameHandle>,
|
||||
// track callback state, because `cancelAnimationFrame` is slow
|
||||
fired: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
impl AnimationFrameRequest {
|
||||
pub fn new<F>(mut f: F) -> AnimationFrameRequest
|
||||
where
|
||||
F: 'static + FnMut(),
|
||||
{
|
||||
let fired = Rc::new(Cell::new(false));
|
||||
let c_fired = fired.clone();
|
||||
let handle = window().request_animation_frame(move |_| {
|
||||
(*c_fired).set(true);
|
||||
f();
|
||||
});
|
||||
|
||||
AnimationFrameRequest {
|
||||
handle: Some(handle),
|
||||
fired,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AnimationFrameRequest {
|
||||
fn drop(&mut self) {
|
||||
if !(*self.fired).get() {
|
||||
if let Some(handle) = self.handle.take() {
|
||||
handle.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use super::event;
|
||||
use super::event_handle::EventListenerHandle;
|
||||
use super::media_query_handle::MediaQueryListHandle;
|
||||
use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
||||
use crate::error::OsError as RootOE;
|
||||
use crate::event::{ModifiersState, MouseButton, MouseScrollDelta, ScanCode, VirtualKeyCode};
|
||||
@@ -8,30 +10,31 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::{closure::Closure, JsCast};
|
||||
use web_sys::{Event, FocusEvent, HtmlCanvasElement, KeyboardEvent, PointerEvent, WheelEvent};
|
||||
use web_sys::{
|
||||
AddEventListenerOptions, Event, FocusEvent, HtmlCanvasElement, KeyboardEvent,
|
||||
MediaQueryListEvent, MouseEvent, WheelEvent,
|
||||
};
|
||||
|
||||
mod mouse_handler;
|
||||
mod pointer_handler;
|
||||
|
||||
pub struct Canvas {
|
||||
/// Note: resizing the HTMLCanvasElement should go through `backend::set_canvas_size` to ensure the DPI factor is maintained.
|
||||
raw: HtmlCanvasElement,
|
||||
on_focus: Option<Closure<dyn FnMut(FocusEvent)>>,
|
||||
on_blur: Option<Closure<dyn FnMut(FocusEvent)>>,
|
||||
on_keyboard_release: Option<Closure<dyn FnMut(KeyboardEvent)>>,
|
||||
on_keyboard_press: Option<Closure<dyn FnMut(KeyboardEvent)>>,
|
||||
on_received_character: Option<Closure<dyn FnMut(KeyboardEvent)>>,
|
||||
on_cursor_leave: Option<Closure<dyn FnMut(PointerEvent)>>,
|
||||
on_cursor_enter: Option<Closure<dyn FnMut(PointerEvent)>>,
|
||||
on_cursor_move: Option<Closure<dyn FnMut(PointerEvent)>>,
|
||||
on_mouse_press: Option<Closure<dyn FnMut(PointerEvent)>>,
|
||||
on_mouse_release: Option<Closure<dyn FnMut(PointerEvent)>>,
|
||||
on_mouse_wheel: Option<Closure<dyn FnMut(WheelEvent)>>,
|
||||
on_fullscreen_change: Option<Closure<dyn FnMut(Event)>>,
|
||||
wants_fullscreen: Rc<RefCell<bool>>,
|
||||
common: Common,
|
||||
on_focus: Option<EventListenerHandle<dyn FnMut(FocusEvent)>>,
|
||||
on_blur: Option<EventListenerHandle<dyn FnMut(FocusEvent)>>,
|
||||
on_keyboard_release: Option<EventListenerHandle<dyn FnMut(KeyboardEvent)>>,
|
||||
on_keyboard_press: Option<EventListenerHandle<dyn FnMut(KeyboardEvent)>>,
|
||||
on_received_character: Option<EventListenerHandle<dyn FnMut(KeyboardEvent)>>,
|
||||
on_mouse_wheel: Option<EventListenerHandle<dyn FnMut(WheelEvent)>>,
|
||||
on_fullscreen_change: Option<EventListenerHandle<dyn FnMut(Event)>>,
|
||||
on_dark_mode: Option<MediaQueryListHandle>,
|
||||
mouse_state: MouseState,
|
||||
}
|
||||
|
||||
impl Drop for Canvas {
|
||||
fn drop(&mut self) {
|
||||
self.raw.remove();
|
||||
}
|
||||
struct Common {
|
||||
/// Note: resizing the HTMLCanvasElement should go through `backend::set_canvas_size` to ensure the DPI factor is maintained.
|
||||
raw: HtmlCanvasElement,
|
||||
wants_fullscreen: Rc<RefCell<bool>>,
|
||||
}
|
||||
|
||||
impl Canvas {
|
||||
@@ -62,32 +65,38 @@ impl Canvas {
|
||||
.set_attribute("tabindex", "0")
|
||||
.map_err(|_| os_error!(OsError("Failed to set a tabindex".to_owned())))?;
|
||||
|
||||
let mouse_state = if has_pointer_event() {
|
||||
MouseState::HasPointerEvent(pointer_handler::PointerHandler::new())
|
||||
} else {
|
||||
MouseState::NoPointerEvent(mouse_handler::MouseHandler::new())
|
||||
};
|
||||
|
||||
Ok(Canvas {
|
||||
raw: canvas,
|
||||
common: Common {
|
||||
raw: canvas,
|
||||
wants_fullscreen: Rc::new(RefCell::new(false)),
|
||||
},
|
||||
on_blur: None,
|
||||
on_focus: None,
|
||||
on_keyboard_release: None,
|
||||
on_keyboard_press: None,
|
||||
on_received_character: None,
|
||||
on_cursor_leave: None,
|
||||
on_cursor_enter: None,
|
||||
on_cursor_move: None,
|
||||
on_mouse_release: None,
|
||||
on_mouse_press: None,
|
||||
on_mouse_wheel: None,
|
||||
on_fullscreen_change: None,
|
||||
wants_fullscreen: Rc::new(RefCell::new(false)),
|
||||
on_dark_mode: None,
|
||||
mouse_state,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_attribute(&self, attribute: &str, value: &str) {
|
||||
self.raw
|
||||
self.common
|
||||
.raw
|
||||
.set_attribute(attribute, value)
|
||||
.expect(&format!("Set attribute: {}", attribute));
|
||||
}
|
||||
|
||||
pub fn position(&self) -> LogicalPosition<f64> {
|
||||
let bounds = self.raw.get_bounding_client_rect();
|
||||
let bounds = self.common.raw.get_bounding_client_rect();
|
||||
|
||||
LogicalPosition {
|
||||
x: bounds.x(),
|
||||
@@ -97,20 +106,20 @@ impl Canvas {
|
||||
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
PhysicalSize {
|
||||
width: self.raw.width(),
|
||||
height: self.raw.height(),
|
||||
width: self.common.raw.width(),
|
||||
height: self.common.raw.height(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn raw(&self) -> &HtmlCanvasElement {
|
||||
&self.raw
|
||||
&self.common.raw
|
||||
}
|
||||
|
||||
pub fn on_blur<F>(&mut self, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(),
|
||||
{
|
||||
self.on_blur = Some(self.add_event("blur", move |_: FocusEvent| {
|
||||
self.on_blur = Some(self.common.add_event("blur", move |_: FocusEvent| {
|
||||
handler();
|
||||
}));
|
||||
}
|
||||
@@ -119,7 +128,7 @@ impl Canvas {
|
||||
where
|
||||
F: 'static + FnMut(),
|
||||
{
|
||||
self.on_focus = Some(self.add_event("focus", move |_: FocusEvent| {
|
||||
self.on_focus = Some(self.common.add_event("focus", move |_: FocusEvent| {
|
||||
handler();
|
||||
}));
|
||||
}
|
||||
@@ -128,28 +137,34 @@ impl Canvas {
|
||||
where
|
||||
F: 'static + FnMut(ScanCode, Option<VirtualKeyCode>, ModifiersState),
|
||||
{
|
||||
self.on_keyboard_release =
|
||||
Some(self.add_user_event("keyup", move |event: KeyboardEvent| {
|
||||
self.on_keyboard_release = Some(self.common.add_user_event(
|
||||
"keyup",
|
||||
move |event: KeyboardEvent| {
|
||||
event.prevent_default();
|
||||
handler(
|
||||
event::scan_code(&event),
|
||||
event::virtual_key_code(&event),
|
||||
event::keyboard_modifiers(&event),
|
||||
);
|
||||
}));
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub fn on_keyboard_press<F>(&mut self, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(ScanCode, Option<VirtualKeyCode>, ModifiersState),
|
||||
{
|
||||
self.on_keyboard_press =
|
||||
Some(self.add_user_event("keydown", move |event: KeyboardEvent| {
|
||||
self.on_keyboard_press = Some(self.common.add_user_event(
|
||||
"keydown",
|
||||
move |event: KeyboardEvent| {
|
||||
event.prevent_default();
|
||||
handler(
|
||||
event::scan_code(&event),
|
||||
event::virtual_key_code(&event),
|
||||
event::keyboard_modifiers(&event),
|
||||
);
|
||||
}));
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub fn on_received_character<F>(&mut self, mut handler: F)
|
||||
@@ -161,7 +176,7 @@ impl Canvas {
|
||||
// The `keypress` event is deprecated, but there does not seem to be a
|
||||
// viable/compatible alternative as of now. `beforeinput` is still widely
|
||||
// unsupported.
|
||||
self.on_received_character = Some(self.add_user_event(
|
||||
self.on_received_character = Some(self.common.add_user_event(
|
||||
"keypress",
|
||||
move |event: KeyboardEvent| {
|
||||
handler(event::codepoint(&event));
|
||||
@@ -169,74 +184,62 @@ impl Canvas {
|
||||
));
|
||||
}
|
||||
|
||||
pub fn on_cursor_leave<F>(&mut self, mut handler: F)
|
||||
pub fn on_cursor_leave<F>(&mut self, handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32),
|
||||
{
|
||||
self.on_cursor_leave = Some(self.add_event("pointerout", move |event: PointerEvent| {
|
||||
handler(event.pointer_id());
|
||||
}));
|
||||
match &mut self.mouse_state {
|
||||
MouseState::HasPointerEvent(h) => h.on_cursor_leave(&self.common, handler),
|
||||
MouseState::NoPointerEvent(h) => h.on_cursor_leave(&self.common, handler),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_cursor_enter<F>(&mut self, mut handler: F)
|
||||
pub fn on_cursor_enter<F>(&mut self, handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32),
|
||||
{
|
||||
self.on_cursor_enter = Some(self.add_event("pointerover", move |event: PointerEvent| {
|
||||
handler(event.pointer_id());
|
||||
}));
|
||||
match &mut self.mouse_state {
|
||||
MouseState::HasPointerEvent(h) => h.on_cursor_enter(&self.common, handler),
|
||||
MouseState::NoPointerEvent(h) => h.on_cursor_enter(&self.common, handler),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_mouse_release<F>(&mut self, mut handler: F)
|
||||
pub fn on_mouse_release<F>(&mut self, handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, MouseButton, ModifiersState),
|
||||
{
|
||||
self.on_mouse_release = Some(self.add_user_event(
|
||||
"pointerup",
|
||||
move |event: PointerEvent| {
|
||||
handler(
|
||||
event.pointer_id(),
|
||||
event::mouse_button(&event),
|
||||
event::mouse_modifiers(&event),
|
||||
);
|
||||
},
|
||||
));
|
||||
match &mut self.mouse_state {
|
||||
MouseState::HasPointerEvent(h) => h.on_mouse_release(&self.common, handler),
|
||||
MouseState::NoPointerEvent(h) => h.on_mouse_release(&self.common, handler),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_mouse_press<F>(&mut self, mut handler: F)
|
||||
pub fn on_mouse_press<F>(&mut self, handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, MouseButton, ModifiersState),
|
||||
F: 'static + FnMut(i32, PhysicalPosition<f64>, MouseButton, ModifiersState),
|
||||
{
|
||||
self.on_mouse_press = Some(self.add_user_event(
|
||||
"pointerdown",
|
||||
move |event: PointerEvent| {
|
||||
handler(
|
||||
event.pointer_id(),
|
||||
event::mouse_button(&event),
|
||||
event::mouse_modifiers(&event),
|
||||
);
|
||||
},
|
||||
));
|
||||
match &mut self.mouse_state {
|
||||
MouseState::HasPointerEvent(h) => h.on_mouse_press(&self.common, handler),
|
||||
MouseState::NoPointerEvent(h) => h.on_mouse_press(&self.common, handler),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_cursor_move<F>(&mut self, mut handler: F)
|
||||
pub fn on_cursor_move<F>(&mut self, handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, PhysicalPosition<f64>, ModifiersState),
|
||||
{
|
||||
self.on_cursor_move = Some(self.add_event("pointermove", move |event: PointerEvent| {
|
||||
handler(
|
||||
event.pointer_id(),
|
||||
event::mouse_position(&event).to_physical(super::scale_factor()),
|
||||
event::mouse_modifiers(&event),
|
||||
);
|
||||
}));
|
||||
match &mut self.mouse_state {
|
||||
MouseState::HasPointerEvent(h) => h.on_cursor_move(&self.common, handler),
|
||||
MouseState::NoPointerEvent(h) => h.on_cursor_move(&self.common, handler),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_mouse_wheel<F>(&mut self, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, MouseScrollDelta, ModifiersState),
|
||||
{
|
||||
self.on_mouse_wheel = Some(self.add_event("wheel", move |event: WheelEvent| {
|
||||
self.on_mouse_wheel = Some(self.common.add_event("wheel", move |event: WheelEvent| {
|
||||
event.prevent_default();
|
||||
if let Some(delta) = event::mouse_scroll_delta(&event) {
|
||||
handler(0, delta, event::mouse_modifiers(&event));
|
||||
}
|
||||
@@ -247,11 +250,54 @@ impl Canvas {
|
||||
where
|
||||
F: 'static + FnMut(),
|
||||
{
|
||||
self.on_fullscreen_change =
|
||||
Some(self.add_event("fullscreenchange", move |_: Event| handler()));
|
||||
self.on_fullscreen_change = Some(
|
||||
self.common
|
||||
.add_event("fullscreenchange", move |_: Event| handler()),
|
||||
);
|
||||
}
|
||||
|
||||
fn add_event<E, F>(&self, event_name: &str, mut handler: F) -> Closure<dyn FnMut(E)>
|
||||
pub fn on_dark_mode<F>(&mut self, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(bool),
|
||||
{
|
||||
let closure =
|
||||
Closure::wrap(
|
||||
Box::new(move |event: MediaQueryListEvent| handler(event.matches()))
|
||||
as Box<dyn FnMut(_)>,
|
||||
);
|
||||
self.on_dark_mode = MediaQueryListHandle::new("(prefers-color-scheme: dark)", closure);
|
||||
}
|
||||
|
||||
pub fn request_fullscreen(&self) {
|
||||
self.common.request_fullscreen()
|
||||
}
|
||||
|
||||
pub fn is_fullscreen(&self) -> bool {
|
||||
self.common.is_fullscreen()
|
||||
}
|
||||
|
||||
pub fn remove_listeners(&mut self) {
|
||||
self.on_focus = None;
|
||||
self.on_blur = None;
|
||||
self.on_keyboard_release = None;
|
||||
self.on_keyboard_press = None;
|
||||
self.on_received_character = None;
|
||||
self.on_mouse_wheel = None;
|
||||
self.on_fullscreen_change = None;
|
||||
self.on_dark_mode = None;
|
||||
match &mut self.mouse_state {
|
||||
MouseState::HasPointerEvent(h) => h.remove_listeners(),
|
||||
MouseState::NoPointerEvent(h) => h.remove_listeners(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Common {
|
||||
fn add_event<E, F>(
|
||||
&self,
|
||||
event_name: &'static str,
|
||||
mut handler: F,
|
||||
) -> EventListenerHandle<dyn FnMut(E)>
|
||||
where
|
||||
E: 'static + AsRef<web_sys::Event> + wasm_bindgen::convert::FromWasmAbi,
|
||||
F: 'static + FnMut(E),
|
||||
@@ -266,17 +312,19 @@ impl Canvas {
|
||||
handler(event);
|
||||
}) as Box<dyn FnMut(E)>);
|
||||
|
||||
self.raw
|
||||
.add_event_listener_with_callback(event_name, &closure.as_ref().unchecked_ref())
|
||||
.expect("Failed to add event listener with callback");
|
||||
let listener = EventListenerHandle::new(&self.raw, event_name, closure);
|
||||
|
||||
closure
|
||||
listener
|
||||
}
|
||||
|
||||
// The difference between add_event and add_user_event is that the latter has a special meaning
|
||||
// for browser security. A user event is a deliberate action by the user (like a mouse or key
|
||||
// press) and is the only time things like a fullscreen request may be successfully completed.)
|
||||
fn add_user_event<E, F>(&self, event_name: &str, mut handler: F) -> Closure<dyn FnMut(E)>
|
||||
fn add_user_event<E, F>(
|
||||
&self,
|
||||
event_name: &'static str,
|
||||
mut handler: F,
|
||||
) -> EventListenerHandle<dyn FnMut(E)>
|
||||
where
|
||||
E: 'static + AsRef<web_sys::Event> + wasm_bindgen::convert::FromWasmAbi,
|
||||
F: 'static + FnMut(E),
|
||||
@@ -296,6 +344,43 @@ impl Canvas {
|
||||
})
|
||||
}
|
||||
|
||||
// This function is used exclusively for mouse events (not pointer events).
|
||||
// Due to the need for mouse capturing, the mouse event handlers are added
|
||||
// to the window instead of the canvas element, which requires special
|
||||
// handling to control event propagation.
|
||||
fn add_window_mouse_event<F>(
|
||||
&self,
|
||||
event_name: &'static str,
|
||||
mut handler: F,
|
||||
) -> EventListenerHandle<dyn FnMut(MouseEvent)>
|
||||
where
|
||||
F: 'static + FnMut(MouseEvent),
|
||||
{
|
||||
let wants_fullscreen = self.wants_fullscreen.clone();
|
||||
let canvas = self.raw.clone();
|
||||
let window = web_sys::window().expect("Failed to obtain window");
|
||||
|
||||
let closure = Closure::wrap(Box::new(move |event: MouseEvent| {
|
||||
handler(event);
|
||||
|
||||
if *wants_fullscreen.borrow() {
|
||||
canvas
|
||||
.request_fullscreen()
|
||||
.expect("Failed to enter fullscreen");
|
||||
*wants_fullscreen.borrow_mut() = false;
|
||||
}
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
|
||||
let listener = EventListenerHandle::with_options(
|
||||
&window,
|
||||
event_name,
|
||||
closure,
|
||||
AddEventListenerOptions::new().capture(true),
|
||||
);
|
||||
|
||||
listener
|
||||
}
|
||||
|
||||
pub fn request_fullscreen(&self) {
|
||||
*self.wants_fullscreen.borrow_mut() = true;
|
||||
}
|
||||
@@ -304,3 +389,20 @@ impl Canvas {
|
||||
super::is_fullscreen(&self.raw)
|
||||
}
|
||||
}
|
||||
|
||||
enum MouseState {
|
||||
HasPointerEvent(pointer_handler::PointerHandler),
|
||||
NoPointerEvent(mouse_handler::MouseHandler),
|
||||
}
|
||||
|
||||
/// Returns whether pointer events are supported.
|
||||
/// Used to decide whether to use pointer events
|
||||
/// or plain mouse events. Note that Safari
|
||||
/// doesn't support pointer events now.
|
||||
fn has_pointer_event() -> bool {
|
||||
if let Some(window) = web_sys::window() {
|
||||
window.get("PointerEvent").is_some()
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
212
src/platform_impl/web/web_sys/canvas/mouse_handler.rs
Normal file
212
src/platform_impl/web/web_sys/canvas/mouse_handler.rs
Normal file
@@ -0,0 +1,212 @@
|
||||
use super::event;
|
||||
use super::EventListenerHandle;
|
||||
use crate::dpi::PhysicalPosition;
|
||||
use crate::event::{ModifiersState, MouseButton};
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use web_sys::{EventTarget, MouseEvent};
|
||||
|
||||
pub(super) struct MouseHandler {
|
||||
on_mouse_leave: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
|
||||
on_mouse_enter: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
|
||||
on_mouse_move: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
|
||||
on_mouse_press: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
|
||||
on_mouse_release: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
|
||||
on_mouse_leave_handler: Rc<RefCell<Option<Box<dyn FnMut(i32)>>>>,
|
||||
mouse_capture_state: Rc<RefCell<MouseCaptureState>>,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub(super) enum MouseCaptureState {
|
||||
NotCaptured,
|
||||
Captured,
|
||||
OtherElement,
|
||||
}
|
||||
|
||||
impl MouseHandler {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
on_mouse_leave: None,
|
||||
on_mouse_enter: None,
|
||||
on_mouse_move: None,
|
||||
on_mouse_press: None,
|
||||
on_mouse_release: None,
|
||||
on_mouse_leave_handler: Rc::new(RefCell::new(None)),
|
||||
mouse_capture_state: Rc::new(RefCell::new(MouseCaptureState::NotCaptured)),
|
||||
}
|
||||
}
|
||||
pub fn on_cursor_leave<F>(&mut self, canvas_common: &super::Common, handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32),
|
||||
{
|
||||
*self.on_mouse_leave_handler.borrow_mut() = Some(Box::new(handler));
|
||||
let on_mouse_leave_handler = self.on_mouse_leave_handler.clone();
|
||||
let mouse_capture_state = self.mouse_capture_state.clone();
|
||||
self.on_mouse_leave = Some(canvas_common.add_event("mouseout", move |_: MouseEvent| {
|
||||
// If the mouse is being captured, it is always considered
|
||||
// to be "within" the the canvas, until the capture has been
|
||||
// released, therefore we don't send cursor leave events.
|
||||
if *mouse_capture_state.borrow() != MouseCaptureState::Captured {
|
||||
if let Some(handler) = on_mouse_leave_handler.borrow_mut().as_mut() {
|
||||
handler(0);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn on_cursor_enter<F>(&mut self, canvas_common: &super::Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32),
|
||||
{
|
||||
let mouse_capture_state = self.mouse_capture_state.clone();
|
||||
self.on_mouse_enter = Some(canvas_common.add_event("mouseover", move |_: MouseEvent| {
|
||||
// We don't send cursor leave events when the mouse is being
|
||||
// captured, therefore we do the same with cursor enter events.
|
||||
if *mouse_capture_state.borrow() != MouseCaptureState::Captured {
|
||||
handler(0);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn on_mouse_release<F>(&mut self, canvas_common: &super::Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, MouseButton, ModifiersState),
|
||||
{
|
||||
let on_mouse_leave_handler = self.on_mouse_leave_handler.clone();
|
||||
let mouse_capture_state = self.mouse_capture_state.clone();
|
||||
let canvas = canvas_common.raw.clone();
|
||||
self.on_mouse_release = Some(canvas_common.add_window_mouse_event(
|
||||
"mouseup",
|
||||
move |event: MouseEvent| {
|
||||
let canvas = canvas.clone();
|
||||
let mut mouse_capture_state = mouse_capture_state.borrow_mut();
|
||||
match &*mouse_capture_state {
|
||||
// Shouldn't happen but we'll just ignore it.
|
||||
MouseCaptureState::NotCaptured => return,
|
||||
MouseCaptureState::OtherElement => {
|
||||
if event.buttons() == 0 {
|
||||
// No buttons are pressed anymore so reset
|
||||
// the capturing state.
|
||||
*mouse_capture_state = MouseCaptureState::NotCaptured;
|
||||
}
|
||||
return;
|
||||
}
|
||||
MouseCaptureState::Captured => {}
|
||||
}
|
||||
event.stop_propagation();
|
||||
handler(
|
||||
0,
|
||||
event::mouse_button(&event),
|
||||
event::mouse_modifiers(&event),
|
||||
);
|
||||
if event
|
||||
.target()
|
||||
.map_or(false, |target| target != EventTarget::from(canvas))
|
||||
{
|
||||
// Since we do not send cursor leave events while the
|
||||
// cursor is being captured, we instead send it after
|
||||
// the capture has been released.
|
||||
if let Some(handler) = on_mouse_leave_handler.borrow_mut().as_mut() {
|
||||
handler(0);
|
||||
}
|
||||
}
|
||||
if event.buttons() == 0 {
|
||||
// No buttons are pressed anymore so reset
|
||||
// the capturing state.
|
||||
*mouse_capture_state = MouseCaptureState::NotCaptured;
|
||||
}
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub fn on_mouse_press<F>(&mut self, canvas_common: &super::Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, PhysicalPosition<f64>, MouseButton, ModifiersState),
|
||||
{
|
||||
let mouse_capture_state = self.mouse_capture_state.clone();
|
||||
let canvas = canvas_common.raw.clone();
|
||||
self.on_mouse_press = Some(canvas_common.add_window_mouse_event(
|
||||
"mousedown",
|
||||
move |event: MouseEvent| {
|
||||
let canvas = canvas.clone();
|
||||
let mut mouse_capture_state = mouse_capture_state.borrow_mut();
|
||||
match &*mouse_capture_state {
|
||||
MouseCaptureState::NotCaptured
|
||||
if event
|
||||
.target()
|
||||
.map_or(false, |target| target != EventTarget::from(canvas)) =>
|
||||
{
|
||||
// The target isn't our canvas which means the
|
||||
// mouse is pressed outside of it.
|
||||
*mouse_capture_state = MouseCaptureState::OtherElement;
|
||||
return;
|
||||
}
|
||||
MouseCaptureState::OtherElement => return,
|
||||
_ => {}
|
||||
}
|
||||
*mouse_capture_state = MouseCaptureState::Captured;
|
||||
event.stop_propagation();
|
||||
handler(
|
||||
0,
|
||||
event::mouse_position(&event).to_physical(super::super::scale_factor()),
|
||||
event::mouse_button(&event),
|
||||
event::mouse_modifiers(&event),
|
||||
);
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub fn on_cursor_move<F>(&mut self, canvas_common: &super::Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, PhysicalPosition<f64>, ModifiersState),
|
||||
{
|
||||
let mouse_capture_state = self.mouse_capture_state.clone();
|
||||
let canvas = canvas_common.raw.clone();
|
||||
self.on_mouse_move = Some(canvas_common.add_window_mouse_event(
|
||||
"mousemove",
|
||||
move |event: MouseEvent| {
|
||||
let canvas = canvas.clone();
|
||||
let mouse_capture_state = mouse_capture_state.borrow();
|
||||
let is_over_canvas = event
|
||||
.target()
|
||||
.map_or(false, |target| target == EventTarget::from(canvas.clone()));
|
||||
match &*mouse_capture_state {
|
||||
// Don't handle hover events outside of canvas.
|
||||
MouseCaptureState::NotCaptured if !is_over_canvas => return,
|
||||
MouseCaptureState::OtherElement if !is_over_canvas => return,
|
||||
// If hovering over the canvas, just send the cursor move event.
|
||||
MouseCaptureState::NotCaptured
|
||||
| MouseCaptureState::OtherElement
|
||||
| MouseCaptureState::Captured => {
|
||||
if *mouse_capture_state == MouseCaptureState::Captured {
|
||||
event.stop_propagation();
|
||||
}
|
||||
let mouse_pos = if is_over_canvas {
|
||||
event::mouse_position(&event)
|
||||
} else {
|
||||
// Since the mouse is not on the canvas, we cannot
|
||||
// use `offsetX`/`offsetY`.
|
||||
event::mouse_position_by_client(&event, &canvas)
|
||||
};
|
||||
handler(
|
||||
0,
|
||||
mouse_pos.to_physical(super::super::scale_factor()),
|
||||
event::mouse_modifiers(&event),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub fn remove_listeners(&mut self) {
|
||||
self.on_mouse_leave = None;
|
||||
self.on_mouse_enter = None;
|
||||
self.on_mouse_move = None;
|
||||
self.on_mouse_press = None;
|
||||
self.on_mouse_release = None;
|
||||
*self.on_mouse_leave_handler.borrow_mut() = None;
|
||||
}
|
||||
}
|
||||
111
src/platform_impl/web/web_sys/canvas/pointer_handler.rs
Normal file
111
src/platform_impl/web/web_sys/canvas/pointer_handler.rs
Normal file
@@ -0,0 +1,111 @@
|
||||
use super::event;
|
||||
use super::EventListenerHandle;
|
||||
use crate::dpi::PhysicalPosition;
|
||||
use crate::event::{ModifiersState, MouseButton};
|
||||
|
||||
use web_sys::PointerEvent;
|
||||
|
||||
pub(super) struct PointerHandler {
|
||||
on_cursor_leave: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
on_cursor_enter: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
on_cursor_move: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
on_pointer_press: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
on_pointer_release: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
}
|
||||
|
||||
impl PointerHandler {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
on_cursor_leave: None,
|
||||
on_cursor_enter: None,
|
||||
on_cursor_move: None,
|
||||
on_pointer_press: None,
|
||||
on_pointer_release: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_cursor_leave<F>(&mut self, canvas_common: &super::Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32),
|
||||
{
|
||||
self.on_cursor_leave = Some(canvas_common.add_event(
|
||||
"pointerout",
|
||||
move |event: PointerEvent| {
|
||||
handler(event.pointer_id());
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub fn on_cursor_enter<F>(&mut self, canvas_common: &super::Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32),
|
||||
{
|
||||
self.on_cursor_enter = Some(canvas_common.add_event(
|
||||
"pointerover",
|
||||
move |event: PointerEvent| {
|
||||
handler(event.pointer_id());
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub fn on_mouse_release<F>(&mut self, canvas_common: &super::Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, MouseButton, ModifiersState),
|
||||
{
|
||||
self.on_pointer_release = Some(canvas_common.add_user_event(
|
||||
"pointerup",
|
||||
move |event: PointerEvent| {
|
||||
handler(
|
||||
event.pointer_id(),
|
||||
event::mouse_button(&event),
|
||||
event::mouse_modifiers(&event),
|
||||
);
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub fn on_mouse_press<F>(&mut self, canvas_common: &super::Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, PhysicalPosition<f64>, MouseButton, ModifiersState),
|
||||
{
|
||||
let canvas = canvas_common.raw.clone();
|
||||
self.on_pointer_press = Some(canvas_common.add_user_event(
|
||||
"pointerdown",
|
||||
move |event: PointerEvent| {
|
||||
handler(
|
||||
event.pointer_id(),
|
||||
event::mouse_position(&event).to_physical(super::super::scale_factor()),
|
||||
event::mouse_button(&event),
|
||||
event::mouse_modifiers(&event),
|
||||
);
|
||||
canvas
|
||||
.set_pointer_capture(event.pointer_id())
|
||||
.expect("Failed to set pointer capture");
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub fn on_cursor_move<F>(&mut self, canvas_common: &super::Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, PhysicalPosition<f64>, ModifiersState),
|
||||
{
|
||||
self.on_cursor_move = Some(canvas_common.add_event(
|
||||
"pointermove",
|
||||
move |event: PointerEvent| {
|
||||
handler(
|
||||
event.pointer_id(),
|
||||
event::mouse_position(&event).to_physical(super::super::scale_factor()),
|
||||
event::mouse_modifiers(&event),
|
||||
);
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub fn remove_listeners(&mut self) {
|
||||
self.on_cursor_leave = None;
|
||||
self.on_cursor_enter = None;
|
||||
self.on_cursor_move = None;
|
||||
self.on_pointer_press = None;
|
||||
self.on_pointer_release = None;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use crate::dpi::LogicalPosition;
|
||||
use crate::event::{ModifiersState, MouseButton, MouseScrollDelta, ScanCode, VirtualKeyCode};
|
||||
|
||||
use std::convert::TryInto;
|
||||
use web_sys::{KeyboardEvent, MouseEvent, WheelEvent};
|
||||
use web_sys::{HtmlCanvasElement, KeyboardEvent, MouseEvent, WheelEvent};
|
||||
|
||||
pub fn mouse_button(event: &MouseEvent) -> MouseButton {
|
||||
match event.button() {
|
||||
@@ -29,13 +29,27 @@ pub fn mouse_position(event: &MouseEvent) -> LogicalPosition<f64> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mouse_position_by_client(
|
||||
event: &MouseEvent,
|
||||
canvas: &HtmlCanvasElement,
|
||||
) -> LogicalPosition<f64> {
|
||||
let bounding_client_rect = canvas.get_bounding_client_rect();
|
||||
LogicalPosition {
|
||||
x: event.client_x() as f64 - bounding_client_rect.x(),
|
||||
y: event.client_y() as f64 - bounding_client_rect.y(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mouse_scroll_delta(event: &WheelEvent) -> Option<MouseScrollDelta> {
|
||||
let x = event.delta_x();
|
||||
let y = event.delta_y();
|
||||
let y = -event.delta_y();
|
||||
|
||||
match event.delta_mode() {
|
||||
WheelEvent::DOM_DELTA_LINE => Some(MouseScrollDelta::LineDelta(x as f32, y as f32)),
|
||||
WheelEvent::DOM_DELTA_PIXEL => Some(MouseScrollDelta::PixelDelta(LogicalPosition { x, y })),
|
||||
WheelEvent::DOM_DELTA_PIXEL => {
|
||||
let delta = LogicalPosition::new(x, y).to_physical(super::scale_factor());
|
||||
Some(MouseScrollDelta::PixelDelta(delta))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -141,7 +155,7 @@ pub fn virtual_key_code(event: &KeyboardEvent) -> Option<VirtualKeyCode> {
|
||||
"Numpad9" => VirtualKeyCode::Numpad9,
|
||||
"AbntC1" => VirtualKeyCode::AbntC1,
|
||||
"AbntC2" => VirtualKeyCode::AbntC2,
|
||||
"NumpadAdd" => VirtualKeyCode::Add,
|
||||
"NumpadAdd" => VirtualKeyCode::NumpadAdd,
|
||||
"Quote" => VirtualKeyCode::Apostrophe,
|
||||
"Apps" => VirtualKeyCode::Apps,
|
||||
"At" => VirtualKeyCode::At,
|
||||
@@ -152,8 +166,8 @@ pub fn virtual_key_code(event: &KeyboardEvent) -> Option<VirtualKeyCode> {
|
||||
"Semicolon" => VirtualKeyCode::Semicolon,
|
||||
"Comma" => VirtualKeyCode::Comma,
|
||||
"Convert" => VirtualKeyCode::Convert,
|
||||
"NumpadDecimal" => VirtualKeyCode::Decimal,
|
||||
"NumpadDivide" => VirtualKeyCode::Divide,
|
||||
"NumpadDecimal" => VirtualKeyCode::NumpadDecimal,
|
||||
"NumpadDivide" => VirtualKeyCode::NumpadDivide,
|
||||
"Equal" => VirtualKeyCode::Equals,
|
||||
"Backquote" => VirtualKeyCode::Grave,
|
||||
"Kana" => VirtualKeyCode::Kana,
|
||||
@@ -167,7 +181,7 @@ pub fn virtual_key_code(event: &KeyboardEvent) -> Option<VirtualKeyCode> {
|
||||
"MediaSelect" => VirtualKeyCode::MediaSelect,
|
||||
"MediaStop" => VirtualKeyCode::MediaStop,
|
||||
"Minus" => VirtualKeyCode::Minus,
|
||||
"NumpadMultiply" => VirtualKeyCode::Multiply,
|
||||
"NumpadMultiply" => VirtualKeyCode::NumpadMultiply,
|
||||
"Mute" => VirtualKeyCode::Mute,
|
||||
"LaunchMyComputer" => VirtualKeyCode::MyComputer,
|
||||
"NavigateForward" => VirtualKeyCode::NavigateForward,
|
||||
@@ -190,7 +204,7 @@ pub fn virtual_key_code(event: &KeyboardEvent) -> Option<VirtualKeyCode> {
|
||||
"Slash" => VirtualKeyCode::Slash,
|
||||
"Sleep" => VirtualKeyCode::Sleep,
|
||||
"Stop" => VirtualKeyCode::Stop,
|
||||
"NumpadSubtract" => VirtualKeyCode::Subtract,
|
||||
"NumpadSubtract" => VirtualKeyCode::NumpadSubtract,
|
||||
"Sysrq" => VirtualKeyCode::Sysrq,
|
||||
"Tab" => VirtualKeyCode::Tab,
|
||||
"Underline" => VirtualKeyCode::Underline,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user