mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-10-14 19:27:04 -04:00
macOS: the first Apple Korean key in a fresh PdfCraft composes (winit#4744) (#680)
* macOS: IME text committed after the marked text is cleared isn't lost (winit#4650)
winit 0.30.13 reports insertText as Ime::Commit only while marked text is
left, and after any commit it swallows the next key. Real paths where that
loses text:
- input methods that end a composition with unmarkText, then insertText
(rust-windowing/winit#3925): the committed text was dropped;
- Apple Korean 2-Set, for the key typed after a syllable: on 한 then 5 it
calls setMarkedText("한"), insertText("한"), setMarkedText(""),
insertText("5"), so the 5 (or ;, or any key that ends the syllable) was
dropped;
- a commit made outside a key press (a candidate clicked with the mouse,
dictation): no key follows to reset the state, so the next key (for
example Backspace) was swallowed.
vendor/winit now commits when a composition was started (pending_commit,
set in setMarkedText, cleared by the commit and when IME is disallowed);
other insertText calls still reach the app as KeyboardInput. A commit
outside keyDown clears the marked text and returns to the ground state.
validAttributesForMarkedText lists the underline and marked-clause
attributes, which some input methods need before they compose.
This is rust-windowing/winit#4650, the 0.30 backport of #4651 (merged on
winit master), plus the part of #4748 that fixes #4651's out-of-key-press
case (#4748's other parts are not included). One correction: upstream
spells the underline attribute "NSUnderlineStyle", but AppKit's
NSUnderlineStyleAttributeName is "NSUnderline" (printed on macOS 14), so
the AppKit value is used.
Checked with the real input methods on macOS 14.7.1 (a scratch winit app fed
key events through AppKit): with the patch 한+5 and 한+; commit the 5 and ;,
unmarkText-then-insertText commits, and Backspace after a commit outside a
key press is delivered; ABC typing, held keys, Japanese (日本, あ), Cangjie
(日) and Korean composition give the same events as before. A test fails if
a re-vendored winit loses the patch.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* macOS: the first Apple Korean key in a fresh PdfCraft composes (winit#4744)
On the first key after PdfCraft starts, Apple Korean 2-Set can answer
interpretKeyEvents with insertText and the raw compatibility jamo instead of
setMarkedText. winit sends that key to the app as an ordinary key, and the
next keys compose without it: g k s Space typed ㅎㅏㄴ instead of 한 (Search,
form fields, comments; rust-windowing/winit#3095).
vendor/winit now ports rust-windowing/winit#4744: keyDown interprets that
one key a second time, synchronously, before any KeyboardInput is sent, and
only when every condition holds: Apple Korean, IME allowed and not yet
composing, no pending commit or marked text, no Command/Control/Option, not
a repeat, the key window's first responder, the only callback is one
insertText of that same single jamo, and focus and input source unchanged
afterwards. The decision is ImeStartup (ime_startup.rs, copied with its
seven tests); no timer, no key queue, no text rewriting. It sits on top of
the previous macOS IME change (pending_commit, in_key_down); the retry runs
inside in_key_down. Command maps to ModifiersState::SUPER in winit 0.30
(META on winit master).
Checked with the real input method on macOS 14.7.1 (scratch winit app, fresh
process each time): without the patch g k s Space gave ㅎ as a key, then
ㅏ and ㄴ committed separately, 3 runs out of 3; with it, ㅎ → 하 → 한 → 한
committed, 3 out of 3. All other traces (Japanese, Cangjie, ABC, held
keys, later Korean keys) are unchanged. ImeStartup's tests pass with
rustc --test. A test fails if a re-vendored winit loses the patch.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
This commit is contained in:
5 files changed
+229
-1
No files matched your search
@@ -0,0 +1,21 @@
|
||||
//! vendor/winit patch (10) (vendor/README.md).
|
||||
|
||||
#[test]
|
||||
fn winit_retries_the_first_apple_korean_key_once() {
|
||||
// On the first key in a freshly started app, Apple Korean can answer with `insertText` and the
|
||||
// raw compatibility jamo instead of starting a composition, so typing g k s in PdfCraft gave
|
||||
// ㅎㅏㄴ instead of 한. vendor/winit interprets that one key again before sending it to the
|
||||
// app, under the conditions `ImeStartup` checks (rust-windowing/winit#4744). A re-vendored copy
|
||||
// without the patch would silently bring the bug back: re-apply the patch, or drop the copy once
|
||||
// a winit 0.30 release has the fix.
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let macos = root.join("vendor/winit/src/platform_impl/macos");
|
||||
let policy = std::fs::read_to_string(macos.join("ime_startup.rs")).expect("vendor/winit lost ime_startup.rs");
|
||||
assert!(policy.contains("source.starts_with(\"com.apple.inputmethod.Korean.\")"), "the retry is no longer limited to Apple Korean");
|
||||
let view = std::fs::read_to_string(macos.join("view.rs")).unwrap();
|
||||
assert!(
|
||||
view.contains("let retry = self.ivars().ime_startup.borrow_mut().finish(serial, same_context);"),
|
||||
"keyDown no longer retries the first key"
|
||||
);
|
||||
assert!(view.contains("self.ivars().ime_startup.borrow_mut().insert(&string);"), "insertText no longer reports to the retry policy");
|
||||
}
|
||||
Vendored
+1
-1
@@ -13,7 +13,7 @@ the fix. Vendoring copyleft code is never allowed (plan/adr/0001).
|
||||
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap, page bitmap, halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer) | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`; (2) the nightly `cargo xtask fuzz` finding, which now finishes in about a second; (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate` |
|
||||
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding` |
|
||||
| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices` |
|
||||
| winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there. The published crate's asset files (`docs/res/*.svg`, `examples/data/*.png`) are left out, so its `window` example doesn't build | (1) `pdfcraft` `tests::winit_carries_the_windows_11_monitor_scale_fix` keeps the patch in the build; the drag itself needs two monitors with different scale factors Line truncated
|
||||
| winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, Line truncated
|
||||
| egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::egui_wgpu_carries_the_surface_size_fit`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::egui_wgpu_returns_a_surface_it_cannot_configure_as_an_error`, which keeps it around `add_surface`'s configure |
|
||||
|
||||
Temporary: hayro is the bootstrap renderer and lopdf the bootstrap inspector (ADR-0004); M2.6 replaces them with our own devices and `cos`/`model`.
|
||||
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
//! Detect Apple's first-key Korean IME fallback. Never compose or rewrite text.
|
||||
//!
|
||||
//! PdfCraft patch: from rust-windowing/winit#4744 (see `WinitView::key_down`).
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct ImeStartup {
|
||||
source: String,
|
||||
attempted: bool,
|
||||
serial: u64,
|
||||
batch: Option<Batch>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Batch {
|
||||
expected: char,
|
||||
inserted: bool,
|
||||
}
|
||||
|
||||
impl ImeStartup {
|
||||
pub fn begin(&mut self, source: &str, characters: &str, eligible: bool) -> u64 {
|
||||
self.serial = self.serial.wrapping_add(1);
|
||||
self.batch = None;
|
||||
if source != self.source {
|
||||
self.source = source.to_owned();
|
||||
self.attempted = false;
|
||||
}
|
||||
if eligible && !self.attempted && source.starts_with("com.apple.inputmethod.Korean.") {
|
||||
let mut chars = characters.chars();
|
||||
if let Some(expected @ '\u{3131}'..='\u{318E}') = chars.next() {
|
||||
if chars.next().is_none() {
|
||||
self.batch = Some(Batch { expected, inserted: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
self.serial
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, text: &str) {
|
||||
if let Some(batch) = &mut self.batch {
|
||||
let mut chars = text.chars();
|
||||
if !batch.inserted && chars.next() == Some(batch.expected) && chars.next().is_none() {
|
||||
batch.inserted = true;
|
||||
} else {
|
||||
self.batch = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A preedit, command or unmark callback means AppKit already handled this batch.
|
||||
pub fn other_callback(&mut self) {
|
||||
self.batch = None;
|
||||
}
|
||||
|
||||
pub fn finish(&mut self, serial: u64, same_context: bool) -> bool {
|
||||
// A nested keyDown or IME reset invalidates the outer interpretation.
|
||||
if serial != self.serial {
|
||||
return false;
|
||||
}
|
||||
let retry = same_context && self.batch.take().is_some_and(|batch| batch.inserted);
|
||||
self.batch = None;
|
||||
if retry {
|
||||
// Disarm BEFORE re-entering AppKit; callbacks must never cause recursive retries.
|
||||
self.attempted = true;
|
||||
}
|
||||
retry
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.serial = self.serial.wrapping_add(1);
|
||||
self.attempted = false;
|
||||
self.batch = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
const KO: &str = "com.apple.inputmethod.Korean.2SetKorean";
|
||||
fn fallback(s: &mut ImeStartup, source: &str, event: &str, text: &str, eligible: bool) -> bool {
|
||||
let serial = s.begin(source, event, eligible);
|
||||
s.insert(text);
|
||||
s.finish(serial, true)
|
||||
}
|
||||
#[test]
|
||||
fn cold_single_jamo_gets_one_retry_only() {
|
||||
let mut s = ImeStartup::default();
|
||||
assert!(fallback(&mut s, KO, "ㅎ", "ㅎ", true));
|
||||
assert!(!fallback(&mut s, KO, "ㅎ", "ㅎ", true));
|
||||
}
|
||||
#[test]
|
||||
fn language_change_and_ime_reset_start_new_attempts() {
|
||||
let mut s = ImeStartup::default();
|
||||
assert!(fallback(&mut s, KO, "ㅎ", "ㅎ", true));
|
||||
assert!(!fallback(&mut s, "com.apple.keylayout.ABC", "a", "a", true));
|
||||
assert!(fallback(&mut s, KO, "ㅎ", "ㅎ", true));
|
||||
s.reset();
|
||||
assert!(fallback(&mut s, KO, "ㅎ", "ㅎ", true));
|
||||
}
|
||||
#[test]
|
||||
fn preserves_ascii_paste_multi_char_other_layouts_and_shortcuts() {
|
||||
for (source, event, text, eligible) in [
|
||||
(KO, "a", "a", true),
|
||||
(KO, "ㅎ", "한", true),
|
||||
(KO, "ㅎ", "ㅎㅏ", true),
|
||||
(KO, "ㅎ", "ㄱ", true),
|
||||
("com.apple.keylayout.ABC", "ㅎ", "ㅎ", true),
|
||||
("com.apple.inputmethod.Kotoeri.Japanese", "ㅎ", "ㅎ", true),
|
||||
(KO, "ㅎ", "ㅎ", false),
|
||||
(KO, "", "ㅎ", true),
|
||||
] {
|
||||
assert!(!fallback(&mut ImeStartup::default(), source, event, text, eligible));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn no_callback_is_not_a_fallback() {
|
||||
let mut s = ImeStartup::default();
|
||||
let id = s.begin(KO, "ㅎ", true);
|
||||
assert!(!s.finish(id, true));
|
||||
}
|
||||
#[test]
|
||||
fn multiple_inserts_or_any_other_native_callback_prevent_replay() {
|
||||
let mut s = ImeStartup::default();
|
||||
let id = s.begin(KO, "ㅎ", true);
|
||||
s.insert("ㅎ");
|
||||
s.insert("ㅎ");
|
||||
assert!(!s.finish(id, true));
|
||||
for before in [true, false] {
|
||||
let id = s.begin(KO, "ㅎ", true);
|
||||
if before {
|
||||
s.other_callback();
|
||||
}
|
||||
s.insert("ㅎ");
|
||||
if !before {
|
||||
s.other_callback();
|
||||
}
|
||||
assert!(!s.finish(id, true));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn nested_key_cannot_replay_outer_key() {
|
||||
let mut s = ImeStartup::default();
|
||||
let outer = s.begin(KO, "ㅎ", true);
|
||||
s.insert("ㅎ");
|
||||
let inner = s.begin(KO, "ㄱ", true);
|
||||
s.insert("ㄱ");
|
||||
assert!(s.finish(inner, true));
|
||||
assert!(!s.finish(outer, true));
|
||||
}
|
||||
#[test]
|
||||
fn focus_source_or_ime_change_during_callback_prevents_replay() {
|
||||
let mut s = ImeStartup::default();
|
||||
let id = s.begin(KO, "ㅎ", true);
|
||||
s.insert("ㅎ");
|
||||
assert!(!s.finish(id, false));
|
||||
let id = s.begin(KO, "ㅎ", true);
|
||||
s.insert("ㅎ");
|
||||
s.reset();
|
||||
assert!(!s.finish(id, true));
|
||||
}
|
||||
}
|
||||
+1
@@ -8,6 +8,7 @@ mod event;
|
||||
mod event_handler;
|
||||
mod event_loop;
|
||||
mod ffi;
|
||||
mod ime_startup;
|
||||
mod menu;
|
||||
mod monitor;
|
||||
mod observer;
|
||||
|
||||
+47
@@ -22,6 +22,7 @@ use super::event::{
|
||||
code_to_key, code_to_location, create_key_event, event_mods, lalt_pressed, ralt_pressed,
|
||||
scancode_to_physicalkey, KeyEventExtra,
|
||||
};
|
||||
use super::ime_startup::ImeStartup;
|
||||
use super::window::WinitWindow;
|
||||
use super::DEVICE_ID;
|
||||
use crate::dpi::{LogicalPosition, LogicalSize};
|
||||
@@ -120,6 +121,7 @@ pub struct ViewState {
|
||||
phys_modifiers: RefCell<HashMap<Key, ModLocationMask>>,
|
||||
tracking_rect: Cell<Option<NSTrackingRectTag>>,
|
||||
ime_state: Cell<ImeState>,
|
||||
ime_startup: RefCell<ImeStartup>,
|
||||
input_source: RefCell<String>,
|
||||
|
||||
/// True if this view was in a preedit session that will result in a commit.
|
||||
@@ -284,6 +286,7 @@ declare_class!(
|
||||
) {
|
||||
// TODO: Use _replacement_range, requires changing the event to report surrounding text.
|
||||
trace_scope!("setMarkedText:selectedRange:replacementRange:");
|
||||
self.ivars().ime_startup.borrow_mut().other_callback();
|
||||
|
||||
// SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`.
|
||||
let (marked_text, string) = if string.is_kind_of::<NSAttributedString>() {
|
||||
@@ -347,6 +350,7 @@ declare_class!(
|
||||
#[method(unmarkText)]
|
||||
fn unmark_text(&self) {
|
||||
trace_scope!("unmarkText");
|
||||
self.ivars().ime_startup.borrow_mut().other_callback();
|
||||
*self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new();
|
||||
|
||||
let input_context = self.inputContext().expect("input context");
|
||||
@@ -420,6 +424,7 @@ declare_class!(
|
||||
unsafe { &*string }.to_string()
|
||||
};
|
||||
|
||||
self.ivars().ime_startup.borrow_mut().insert(&string);
|
||||
let is_control = string.chars().next().is_some_and(|c| c.is_control());
|
||||
// PdfCraft patch: commit when a composition was started (`pending_commit`, set by
|
||||
// `setMarkedText`), not when marked text is still present, and send the text of other
|
||||
@@ -477,6 +482,7 @@ declare_class!(
|
||||
#[method(doCommandBySelector:)]
|
||||
fn do_command_by_selector(&self, _command: Sel) {
|
||||
trace_scope!("doCommandBySelector:");
|
||||
self.ivars().ime_startup.borrow_mut().other_callback();
|
||||
// We shouldn't forward any character from just committed text, since we'll end up sending
|
||||
// it twice with some IMEs like Korean one. We'll also always send `Enter` in that case,
|
||||
// which is not desired given it was used to confirm IME input.
|
||||
@@ -514,6 +520,26 @@ declare_class!(
|
||||
self.ivars().forward_key_to_app.set(false);
|
||||
let event = replace_event(event, self.option_as_alt());
|
||||
|
||||
// PdfCraft patch: on the first key in a fresh app, Apple Korean can call `insertText`
|
||||
// with the raw compatibility jamo instead of starting a composition, so g k s typed
|
||||
// ㅎㅏㄴ instead of 한. Retry that exact key once, synchronously, before it is sent
|
||||
// as `KeyboardInput`, and only in that case (rust-windowing/winit#4744; `ImeStartup`).
|
||||
let source = self.current_input_source();
|
||||
let characters =
|
||||
unsafe { event.characters() }.map(|s| s.to_string()).unwrap_or_default();
|
||||
let modifiers = event_mods(&event).state();
|
||||
let eligible = self.ivars().ime_allowed.get()
|
||||
&& old_ime_state == ImeState::Disabled
|
||||
&& !self.ivars().pending_commit.get()
|
||||
&& !unsafe { self.hasMarkedText() }
|
||||
&& !unsafe { event.isARepeat() }
|
||||
&& !modifiers.intersects(
|
||||
ModifiersState::SUPER | ModifiersState::CONTROL | ModifiersState::ALT,
|
||||
)
|
||||
&& self.ime_retry_has_focus();
|
||||
let serial =
|
||||
self.ivars().ime_startup.borrow_mut().begin(&source, &characters, eligible);
|
||||
|
||||
// The `interpretKeyEvents` function might call
|
||||
// `setMarkedText`, `insertText`, and `doCommandBySelector`.
|
||||
// It's important that we call this before queuing the KeyboardInput, because
|
||||
@@ -524,6 +550,17 @@ declare_class!(
|
||||
let events_for_nsview = NSArray::from_slice(&[&*event]);
|
||||
self.ivars().in_key_down.set(true);
|
||||
unsafe { self.interpretKeyEvents(&events_for_nsview) };
|
||||
|
||||
let same_context = self.ivars().ime_allowed.get()
|
||||
&& self.ivars().ime_state.get() == ImeState::Disabled
|
||||
&& !self.ivars().pending_commit.get()
|
||||
&& !unsafe { self.hasMarkedText() }
|
||||
&& self.current_input_source() == source
|
||||
&& self.ime_retry_has_focus();
|
||||
let retry = self.ivars().ime_startup.borrow_mut().finish(serial, same_context);
|
||||
if retry {
|
||||
unsafe { self.interpretKeyEvents(&events_for_nsview) };
|
||||
}
|
||||
self.ivars().in_key_down.set(false);
|
||||
|
||||
// If the text was committed we must treat the next keyboard event as IME related.
|
||||
@@ -865,6 +902,7 @@ impl WinitView {
|
||||
phys_modifiers: Default::default(),
|
||||
tracking_rect: Default::default(),
|
||||
ime_state: Default::default(),
|
||||
ime_startup: RefCell::new(ImeStartup::default()),
|
||||
input_source: Default::default(),
|
||||
pending_commit: Default::default(),
|
||||
ime_allowed: Default::default(),
|
||||
@@ -915,6 +953,14 @@ impl WinitView {
|
||||
!matches!(self.ivars().ime_state.get(), ImeState::Disabled)
|
||||
}
|
||||
|
||||
fn ime_retry_has_focus(&self) -> bool {
|
||||
let Some(window) = (**self).window() else {
|
||||
return false;
|
||||
};
|
||||
window.isKeyWindow()
|
||||
&& window.firstResponder().is_some_and(|responder| *responder == ***self)
|
||||
}
|
||||
|
||||
fn current_input_source(&self) -> String {
|
||||
self.inputContext()
|
||||
.expect("input context")
|
||||
@@ -950,6 +996,7 @@ impl WinitView {
|
||||
return;
|
||||
}
|
||||
self.ivars().ime_allowed.set(ime_allowed);
|
||||
self.ivars().ime_startup.borrow_mut().reset();
|
||||
if self.ivars().ime_allowed.get() {
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user