mirror of
https://github.com/storytold/winit.git
synced 2026-11-30 18:26:33 +01:00
Merge craft/0.30.13 into fix/windows-tool-window
This commit is contained in:
16 files changed
+404
-18
No files matched your search
@@ -60,6 +60,13 @@ jobs:
|
||||
- { name: 'iOS Aarch64', target: aarch64-apple-ios, os: macos-latest, }
|
||||
- { name: 'web', target: wasm32-unknown-unknown, os: ubuntu-latest, }
|
||||
exclude:
|
||||
# Rust 1.100 no longer ships host tools for i686-pc-windows-gnu, so the
|
||||
# stable-i686-pc-windows-gnu and nightly toolchains can't be installed. 1.70.0 still
|
||||
# covers the target.
|
||||
- toolchain: stable
|
||||
platform: { name: 'Windows 32bit GNU' }
|
||||
- toolchain: nightly
|
||||
platform: { name: 'Windows 32bit GNU' }
|
||||
# Android is tested on stable-3
|
||||
- toolchain: '1.70.0'
|
||||
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||
@@ -107,6 +114,10 @@ jobs:
|
||||
|
||||
- name: Generate lockfile
|
||||
# Also updates the crates.io index
|
||||
env:
|
||||
# This step runs with the runner's cargo, before the matrix toolchain is installed.
|
||||
# On the 1.70.0 jobs, it picks dependency versions whose `rust-version` allows 1.70.0.
|
||||
CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS: ${{ matrix.toolchain == '1.70.0' && 'fallback' || 'allow' }}
|
||||
run: |
|
||||
cargo generate-lockfile
|
||||
cargo update -p ahash --precise 0.8.7
|
||||
@@ -115,9 +126,13 @@ jobs:
|
||||
cargo update -p objc2-encode --precise 4.0.3
|
||||
cargo update -p orbclient --precise 0.3.47
|
||||
cargo update -p image --precise 0.25.0
|
||||
cargo update -p gethostname@1.1.0 --precise 1.0.2
|
||||
cargo update -p gethostname@1 --precise 1.0.2
|
||||
cargo update -p unicode-ident --precise 1.0.10
|
||||
cargo update -p syn --precise 2.0.114
|
||||
cargo update -p serde --precise 1.0.228
|
||||
cargo update -p foreign-types-macros --precise 0.2.3
|
||||
cargo update -p tracing-web --precise 0.1.3
|
||||
cargo update -p wasm-bindgen -p wasm-bindgen-futures -p js-sys -p web-sys
|
||||
cargo update -p syn@2 --precise 2.0.114
|
||||
|
||||
- name: Install GCC Multilib
|
||||
if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
|
||||
|
||||
@@ -34,6 +34,8 @@ input lives in `craft-tablet`).
|
||||
| W25 | `eb4007da` | X11/Wayland: `platform::latin_layout::KeyEventExtLatinLayout`, the key on the first Latin layout group for shortcuts on non-Latin layouts | none; to be proposed | upstream release with an equivalent | storytold/winit PR #5; craft-libs#198 (K2) |
|
||||
| W26 | `2b9cd1cf` | macOS: replaced text is deleted by UTF-8 byte count with the commit (`WindowExtMacOS::take_ime_delete_surrounding`, same shape as W27) | master: `Ime::DeleteSurrounding` (a new `Ime` variant breaks 0.30 matchers) | the egui → 0.31 move | storytold/winit PR #6 (`d103edae`) |
|
||||
| W27 | `f40c76a2` | Wayland: text-input-v3 surrounding text (`WindowExtWayland::set_ime_surrounding_text`, `set_ime_surrounding_text_with_change_cause`, `clear_ime_surrounding_text`), delete-surrounding attached to the commit (`take_ime_delete_surrounding` → `ImeDeleteSurrounding { before_bytes, after_bytes }`), per-seat preedit ownership and outgoing state waiting for a matching `done` (E21b) | master has both as core API (`Ime::DeleteSurrounding`) | the egui → 0.31 move | storytold/winit PR #7; craft-libs#198 (I7) |
|
||||
| W30 | this commit | Linux: the first window created without an activation token takes the launcher's (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and hands it back as one given through `with_activation_token` would be (`platform_impl/linux/startup_token.rs`), so GNOME drops the busy cursor and a Wayland window opens focused; later windows don't reuse the spent token, an empty or oversized (over 1,024 bytes) token is ignored, and the variable stays in the environment (changing it while other threads may read it is unsound) | none; to be proposed | upstream release that hands the launcher's token to the first window | pdfcraft vendor patch (14); cadcraft#2030 (`tests/winit_startup_token.rs`) |
|
||||
| W36 | `924c77b4` | Windows: an Alt code (Alt+0181 for µ) types its character; Windows sends it in `WM_CHAR` after Alt's key-up, which the keyboard builder dropped as IME text. It goes on a press of an unidentified key (as `VK_PACKET` is reported) with a release after it | none found; to be proposed | upstream release with an equivalent | pdfcraft#5746 |
|
||||
|
||||
Conflict resolved by hand: `wayland/seat/mod.rs` `remove_seat` keeps all three cleanups — cancel a
|
||||
file drag (W15), remove the seat from winit's clipboard (W15), destroy the seat's text input (W2).
|
||||
|
||||
@@ -42,6 +42,11 @@ skip = [
|
||||
{ crate = "bitflags@1", reason = "the ecosystem is in the process of migrating" },
|
||||
{ crate = "rustix@0.38", reason = "the ecosystem is in the process of migrating" },
|
||||
{ crate = "linux-raw-sys@0.4", reason = "the ecosystem is in the process of migrating" },
|
||||
{ crate = "syn@2", reason = "the ecosystem is in the process of migrating" },
|
||||
{ crate = "thiserror@1", reason = "the ecosystem is in the process of migrating" },
|
||||
{ crate = "thiserror-impl@1", reason = "the ecosystem is in the process of migrating" },
|
||||
{ crate = "jni-sys@0.3", reason = "jni-sys 0.3.1 depends on jni-sys 0.4" },
|
||||
{ crate = "redox_syscall@0.4", reason = "winit and orbclient depend on different versions" },
|
||||
]
|
||||
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
||||
|
||||
@@ -52,6 +57,7 @@ interpreted = "deny"
|
||||
[[bans.build.bypass]]
|
||||
allow = [
|
||||
{ path = "generate-bindings.sh", checksum = "268ec23248218d779e33853cdc60e2985e70214ff004716cd734270de1f6b561" },
|
||||
{ path = "android-games-sdk/import-games-sdk.sh", checksum = "98ed2741804d10ddbd8d035557897ab1edc5257705759377271dcb4ba5636446" },
|
||||
]
|
||||
crate = "android-activity"
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Opt-in native protocol probe; driven by a private compositor, never a user's clipboard.
|
||||
#[cfg(all(unix, not(target_os = "macos"), feature = "wayland"))]
|
||||
#[cfg(wayland_platform)]
|
||||
mod probe {
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -212,10 +212,10 @@ mod probe {
|
||||
event_loop.run_app(&mut app).expect("native probe event loop");
|
||||
}
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos"), feature = "wayland"))]
|
||||
#[cfg(wayland_platform)]
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
fn main() {
|
||||
#[cfg(all(unix, not(target_os = "macos"), feature = "wayland"))]
|
||||
#[cfg(wayland_platform)]
|
||||
probe::run();
|
||||
}
|
||||
+3
-3
@@ -548,10 +548,10 @@ pub enum KeyCode {
|
||||
NumpadMemoryStore,
|
||||
/// <kbd>M</kbd> Subtract current entry from the value stored in memory.
|
||||
NumpadMemorySubtract,
|
||||
/// <kbd>*</kbd> on a keyboard. For use with numpads that provide mathematical
|
||||
/// operations (<kbd>+</kbd>, <kbd>-</kbd> <kbd>*</kbd> and <kbd>/</kbd>).
|
||||
/// <kbd>\*</kbd> on a keyboard. For use with numpads that provide mathematical
|
||||
/// operations (<kbd>+</kbd>, <kbd>-</kbd> <kbd>\*</kbd> and <kbd>/</kbd>).
|
||||
///
|
||||
/// Use `NumpadStar` for the <kbd>*</kbd> key on phones and remote controls.
|
||||
/// Use `NumpadStar` for the <kbd>\*</kbd> key on phones and remote controls.
|
||||
NumpadMultiply,
|
||||
/// <kbd>(</kbd> Found on the Microsoft Natural Keyboard.
|
||||
NumpadParenLeft,
|
||||
|
||||
@@ -28,10 +28,10 @@ use crate::event_loop::{ActiveEventLoop, AsyncRequestSerial};
|
||||
use crate::window::{ActivationToken, Window, WindowAttributes};
|
||||
|
||||
/// The variable which is used mostly on X11.
|
||||
const X11_VAR: &str = "DESKTOP_STARTUP_ID";
|
||||
pub(crate) const X11_VAR: &str = "DESKTOP_STARTUP_ID";
|
||||
|
||||
/// The variable which is used mostly on Wayland.
|
||||
const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN";
|
||||
pub(crate) const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN";
|
||||
|
||||
pub trait EventLoopExtStartupNotify {
|
||||
/// Read the token from the environment.
|
||||
|
||||
@@ -25,6 +25,8 @@ use crate::window::{Window, WindowAttributes, WindowId};
|
||||
|
||||
pub use crate::window::Theme;
|
||||
|
||||
// The clipboard needs the Wayland backend, which docs built for other platforms (`docsrs`) lack.
|
||||
#[cfg(wayland_platform)]
|
||||
pub use crate::platform_impl::wayland::clipboard::{
|
||||
ClipboardContent, ClipboardError, ImageClaimReservation, InputOriginToken, PngBytes,
|
||||
PngBytesWriter, RegularTransferHandle, SelectionClaim, TransferHandle, TransferOptions,
|
||||
@@ -37,6 +39,7 @@ pub trait ActiveEventLoopExtWayland {
|
||||
fn is_wayland(&self) -> bool;
|
||||
|
||||
/// The clipboard of this event loop, or [`None`] if it doesn't use Wayland.
|
||||
#[cfg(wayland_platform)]
|
||||
fn clipboard(&self) -> Option<Clipboard>;
|
||||
}
|
||||
|
||||
@@ -46,6 +49,7 @@ impl ActiveEventLoopExtWayland for ActiveEventLoop {
|
||||
self.p.is_wayland()
|
||||
}
|
||||
|
||||
#[cfg(wayland_platform)]
|
||||
fn clipboard(&self) -> Option<Clipboard> {
|
||||
#[allow(clippy::single_match)]
|
||||
match &self.p {
|
||||
@@ -81,11 +85,13 @@ impl ActiveEventLoopExtWayland for ActiveEventLoop {
|
||||
/// `input_origin` and `reserve_image_claim` are synchronous state transitions used at that same
|
||||
/// input/output boundary. This is a caller contract; the type does not inspect which thread is
|
||||
/// currently calling it.
|
||||
#[cfg(wayland_platform)]
|
||||
#[derive(Clone)]
|
||||
pub struct Clipboard {
|
||||
state: Weak<crate::platform_impl::wayland::ClipboardState>,
|
||||
}
|
||||
|
||||
#[cfg(wayland_platform)]
|
||||
impl Clipboard {
|
||||
/// The clipboard of the winit event loop connected through `display`, a `wl_display`
|
||||
/// pointer such as the one in its `WaylandDisplayHandle`, if that event loop still exists.
|
||||
@@ -281,6 +287,7 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(wayland_platform)]
|
||||
impl fmt::Debug for Clipboard {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Clipboard").finish_non_exhaustive()
|
||||
|
||||
@@ -25,6 +25,7 @@ use crate::event_loop::{
|
||||
use crate::icon::Icon;
|
||||
use crate::keyboard::Key;
|
||||
use crate::platform::pump_events::PumpStatus;
|
||||
use crate::platform::startup_notify;
|
||||
#[cfg(x11_platform)]
|
||||
use crate::platform::x11::{WindowType as XWindowType, XlibErrorHook};
|
||||
use crate::window::{
|
||||
@@ -38,6 +39,7 @@ pub(crate) use crate::icon::RgbaIcon as PlatformIcon;
|
||||
pub(crate) use crate::platform_impl::Fullscreen;
|
||||
|
||||
pub(crate) mod common;
|
||||
mod startup_token;
|
||||
#[cfg(wayland_platform)]
|
||||
pub(crate) mod wayland;
|
||||
#[cfg(x11_platform)]
|
||||
@@ -290,16 +292,23 @@ impl Window {
|
||||
#[inline]
|
||||
pub(crate) fn new(
|
||||
window_target: &ActiveEventLoop,
|
||||
attribs: WindowAttributes,
|
||||
mut attribs: WindowAttributes,
|
||||
) -> Result<Self, RootOsError> {
|
||||
let given = attribs.platform_specific.activation_token.take();
|
||||
match *window_target {
|
||||
#[cfg(wayland_platform)]
|
||||
ActiveEventLoop::Wayland(ref window_target) => {
|
||||
wayland::Window::new(window_target, attribs).map(Window::Wayland)
|
||||
startup_token::with_token(given, startup_notify::WAYLAND_VAR, |token| {
|
||||
attribs.platform_specific.activation_token = token;
|
||||
wayland::Window::new(window_target, attribs).map(Window::Wayland)
|
||||
})
|
||||
},
|
||||
#[cfg(x11_platform)]
|
||||
ActiveEventLoop::X(ref window_target) => {
|
||||
x11::Window::new(window_target, attribs).map(Window::X)
|
||||
startup_token::with_token(given, startup_notify::X11_VAR, |token| {
|
||||
attribs.platform_specific.activation_token = token;
|
||||
x11::Window::new(window_target, attribs).map(Window::X)
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
//! The launcher's activation token for the first window (CADCraft patch, from PdfCraft).
|
||||
//!
|
||||
//! A launcher with `StartupNotify=true` passes an activation token in the environment
|
||||
//! (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and shows a busy cursor
|
||||
//! until a window hands it back. winit hands back only a token given through
|
||||
//! `WindowAttributesExtStartupNotify::with_activation_token`, and eframe never gives one, so
|
||||
//! GNOME kept the busy cursor until its 15-second timeout and the window opened without focus.
|
||||
//!
|
||||
//! The first window the process creates without a token now takes the one in the environment.
|
||||
//! Later windows never do: the token is spent once a window has been created with it. A window
|
||||
//! that fails to be created leaves it unspent, so a retry still hands it back. The variable is
|
||||
//! left in the environment, unlike `reset_activation_token_env`, because changing the
|
||||
//! environment while other threads may read it is unsound, and an application can start
|
||||
//! threads before its first window.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use crate::window::ActivationToken;
|
||||
|
||||
/// Longer tokens are ignored. Launchers make tokens of a few dozen bytes; on X11 the token is
|
||||
/// written to a window property and sent to the window manager, and an oversized one would
|
||||
/// fail window creation.
|
||||
const MAX_TOKEN_LEN: usize = 1024;
|
||||
|
||||
static TAKEN: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Creates a window with `given` if there is one, else, for the process's first window, the
|
||||
/// environment's value of `var`. The launcher's token is spent only when `create` succeeds.
|
||||
pub(crate) fn with_token<T, E>(
|
||||
given: Option<ActivationToken>,
|
||||
var: &str,
|
||||
create: impl FnOnce(Option<ActivationToken>) -> Result<T, E>,
|
||||
) -> Result<T, E> {
|
||||
create_with(given, &TAKEN, from_env(var), create)
|
||||
}
|
||||
|
||||
/// Reads the launcher's token from the environment variable `var`.
|
||||
fn from_env(var: &str) -> impl FnOnce() -> Option<String> + '_ {
|
||||
move || std::env::var(var).ok()
|
||||
}
|
||||
|
||||
fn create_with<T, E>(
|
||||
given: Option<ActivationToken>,
|
||||
taken: &AtomicBool,
|
||||
read: impl FnOnce() -> Option<String>,
|
||||
create: impl FnOnce(Option<ActivationToken>) -> Result<T, E>,
|
||||
) -> Result<T, E> {
|
||||
let first = !taken.load(Ordering::Relaxed);
|
||||
let token = if given.is_some() || !first {
|
||||
given
|
||||
} else {
|
||||
read()
|
||||
.filter(|token| !token.is_empty() && token.len() <= MAX_TOKEN_LEN)
|
||||
.map(ActivationToken::from_raw)
|
||||
};
|
||||
let window = create(token)?;
|
||||
// The first window spends the launcher's token, whether or not it was given one.
|
||||
taken.store(true, Ordering::Relaxed);
|
||||
Ok(window)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn token(raw: &str) -> Option<ActivationToken> {
|
||||
Some(ActivationToken::from_raw(raw.to_owned()))
|
||||
}
|
||||
|
||||
/// The token a successfully created window received.
|
||||
fn choose(
|
||||
given: Option<ActivationToken>,
|
||||
taken: &AtomicBool,
|
||||
read: impl FnOnce() -> Option<String>,
|
||||
) -> Option<ActivationToken> {
|
||||
create_with(given, taken, read, Ok::<_, ()>).ok().flatten()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_window_takes_the_launchers_token() {
|
||||
let taken = AtomicBool::new(false);
|
||||
assert_eq!(
|
||||
choose(None, &taken, || Some("gnome-shell/PdfCraft/1234".into())),
|
||||
token("gnome-shell/PdfCraft/1234")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_window_does_not_reuse_the_spent_token() {
|
||||
let taken = AtomicBool::new(false);
|
||||
assert!(choose(None, &taken, || Some("t".into())).is_some());
|
||||
assert_eq!(choose(None, &taken, || Some("t".into())), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_given_token_wins_and_still_spends_the_launchers() {
|
||||
let taken = AtomicBool::new(false);
|
||||
assert_eq!(choose(token("mine"), &taken, || Some("env".into())), token("mine"));
|
||||
assert_eq!(choose(None, &taken, || Some("env".into())), None);
|
||||
assert_eq!(choose(token("again"), &taken, || Some("env".into())), token("again"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_empty_or_oversized_token_is_ignored() {
|
||||
assert_eq!(choose(None, &AtomicBool::new(false), || None), None);
|
||||
assert_eq!(choose(None, &AtomicBool::new(false), || Some(String::new())), None);
|
||||
let long = "x".repeat(MAX_TOKEN_LEN + 1);
|
||||
assert_eq!(choose(None, &AtomicBool::new(false), || Some(long)), None);
|
||||
let limit = "x".repeat(MAX_TOKEN_LEN);
|
||||
assert!(choose(None, &AtomicBool::new(false), || Some(limit)).is_some());
|
||||
}
|
||||
|
||||
/// The variable the child below reads its token from.
|
||||
const VAR: &str = "WINIT_W30_TEST_ACTIVATION_TOKEN";
|
||||
/// Set only in the child: the token it must take, or empty for none.
|
||||
const EXPECT: &str = "WINIT_W30_TEST_EXPECT";
|
||||
|
||||
#[test]
|
||||
fn the_token_is_read_from_the_variable_when_set_and_not_when_cleared() {
|
||||
// The environment is given to a child process rather than changed here: `set_var` while
|
||||
// other test threads run is the unsoundness this module avoids by leaving the variable.
|
||||
let name = concat!(module_path!(), "::the_first_window_reads_the_variable_in_a_child");
|
||||
let name = name.split_once("::").unwrap().1;
|
||||
for value in [Some("gnome-shell/CADCraft/42"), None] {
|
||||
let mut child = std::process::Command::new(std::env::current_exe().unwrap());
|
||||
child.args([name, "--exact", "--test-threads=1"]).env(EXPECT, value.unwrap_or(""));
|
||||
match value {
|
||||
Some(value) => child.env(VAR, value),
|
||||
None => child.env_remove(VAR),
|
||||
};
|
||||
let out = child.output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{value:?}: {stdout}{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
assert!(stdout.contains("1 passed"), "{value:?}: the child ran no test: {stdout}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_window_reads_the_variable_in_a_child() {
|
||||
let Some(expect) = std::env::var_os(EXPECT) else { return };
|
||||
let expect = Some(expect.into_string().unwrap()).filter(|e| !e.is_empty());
|
||||
let received = choose(None, &AtomicBool::new(false), from_env(VAR));
|
||||
assert_eq!(received, expect.as_deref().and_then(token));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_window_leaves_the_token_for_a_retry() {
|
||||
let taken = AtomicBool::new(false);
|
||||
let failed = create_with(
|
||||
None,
|
||||
&taken,
|
||||
|| Some("t".into()),
|
||||
|received| {
|
||||
assert_eq!(received, token("t"));
|
||||
Err::<(), _>("no window")
|
||||
},
|
||||
);
|
||||
assert_eq!(failed, Err("no window"));
|
||||
assert_eq!(choose(None, &taken, || Some("t".into())), token("t"));
|
||||
assert_eq!(choose(None, &taken, || Some("t".into())), None);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,10 @@ mod macos;
|
||||
#[cfg(orbital_platform)]
|
||||
mod orbital;
|
||||
#[cfg(web_platform)]
|
||||
// The code `#[wasm_bindgen]` generates in newer wasm-bindgen releases uses `const` features
|
||||
// stable since Rust 1.77, which clippy reports against the 1.70 MSRV. The MSRV build locks an
|
||||
// older wasm-bindgen.
|
||||
#[allow(clippy::incompatible_msrv)]
|
||||
mod web;
|
||||
#[cfg(windows_platform)]
|
||||
mod windows;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// This is a simple implementation of support for Windows Dark Mode,
|
||||
/// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode
|
||||
/// which is inspired by the solution in <https://github.com/ysc3839/win32-darkmode>
|
||||
use std::{ffi::c_void, ptr};
|
||||
|
||||
use crate::utils::Lazy;
|
||||
|
||||
@@ -182,7 +182,7 @@ impl ImeContext {
|
||||
|
||||
/// Applies a change to the hidden system caret that follows the IME cursor area
|
||||
/// (`ime_caret.rs`). Runs on the window's thread, which owns the caret.
|
||||
pub unsafe fn update_system_caret(hwnd: HWND, change: Option<CaretChange>) {
|
||||
pub(crate) unsafe fn update_system_caret(hwnd: HWND, change: Option<CaretChange>) {
|
||||
match change {
|
||||
None => {},
|
||||
// A new caret is hidden, and this one is never shown.
|
||||
|
||||
@@ -61,7 +61,9 @@ pub struct MessageAsKeyEvent {
|
||||
/// the key.
|
||||
///
|
||||
/// Key release messages are a bit different due to the fact that they don't contribute to
|
||||
/// text input. The "sequence" only consists of one WM_KEYUP / WM_SYSKEYUP event.
|
||||
/// text input. The "sequence" only consists of one WM_KEYUP / WM_SYSKEYUP event. The exception
|
||||
/// is Alt's release ending an Alt code, which the code's WM_CHAR follows; that character is
|
||||
/// reported as a press and a release of its own (`PartialKeyEventInfo::alt_code`).
|
||||
pub struct KeyEventBuilder {
|
||||
event_info: Mutex<Option<PartialKeyEventInfo>>,
|
||||
pending: PendingEventQueue<MessageAsKeyEvent>,
|
||||
@@ -260,7 +262,35 @@ impl KeyEventBuilder {
|
||||
let key = layout.get_key(mod_no_ctrl, num_lock_on, vkey, physical_key);
|
||||
event_info.text = PartialText::Text(key.to_text().map(SmolStr::new));
|
||||
}
|
||||
let alt_code = event_info.alt_code;
|
||||
let ev = event_info.finalize();
|
||||
if alt_code {
|
||||
// No key was pressed for the character, so none is left down: its
|
||||
// release follows the press. `pending_token` is earlier and still
|
||||
// incomplete, so completing the release dispatches nothing yet.
|
||||
let release = KeyEvent {
|
||||
state: ElementState::Released,
|
||||
text: None,
|
||||
platform_specific: KeyEventExtra {
|
||||
text_with_all_modifiers: None,
|
||||
key_without_modifiers: ev
|
||||
.platform_specific
|
||||
.key_without_modifiers
|
||||
.clone(),
|
||||
},
|
||||
..ev.clone()
|
||||
};
|
||||
let release_token = self.pending.add_pending();
|
||||
let early =
|
||||
self.pending.complete_pending(release_token, MessageAsKeyEvent {
|
||||
event: release,
|
||||
is_synthetic: false,
|
||||
});
|
||||
debug_assert!(
|
||||
early.is_empty(),
|
||||
"the release went out before its press"
|
||||
);
|
||||
}
|
||||
MatchResult::MessagesToDispatch(self.pending.complete_pending(
|
||||
pending_token,
|
||||
MessageAsKeyEvent { event: ev, is_synthetic: false },
|
||||
@@ -284,6 +314,16 @@ impl KeyEventBuilder {
|
||||
// It's important that we create the pending token before reading the next
|
||||
// message.
|
||||
let next_msg = next_kbd_msg(hwnd);
|
||||
// An Alt code types its character when Alt is released: the `WM_CHAR`
|
||||
// follows Alt's key-up, and with no press for the `WM_CHAR` branch to add it
|
||||
// to, it was dropped as IME text. It goes on a press of its own instead
|
||||
// (storytold/pdfcraft#5746).
|
||||
let alt_released = matches!(event_info.vkey, VK_MENU | VK_LMENU | VK_RMENU);
|
||||
if alt_released
|
||||
&& next_msg.is_some_and(|m| matches!(m.message, WM_CHAR | WM_SYSCHAR))
|
||||
{
|
||||
*self.event_info.lock().unwrap() = Some(PartialKeyEventInfo::alt_code());
|
||||
}
|
||||
let mut valid_event_info = Some(event_info);
|
||||
if let Some(next_msg) = next_msg {
|
||||
let mut layouts = LAYOUT_CACHE.lock().unwrap();
|
||||
@@ -457,6 +497,7 @@ impl KeyEventBuilder {
|
||||
location: get_location(scancode, locale_id),
|
||||
utf16parts: Vec::with_capacity(8),
|
||||
text: PartialText::Text(text.clone()),
|
||||
alt_code: false,
|
||||
};
|
||||
|
||||
let mut event = event_info.finalize();
|
||||
@@ -498,9 +539,32 @@ struct PartialKeyEventInfo {
|
||||
utf16parts: Vec<u16>,
|
||||
|
||||
text: PartialText,
|
||||
|
||||
/// The press an Alt code's character is reported on ([`Self::alt_code`]), which a release
|
||||
/// follows at once.
|
||||
alt_code: bool,
|
||||
}
|
||||
|
||||
impl PartialKeyEventInfo {
|
||||
/// The press that carries an Alt code's character. Holding Alt and typing a number on the
|
||||
/// number pad (Alt+0181 for µ) makes Windows send the character in `WM_CHAR` after Alt is
|
||||
/// released, with no key press of its own. It is reported like a character injected with
|
||||
/// `VK_PACKET`: a press of an unidentified key, whose text and logical key are the character.
|
||||
fn alt_code() -> Self {
|
||||
PartialKeyEventInfo {
|
||||
vkey: 0,
|
||||
key_state: ElementState::Pressed,
|
||||
is_repeat: false,
|
||||
physical_key: PhysicalKey::Unidentified(NativeKeyCode::Unidentified),
|
||||
location: KeyLocation::Standard,
|
||||
logical_key: PartialLogicalKey::TextOr(Key::Unidentified(NativeKey::Unidentified)),
|
||||
key_without_modifiers: Key::Unidentified(NativeKey::Unidentified),
|
||||
utf16parts: Vec::with_capacity(8),
|
||||
text: PartialText::System(Vec::new()),
|
||||
alt_code: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_message(
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
@@ -590,6 +654,7 @@ impl PartialKeyEventInfo {
|
||||
location,
|
||||
utf16parts: Vec::with_capacity(8),
|
||||
text: PartialText::System(Vec::new()),
|
||||
alt_code: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1250,3 +1315,102 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
_ => return PhysicalKey::Unidentified(NativeKeyCode::Windows(scancode as u16)),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod alt_code_tests {
|
||||
use std::{mem, ptr};
|
||||
|
||||
use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM};
|
||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{VK_MENU, VK_RETURN};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
CreateWindowExW, DestroyWindow, PeekMessageW, PostMessageW, HWND_MESSAGE, MSG, PM_REMOVE,
|
||||
WM_CHAR, WM_KEYUP, WM_SYSKEYUP,
|
||||
};
|
||||
|
||||
use super::{KeyEventBuilder, MessageAsKeyEvent};
|
||||
use crate::event::ElementState;
|
||||
use crate::keyboard::{Key, NamedKey};
|
||||
use crate::platform_impl::platform::event_loop::ProcResult;
|
||||
use crate::platform_impl::platform::util;
|
||||
|
||||
/// The lParam of a key's release: repeat count 1, the key's scan code, previous state down,
|
||||
/// transition up.
|
||||
fn released(scancode: u32) -> LPARAM {
|
||||
(1 | scancode << 16 | 1 << 30 | 1 << 31) as LPARAM
|
||||
}
|
||||
|
||||
/// A key release (`WM_KEYUP` or `WM_SYSKEYUP`), then the `WM_CHAR` Windows queues after it,
|
||||
/// through one builder: the events for the release and for the character.
|
||||
fn release_then_char(
|
||||
up_msg: u32,
|
||||
vkey: u16,
|
||||
scancode: u32,
|
||||
ch: char,
|
||||
) -> (Vec<MessageAsKeyEvent>, Vec<MessageAsKeyEvent>) {
|
||||
let class: Vec<u16> = "STATIC\0".encode_utf16().collect();
|
||||
let window: HWND = unsafe {
|
||||
CreateWindowExW(
|
||||
0,
|
||||
class.as_ptr(),
|
||||
ptr::null(),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
HWND_MESSAGE,
|
||||
0,
|
||||
util::get_instance_handle(),
|
||||
ptr::null(),
|
||||
)
|
||||
};
|
||||
assert_ne!(window, 0);
|
||||
let lparam = released(scancode);
|
||||
assert_ne!(unsafe { PostMessageW(window, WM_CHAR, ch as WPARAM, lparam) }, 0);
|
||||
let builder = KeyEventBuilder::default();
|
||||
let mut result = ProcResult::DefWindowProc(0);
|
||||
let release = builder.process_message(window, up_msg, vkey as WPARAM, lparam, &mut result);
|
||||
let mut msg: MSG = unsafe { mem::zeroed() };
|
||||
assert_ne!(unsafe { PeekMessageW(&mut msg, window, WM_CHAR, WM_CHAR, PM_REMOVE) }, 0);
|
||||
let typed =
|
||||
builder.process_message(window, msg.message, msg.wParam, msg.lParam, &mut result);
|
||||
unsafe { DestroyWindow(window) };
|
||||
(release, typed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alt_code_types_its_character() {
|
||||
// Alt+0181: Windows sends µ after Alt's release (storytold/pdfcraft#5746).
|
||||
assert_alt_code_types(WM_KEYUP);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alt_code_types_its_character_after_a_syskeyup() {
|
||||
// Alt's release can also arrive as `WM_SYSKEYUP`; the builder treats both the same.
|
||||
assert_alt_code_types(WM_SYSKEYUP);
|
||||
}
|
||||
|
||||
fn assert_alt_code_types(up_msg: u32) {
|
||||
let (release, typed) = release_then_char(up_msg, VK_MENU, 0x38, 'µ');
|
||||
let [alt] = release.as_slice() else {
|
||||
panic!("{} events for Alt's release", release.len())
|
||||
};
|
||||
assert_eq!(alt.event.logical_key, Key::Named(NamedKey::Alt));
|
||||
assert_eq!(alt.event.state, ElementState::Released);
|
||||
let [press, up] = typed.as_slice() else { panic!("{} events for µ", typed.len()) };
|
||||
assert_eq!(press.event.state, ElementState::Pressed);
|
||||
assert_eq!(press.event.text.as_deref(), Some("µ"));
|
||||
assert_eq!(press.event.logical_key, Key::Character("µ".into()));
|
||||
assert_eq!(up.event.state, ElementState::Released);
|
||||
assert_eq!(up.event.text, None);
|
||||
assert_eq!(up.event.physical_key, press.event.physical_key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_character_after_another_release_is_still_left_to_the_ime() {
|
||||
// Only Alt's release ends an Alt code; a character queued after any other release is
|
||||
// input method text, which reaches the app as `Ime` events.
|
||||
let (_, typed) = release_then_char(WM_KEYUP, VK_RETURN, 0x1c, 'x');
|
||||
assert!(typed.is_empty(), "{} events for x", typed.len());
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,13 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The source with `\n` line endings: a Windows checkout has `\r\n` (`* text=auto`), and some
|
||||
/// tests match code that spans lines.
|
||||
fn source(path: &str) -> String {
|
||||
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/platform_impl").join(path);
|
||||
std::fs::read_to_string(&path).unwrap_or_else(|err| panic!("{}: {err}", path.display()))
|
||||
std::fs::read_to_string(&path)
|
||||
.unwrap_or_else(|err| panic!("{}: {err}", path.display()))
|
||||
.replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
/// The text after `start`, up to the first `end`.
|
||||
|
||||
@@ -6,9 +6,13 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The source with `\n` line endings: a Windows checkout has `\r\n` (`* text=auto`), and some
|
||||
/// tests match code that spans lines.
|
||||
fn source(path: &str) -> String {
|
||||
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/platform_impl").join(path);
|
||||
std::fs::read_to_string(&path).unwrap_or_else(|err| panic!("{}: {err}", path.display()))
|
||||
std::fs::read_to_string(&path)
|
||||
.unwrap_or_else(|err| panic!("{}: {err}", path.display()))
|
||||
.replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
/// The text after `start`, up to the first `end`.
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# documentation: https://github.com/crate-ci/typos/blob/master/docs/reference.md
|
||||
|
||||
[default]
|
||||
extend-ignore-re = [
|
||||
"6a87addd", # A commit SHA in PATCHES.md and docs/egui-037-migration-plan.md
|
||||
]
|
||||
|
||||
[default.extend-identifiers]
|
||||
ptd = "ptd" # From windows_sys::Win32::System::Com::FORMATETC { ptd, ..}
|
||||
TME_LEAVE = "TME_LEAVE" # From windows_sys::Win32::UI::Input::KeyboardAndMouse::TME_LEAVE
|
||||
|
||||
Reference in new issue
Block a user