From 894bf2d7338ce3f5663632f9cd083a4f1355c8e2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 05:03:02 +0000 Subject: [PATCH] W18: Windows: keep a hidden system caret at the IME cursor area Some IMEs place their composition and candidate windows at the system caret (GetCaretPos, GetGUIThreadInfo) and ignore ImmSetCandidateWindow: Sogou, and some Japanese IMEs. winit created no caret, so those windows didn't follow the text. A window that has the keyboard focus and allows IME now keeps a hidden caret the size of the last IME cursor area, created on focus or when IME is allowed, moved with set_ime_cursor_area, and destroyed before the window loses the focus (Windows has one caret per thread). The policy is plain Rust (ime_caret.rs), so its tests run on every platform through tests/ime_patches.rs, with a guard on its callers. Part of storytold/craft-libs#198 (item I6). --- src/platform_impl/windows/event_loop.rs | 12 ++- src/platform_impl/windows/ime.rs | 25 ++++- src/platform_impl/windows/ime_caret.rs | 122 ++++++++++++++++++++++ src/platform_impl/windows/mod.rs | 1 + src/platform_impl/windows/window.rs | 17 ++- src/platform_impl/windows/window_state.rs | 3 + tests/ime_patches.rs | 35 +++++++ 7 files changed, 210 insertions(+), 5 deletions(-) create mode 100644 src/platform_impl/windows/ime_caret.rs diff --git a/src/platform_impl/windows/event_loop.rs b/src/platform_impl/windows/event_loop.rs index dad5f2a5..19eed6bf 100644 --- a/src/platform_impl/windows/event_loop.rs +++ b/src/platform_impl/windows/event_loop.rs @@ -2143,7 +2143,11 @@ unsafe fn public_window_callback_inner( }, WM_SETFOCUS => { - let active_focus_changed = userdata.window_state_lock().set_focused(true); + let (active_focus_changed, caret) = { + let mut w = userdata.window_state_lock(); + (w.set_focused(true), w.system_caret.set_focused(true)) + }; + unsafe { ImeContext::update_system_caret(window, caret) }; if active_focus_changed { unsafe { gain_active_focus(window, userdata) }; } @@ -2151,7 +2155,11 @@ unsafe fn public_window_callback_inner( }, WM_KILLFOCUS => { - let active_focus_changed = userdata.window_state_lock().set_focused(false); + let (active_focus_changed, caret) = { + let mut w = userdata.window_state_lock(); + (w.set_focused(false), w.system_caret.set_focused(false)) + }; + unsafe { ImeContext::update_system_caret(window, caret) }; if active_focus_changed { unsafe { lose_active_focus(window, userdata) }; } diff --git a/src/platform_impl/windows/ime.rs b/src/platform_impl/windows/ime.rs index 62148df9..acb7413b 100644 --- a/src/platform_impl/windows/ime.rs +++ b/src/platform_impl/windows/ime.rs @@ -10,10 +10,13 @@ use windows_sys::Win32::UI::Input::Ime::{ ATTR_TARGET_NOTCONVERTED, CANDIDATEFORM, CFS_EXCLUDE, CFS_POINT, COMPOSITIONFORM, GCS_COMPATTR, GCS_COMPSTR, GCS_CURSORPOS, GCS_RESULTSTR, IACE_CHILDREN, IACE_DEFAULT, }; -use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_IMMENABLED}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CreateCaret, DestroyCaret, GetSystemMetrics, SetCaretPos, SM_IMMENABLED, +}; use crate::dpi::{Position, Size}; use crate::platform::windows::HWND; +use crate::platform_impl::platform::ime_caret::CaretChange; pub struct ImeContext { hwnd: HWND, @@ -160,6 +163,26 @@ 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) { + match change { + None => {}, + // A new caret is hidden, and this one is never shown. + Some(CaretChange::Create(area)) => unsafe { + if CreateCaret(hwnd, 0, area.width, area.height) != 0 { + SetCaretPos(area.x, area.y); + } + }, + Some(CaretChange::Move(area)) => unsafe { + SetCaretPos(area.x, area.y); + }, + Some(CaretChange::Destroy) => unsafe { + DestroyCaret(); + }, + } + } + unsafe fn system_has_ime() -> bool { unsafe { GetSystemMetrics(SM_IMMENABLED) != 0 } } diff --git a/src/platform_impl/windows/ime_caret.rs b/src/platform_impl/windows/ime_caret.rs new file mode 100644 index 00000000..91d93cd8 --- /dev/null +++ b/src/platform_impl/windows/ime_caret.rs @@ -0,0 +1,122 @@ +//! When a window keeps a hidden system caret at the IME cursor area. +//! +//! Some IMEs place their composition and candidate windows at the system caret +//! (`GetCaretPos`, `GetGUIThreadInfo`) and ignore `ImmSetCandidateWindow`: Sogou, and some +//! Japanese IMEs. A window that has the keyboard focus and allows IME keeps a hidden caret over +//! the last IME cursor area. Windows has one caret per thread, and a window must destroy it before +//! it loses the focus. +//! +//! This is plain Rust so that its tests run on every platform (`tests/ime_patches.rs`). + +/// An IME cursor area in physical client coordinates. Both sides are at least 1. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct CaretArea { + pub x: i32, + pub y: i32, + pub width: i32, + pub height: i32, +} + +impl CaretArea { + pub fn new(x: i32, y: i32, width: i32, height: i32) -> Self { + CaretArea { x, y, width: width.max(1), height: height.max(1) } + } +} + +/// What to do with the thread's system caret. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CaretChange { + /// `CreateCaret` at this size, then `SetCaretPos`. It replaces any caret the thread has. + Create(CaretArea), + /// `SetCaretPos`. + Move(CaretArea), + /// `DestroyCaret`. + Destroy, +} + +#[derive(Debug, Default)] +pub(crate) struct SystemCaret { + focused: bool, + ime_allowed: bool, + area: Option, + /// The caret this window has created, if any. + current: Option, +} + +impl SystemCaret { + pub fn set_focused(&mut self, focused: bool) -> Option { + self.focused = focused; + self.update() + } + + pub fn set_ime_allowed(&mut self, allowed: bool) -> Option { + self.ime_allowed = allowed; + self.update() + } + + pub fn set_area(&mut self, area: CaretArea) -> Option { + self.area = Some(area); + self.update() + } + + fn update(&mut self) -> Option { + let wanted = self.area.filter(|_| self.focused && self.ime_allowed); + match (std::mem::replace(&mut self.current, wanted), wanted) { + (None, None) => None, + (Some(_), None) => Some(CaretChange::Destroy), + (None, Some(new)) => Some(CaretChange::Create(new)), + (Some(old), Some(new)) if old == new => None, + (Some(old), Some(new)) if (old.width, old.height) == (new.width, new.height) => { + Some(CaretChange::Move(new)) + }, + (Some(_), Some(new)) => Some(CaretChange::Create(new)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn caret_exists_only_while_focused_with_ime_allowed() { + let area = CaretArea::new(10, 20, 2, 16); + let mut caret = SystemCaret::default(); + assert_eq!(caret.set_area(area), None); + assert_eq!(caret.set_focused(true), None); + assert_eq!(caret.set_ime_allowed(true), Some(CaretChange::Create(area))); + assert_eq!(caret.set_focused(false), Some(CaretChange::Destroy)); + assert_eq!(caret.set_focused(true), Some(CaretChange::Create(area))); + assert_eq!(caret.set_ime_allowed(false), Some(CaretChange::Destroy)); + assert_eq!(caret.set_ime_allowed(false), None); + } + + #[test] + fn caret_waits_for_a_cursor_area() { + let mut caret = SystemCaret::default(); + assert_eq!(caret.set_focused(true), None); + assert_eq!(caret.set_ime_allowed(true), None); + let area = CaretArea::new(0, 0, 1, 18); + assert_eq!(caret.set_area(area), Some(CaretChange::Create(area))); + } + + #[test] + fn caret_follows_the_cursor_area() { + let mut caret = SystemCaret::default(); + caret.set_focused(true); + caret.set_ime_allowed(true); + let first = CaretArea::new(10, 20, 1, 16); + assert_eq!(caret.set_area(first), Some(CaretChange::Create(first))); + assert_eq!(caret.set_area(first), None); + let moved = CaretArea::new(30, 20, 1, 16); + assert_eq!(caret.set_area(moved), Some(CaretChange::Move(moved))); + // A caret's size is fixed when it is created. + let taller = CaretArea::new(30, 20, 1, 24); + assert_eq!(caret.set_area(taller), Some(CaretChange::Create(taller))); + } + + #[test] + fn caret_area_is_never_empty() { + assert_eq!(CaretArea::new(5, 6, 0, -3), CaretArea { x: 5, y: 6, width: 1, height: 1 }); + } +} diff --git a/src/platform_impl/windows/mod.rs b/src/platform_impl/windows/mod.rs index 9bb02fd4..29d5c77d 100644 --- a/src/platform_impl/windows/mod.rs +++ b/src/platform_impl/windows/mod.rs @@ -188,6 +188,7 @@ mod drop_handler; mod event_loop; mod icon; mod ime; +mod ime_caret; mod keyboard; mod keyboard_layout; mod monitor; diff --git a/src/platform_impl/windows/window.rs b/src/platform_impl/windows/window.rs index 228c6f03..ad28730b 100644 --- a/src/platform_impl/windows/window.rs +++ b/src/platform_impl/windows/window.rs @@ -62,6 +62,7 @@ use crate::platform_impl::platform::drop_handler::FileDropHandler; use crate::platform_impl::platform::event_loop::{self, ActiveEventLoop, DESTROY_MSG_ID}; use crate::platform_impl::platform::icon::{self, IconType, WinCursor}; use crate::platform_impl::platform::ime::ImeContext; +use crate::platform_impl::platform::ime_caret::CaretArea; use crate::platform_impl::platform::keyboard::KeyEventBuilder; use crate::platform_impl::platform::monitor::{self, MonitorHandle}; use crate::platform_impl::platform::window_state::{ @@ -913,8 +914,15 @@ impl Window { let window = self.window; let state = self.window_state.clone(); self.thread_executor.execute_in_thread(move || unsafe { - let scale_factor = state.lock().unwrap().scale_factor; + let (scale_factor, caret) = { + let mut state = state.lock().unwrap(); + let scale_factor = state.scale_factor; + let (x, y) = spot.to_physical::(scale_factor).into(); + let (width, height) = size.to_physical::(scale_factor).into(); + (scale_factor, state.system_caret.set_area(CaretArea::new(x, y, width, height))) + }; ImeContext::current(window).set_ime_cursor_area(spot, size, scale_factor); + ImeContext::update_system_caret(window, caret); }); } @@ -923,8 +931,13 @@ impl Window { let window = self.window; let state = self.window_state.clone(); self.thread_executor.execute_in_thread(move || unsafe { - state.lock().unwrap().ime_allowed = allowed; + let caret = { + let mut state = state.lock().unwrap(); + state.ime_allowed = allowed; + state.system_caret.set_ime_allowed(allowed) + }; ImeContext::set_ime_allowed(window, allowed); + ImeContext::update_system_caret(window, caret); }) } diff --git a/src/platform_impl/windows/window_state.rs b/src/platform_impl/windows/window_state.rs index 92b9a07d..1f801ede 100644 --- a/src/platform_impl/windows/window_state.rs +++ b/src/platform_impl/windows/window_state.rs @@ -1,6 +1,7 @@ use crate::dpi::{PhysicalPosition, PhysicalSize, Size}; use crate::icon::Icon; use crate::keyboard::ModifiersState; +use crate::platform_impl::platform::ime_caret::SystemCaret; use crate::platform_impl::platform::{event_loop, util, Fullscreen, SelectedCursor}; use crate::window::{Theme, WindowAttributes}; use bitflags::bitflags; @@ -45,6 +46,7 @@ pub(crate) struct WindowState { pub ime_state: ImeState, pub ime_allowed: bool, + pub system_caret: SystemCaret, // Used by WM_NCACTIVATE, WM_SETFOCUS and WM_KILLFOCUS pub is_active: bool, @@ -169,6 +171,7 @@ impl WindowState { ime_state: ImeState::Disabled, ime_allowed: false, + system_caret: SystemCaret::default(), is_active: false, is_focused: false, diff --git a/tests/ime_patches.rs b/tests/ime_patches.rs index 86ca9728..8de2e352 100644 --- a/tests/ime_patches.rs +++ b/tests/ime_patches.rs @@ -195,3 +195,38 @@ fn macos_first_apple_korean_key_is_retried_once() { "insertText doesn't report to the retry policy" ); } + +// `SystemCaret` is plain Rust, so its policy tests run on every platform. +#[allow(dead_code)] +#[path = "../src/platform_impl/windows/ime_caret.rs"] +mod ime_caret; + +#[test] +fn windows_system_caret_follows_the_ime_cursor_area() { + // Some IMEs place their windows at the system caret and ignore `ImmSetCandidateWindow` + // (Sogou, some Japanese IMEs). winit 0.30.13 creates no caret, so they couldn't find the + // text being composed. A focused window that allows IME keeps a hidden caret over the IME + // cursor area, under the rules `SystemCaret` tests. + let window = source("windows/window.rs"); + let cursor_area = section(&window, "pub fn set_ime_cursor_area(", "\n }\n"); + assert!( + cursor_area.contains("state.system_caret.set_area(") + && cursor_area.contains("ImeContext::update_system_caret(window, caret);"), + "the caret doesn't follow the IME cursor area" + ); + let allowed = section(&window, "pub fn set_ime_allowed(", "\n }\n"); + assert!( + allowed.contains("state.system_caret.set_ime_allowed(allowed)") + && allowed.contains("ImeContext::update_system_caret(window, caret);"), + "allowing IME doesn't create or destroy the caret" + ); + let event_loop = source("windows/event_loop.rs"); + for (message, focused) in [("WM_SETFOCUS => {", "true"), ("WM_KILLFOCUS => {", "false")] { + let handler = section(&event_loop, message, "\n },\n"); + assert!( + handler.contains(&format!("w.system_caret.set_focused({focused})")) + && handler.contains("ImeContext::update_system_caret(window, caret)"), + "{message} doesn't update the caret" + ); + } +}