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).
This commit is contained in:
aiongg committed 2026-10-21 18:07:40 +00:00
1 parent 2be273826c
commit 894bf2d733
7 files changed
+210 -5

No files matched your search

+10 -2
View File
@@ -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) };
}
+24 -1
View File
@@ -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<CaretChange>) {
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 }
}
+122
View File
@@ -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<CaretArea>,
/// The caret this window has created, if any.
current: Option<CaretArea>,
}
impl SystemCaret {
pub fn set_focused(&mut self, focused: bool) -> Option<CaretChange> {
self.focused = focused;
self.update()
}
pub fn set_ime_allowed(&mut self, allowed: bool) -> Option<CaretChange> {
self.ime_allowed = allowed;
self.update()
}
pub fn set_area(&mut self, area: CaretArea) -> Option<CaretChange> {
self.area = Some(area);
self.update()
}
fn update(&mut self) -> Option<CaretChange> {
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 });
}
}
+1
View File
@@ -188,6 +188,7 @@ mod drop_handler;
mod event_loop;
mod icon;
mod ime;
mod ime_caret;
mod keyboard;
mod keyboard_layout;
mod monitor;
+15 -2
View File
@@ -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::<i32>(scale_factor).into();
let (width, height) = size.to_physical::<i32>(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);
})
}
@@ -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,
+35
View File
@@ -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"
);
}
}