|
| 1 | +"""Read the live IME (input method editor) state for safe CJK entry. |
| 2 | +
|
| 3 | +Typing into a CJK / Japanese / Korean field is unsafe while an IME is *composing*: |
| 4 | +the candidate text has not been committed yet, so reading the field back returns |
| 5 | +half-entered glyphs and the next keystroke edits the composition instead of the |
| 6 | +field. ``text_unicode`` (``VK_PACKET``) is blind to this. ``ime_state`` exposes |
| 7 | +the live composition and conversion state so a flow can wait for the IME to |
| 8 | +commit before it reads or acts. |
| 9 | +
|
| 10 | +* :func:`ime_state` — ``{open, composing, composition, conversion}`` for the |
| 11 | + focused window's IME, through an injectable ``reader``. |
| 12 | +* :func:`is_composing` — ``True`` while the IME has an uncommitted composition. |
| 13 | +* :func:`wait_for_composition_commit` — block until composition ends (or a |
| 14 | + timeout), with injectable ``clock`` / ``sleep`` / ``reader``. |
| 15 | +* :func:`decode_conversion_mode` — pure: the IMM32 ``IME_CMODE_*`` conversion |
| 16 | + bitmask to ``{native, katakana, full_shape, roman, char_code}``. |
| 17 | +
|
| 18 | +The default ``reader`` queries Windows IMM32 (``ImmGetContext`` / |
| 19 | +``ImmGetOpenStatus`` / ``ImmGetConversionStatus`` / ``ImmGetCompositionStringW``) |
| 20 | +read-only; all decoding / waiting logic runs through the injectable seam, so it |
| 21 | +is fully testable without an IME. Imports no ``PySide6``. |
| 22 | +""" |
| 23 | +import sys |
| 24 | +import time |
| 25 | +from typing import Any, Callable, Dict, Optional |
| 26 | + |
| 27 | +# IMM32 conversion-mode (IME_CMODE_*) bit flags. |
| 28 | +IME_CMODE_NATIVE = 0x0001 |
| 29 | +IME_CMODE_KATAKANA = 0x0002 |
| 30 | +IME_CMODE_FULLSHAPE = 0x0008 |
| 31 | +IME_CMODE_ROMAN = 0x0010 |
| 32 | +IME_CMODE_CHARCODE = 0x0020 |
| 33 | + |
| 34 | +# A reader returns the raw IME state: {open, conversion, composition}. |
| 35 | +ImeReader = Callable[[], Dict[str, Any]] |
| 36 | + |
| 37 | + |
| 38 | +def decode_conversion_mode(flags: int) -> Dict[str, bool]: |
| 39 | + """Decode an IMM32 ``IME_CMODE_*`` bitmask into named booleans (pure).""" |
| 40 | + value = int(flags) |
| 41 | + return { |
| 42 | + "native": bool(value & IME_CMODE_NATIVE), |
| 43 | + "katakana": bool(value & IME_CMODE_KATAKANA), |
| 44 | + "full_shape": bool(value & IME_CMODE_FULLSHAPE), |
| 45 | + "roman": bool(value & IME_CMODE_ROMAN), |
| 46 | + "char_code": bool(value & IME_CMODE_CHARCODE), |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | +def _normalize(raw: Dict[str, Any]) -> Dict[str, Any]: |
| 51 | + """Turn a raw reader result into the public IME-state dict (pure).""" |
| 52 | + composition = str(raw.get("composition") or "") |
| 53 | + flags = int(raw.get("conversion") or 0) |
| 54 | + return { |
| 55 | + "open": bool(raw.get("open")), |
| 56 | + "composing": bool(composition), |
| 57 | + "composition": composition, |
| 58 | + "conversion": decode_conversion_mode(flags), |
| 59 | + "conversion_flags": flags, |
| 60 | + } |
| 61 | + |
| 62 | + |
| 63 | +def ime_state(*, reader: Optional[ImeReader] = None) -> Dict[str, Any]: |
| 64 | + """Return the focused window's IME state. |
| 65 | +
|
| 66 | + ``{open, composing, composition, conversion, conversion_flags}``. Pass |
| 67 | + ``reader`` (a ``() -> {open, conversion, composition}``) to supply the |
| 68 | + reading in tests; the default queries Windows IMM32. |
| 69 | + """ |
| 70 | + source = reader if reader is not None else _default_reader |
| 71 | + return _normalize(source()) |
| 72 | + |
| 73 | + |
| 74 | +def is_composing(*, reader: Optional[ImeReader] = None) -> bool: |
| 75 | + """Return ``True`` while the IME has an uncommitted composition.""" |
| 76 | + return bool(ime_state(reader=reader)["composing"]) |
| 77 | + |
| 78 | + |
| 79 | +def wait_for_composition_commit( |
| 80 | + *, reader: Optional[ImeReader] = None, timeout_s: float = 5.0, |
| 81 | + interval_s: float = 0.1, clock: Callable[[], float] = time.monotonic, |
| 82 | + sleep: Callable[[float], None] = time.sleep) -> bool: |
| 83 | + """Block until the IME is no longer composing; ``True``, or ``False`` on timeout. |
| 84 | +
|
| 85 | + ``clock`` / ``sleep`` / ``reader`` are injectable for deterministic tests. |
| 86 | + """ |
| 87 | + deadline = clock() + float(timeout_s) |
| 88 | + while True: |
| 89 | + if not is_composing(reader=reader): |
| 90 | + return True |
| 91 | + if clock() >= deadline: |
| 92 | + return False |
| 93 | + sleep(float(interval_s)) |
| 94 | + |
| 95 | + |
| 96 | +# IMM32 composition-string flag: read the in-progress composition (GCS_COMPSTR). |
| 97 | +_GCS_COMPSTR = 0x0008 |
| 98 | + |
| 99 | + |
| 100 | +def _read_composition(imm32: Any, himc: int) -> str: |
| 101 | + """Read the in-progress composition string from an IME context.""" |
| 102 | + import ctypes |
| 103 | + byte_len = imm32.ImmGetCompositionStringW(himc, _GCS_COMPSTR, None, 0) |
| 104 | + if byte_len <= 0: |
| 105 | + return "" |
| 106 | + buffer = ctypes.create_unicode_buffer(byte_len // 2) |
| 107 | + imm32.ImmGetCompositionStringW(himc, _GCS_COMPSTR, buffer, byte_len) |
| 108 | + return buffer.value |
| 109 | + |
| 110 | + |
| 111 | +def _default_reader() -> Dict[str, Any]: |
| 112 | + """Read the focused window's IME state from Windows IMM32 (read-only).""" |
| 113 | + if not sys.platform.startswith("win"): |
| 114 | + raise RuntimeError( |
| 115 | + "IME state has no OS reader on this platform; pass reader=") |
| 116 | + import ctypes |
| 117 | + user32 = ctypes.windll.user32 |
| 118 | + imm32 = ctypes.windll.imm32 |
| 119 | + hwnd = user32.GetForegroundWindow() |
| 120 | + himc = imm32.ImmGetContext(hwnd) |
| 121 | + if not himc: |
| 122 | + return {"open": False, "conversion": 0, "composition": ""} |
| 123 | + try: |
| 124 | + conversion = ctypes.c_uint(0) |
| 125 | + sentence = ctypes.c_uint(0) |
| 126 | + imm32.ImmGetConversionStatus( |
| 127 | + himc, ctypes.byref(conversion), ctypes.byref(sentence)) |
| 128 | + return { |
| 129 | + "open": bool(imm32.ImmGetOpenStatus(himc)), |
| 130 | + "conversion": int(conversion.value), |
| 131 | + "composition": _read_composition(imm32, himc), |
| 132 | + } |
| 133 | + finally: |
| 134 | + imm32.ImmReleaseContext(hwnd, himc) |
0 commit comments