Skip to main content

dear_imgui_rs/context/
ime.rs

1use super::binding::CTX_MUTEX;
2use crate::{Context, Id, sys};
3
4/// Transient IME text owned by the active text widget, separate from its buffer.
5#[derive(Clone, Debug, Eq, PartialEq)]
6pub struct ImePreedit {
7    text: String,
8    cursor_range: Option<(usize, usize)>,
9    owner: ImeOwner,
10}
11
12impl ImePreedit {
13    pub fn text(&self) -> &str {
14        &self.text
15    }
16
17    /// UTF-8 byte offsets for the cursor or selected range; `None` hides the cursor.
18    /// A reversed range is accepted and retains the cursor direction.
19    pub fn cursor_range(&self) -> Option<(usize, usize)> {
20        self.cursor_range
21    }
22}
23
24#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
25pub enum ImePreeditError {
26    #[error("IME cursor offsets must be UTF-8 boundaries within the preedit text")]
27    InvalidCursorRange,
28    #[error("IME preedit text must not contain NUL")]
29    InteriorNul,
30}
31
32#[derive(Debug, Default)]
33pub(crate) struct ImeState {
34    pub(crate) preedit: Option<ImePreedit>,
35    presentation: Option<InputPresentation>,
36    session: ImeSession,
37}
38
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40struct ImeOwner {
41    widget: sys::ImGuiID,
42    window: sys::ImGuiID,
43    viewport: sys::ImGuiID,
44}
45
46impl ImeOwner {
47    fn current(raw: &sys::ImGuiContext) -> Option<Self> {
48        if raw.ActiveId == 0
49            || raw.InputTextState.ID != raw.ActiveId
50            || raw.ActiveIdWindow.is_null()
51            || raw.InputTextState.Flags & sys::ImGuiInputTextFlags_ReadOnly != 0
52        {
53            return None;
54        }
55        let window = unsafe { &*raw.ActiveIdWindow };
56        if window.Viewport.is_null() {
57            return None;
58        }
59        Some(Self {
60            widget: raw.ActiveId,
61            window: window.ID,
62            viewport: unsafe { (*window.Viewport)._ImGuiViewport.ID },
63        })
64    }
65}
66
67#[derive(Clone, Copy, Debug, Default)]
68enum ImeSession {
69    #[default]
70    Idle,
71    Composing(ImeOwner),
72    Cancelled {
73        owner: ImeOwner,
74        reset_requested: bool,
75    },
76    Disabled,
77}
78
79impl ImeState {
80    pub(crate) fn cancel(&mut self) {
81        self.preedit = None;
82        if let ImeSession::Composing(owner) = self.session {
83            self.session = ImeSession::Cancelled {
84                owner,
85                reset_requested: true,
86            };
87        }
88    }
89
90    fn reconcile_owner(&mut self, current: Option<ImeOwner>) {
91        if let ImeSession::Composing(owner) = self.session
92            && current != Some(owner)
93        {
94            self.cancel();
95        }
96    }
97
98    pub(crate) fn session_viewport(&self) -> Option<Id> {
99        match self.session {
100            ImeSession::Composing(owner) | ImeSession::Cancelled { owner, .. } => {
101                Some(Id::from(owner.viewport))
102            }
103            ImeSession::Idle | ImeSession::Disabled => None,
104        }
105    }
106
107    pub(crate) fn take_reset_request(&mut self) -> Option<Id> {
108        if let ImeSession::Cancelled {
109            owner,
110            reset_requested,
111        } = &mut self.session
112            && std::mem::take(reset_requested)
113        {
114            Some(Id::from(owner.viewport))
115        } else {
116            None
117        }
118    }
119
120    pub(crate) fn reset_session(&mut self) {
121        self.preedit = None;
122        self.session = ImeSession::Idle;
123    }
124}
125
126#[derive(Clone, Copy, Debug)]
127struct InputPresentation {
128    frame: i32,
129    owner: sys::ImGuiID,
130    font: *mut sys::ImFont,
131    size: f32,
132    density: f32,
133}
134
135impl crate::Ui {
136    // Capture inside the widget's font scope, never from the frame's final font.
137    pub(crate) fn run_input_widget<R>(
138        &self,
139        label: *const std::ffi::c_char,
140        f: impl FnOnce() -> R,
141    ) -> R {
142        self.run_with_bound_context(|| {
143            // A clipped inactive widget may leave LastItemData unchanged.
144            let owner = unsafe { sys::igGetID_Str(label) };
145            let (font, size, density) = unsafe {
146                let font = (*self.ctx).Font;
147                (font, (*self.ctx).FontSize, (*font).CurrentRasterizerDensity)
148            };
149            // InputTextEx renders the label and hint after user callbacks have returned. Keep
150            // their allocation here so a callback using Ui scratch strings gets a separate buffer.
151            let result = self.with_scratch_buffer(|_| f());
152            unsafe {
153                let raw = &*self.ctx;
154                if raw.ActiveId == owner
155                    && raw.InputTextState.ID == owner
156                    && raw.LastItemData.ID == owner
157                {
158                    self.ime.borrow_mut().presentation = Some(InputPresentation {
159                        frame: raw.FrameCount,
160                        owner: raw.ActiveId,
161                        font,
162                        size,
163                        density,
164                    });
165                }
166                self.ime
167                    .borrow_mut()
168                    .reconcile_owner(ImeOwner::current(raw));
169            }
170            result
171        })
172    }
173}
174
175impl Context {
176    /// Replace the active text widget's composition without editing its buffer or undo history.
177    ///
178    /// Cursor offsets use UTF-8 bytes. Empty text hides the panel while retaining
179    /// its owner until commit; `None` hides its cursor. Updates without an active
180    /// editable text widget are discarded.
181    /// The composition is drawn in a non-interactive foreground panel at the
182    /// widget's caret, on its owning viewport. Password input masks its text.
183    /// Core single-line, hint, and multiline text inputs capture their presentation;
184    /// unsupported custom/native widgets discard composition.
185    /// After cancellation or an owner change, a platform must report a new
186    /// enabled session through [`Self::notify_ime_enabled`] before more updates.
187    pub fn set_ime_preedit(
188        &mut self,
189        text: &str,
190        cursor_range: Option<(usize, usize)>,
191    ) -> Result<(), ImePreeditError> {
192        let _guard = CTX_MUTEX.lock();
193        self.assert_current_context("Context::set_ime_preedit()");
194        if let Some((start, end)) = cursor_range
195            && (!text.is_char_boundary(start) || !text.is_char_boundary(end))
196        {
197            return Err(ImePreeditError::InvalidCursorRange);
198        }
199        if text.contains('\0') {
200            return Err(ImePreeditError::InteriorNul);
201        }
202        let raw = unsafe { &*self.as_raw() };
203        let owner = ImeOwner::current(raw);
204        let mut ime = self.state.ime.borrow_mut();
205        ime.reconcile_owner(owner);
206        if matches!(
207            ime.session,
208            ImeSession::Cancelled { .. } | ImeSession::Disabled
209        ) {
210            return Ok(());
211        }
212        if text.is_empty() {
213            ime.preedit = None;
214            return Ok(());
215        }
216        let Some(owner) = owner.filter(|owner| {
217            ime.presentation
218                .is_some_and(|p| p.owner == owner.widget && p.frame == raw.FrameCount)
219        }) else {
220            return Ok(());
221        };
222        ime.session = ImeSession::Composing(owner);
223        ime.preedit = Some(ImePreedit {
224            text: text.to_owned(),
225            cursor_range,
226            owner,
227        });
228        Ok(())
229    }
230
231    /// Return an owned snapshot, without borrowing state needed by platform teardown.
232    pub fn ime_preedit(&self) -> Option<ImePreedit> {
233        self.state.ime.borrow().preedit.clone()
234    }
235
236    /// Whether transient composition is active.
237    pub fn has_ime_preedit(&self) -> bool {
238        self.state.ime.borrow().preedit.is_some()
239    }
240
241    /// Whether a composition owns an input, including an empty pre-commit panel.
242    pub fn has_ime_composition(&self) -> bool {
243        matches!(self.state.ime.borrow().session, ImeSession::Composing(_))
244    }
245
246    /// Notify the Context that the platform enabled or disabled its IME session.
247    ///
248    /// This does not enable the native IME. Enabling starts a fresh session;
249    /// disabling rejects preedit and commit events until the next enabled notice.
250    pub fn notify_ime_enabled(&mut self, enabled: bool) {
251        let mut ime = self.state.ime.borrow_mut();
252        if enabled {
253            ime.reset_session();
254        } else {
255            ime.cancel();
256            if let ImeSession::Cancelled {
257                reset_requested, ..
258            } = &mut ime.session
259            {
260                *reset_requested = false;
261            } else {
262                ime.session = ImeSession::Disabled;
263            }
264        }
265    }
266
267    /// Commit IME text to its original input, returning whether characters were queued.
268    ///
269    /// Control characters are ignored. A cancelled session or a changed owner
270    /// rejects the commit. Without preedit, native/custom editors requesting text
271    /// input can still receive direct commits through the regular IO queue.
272    pub fn commit_ime_text(&mut self, text: &str) -> bool {
273        let _guard = CTX_MUTEX.lock();
274        self.assert_current_context("Context::commit_ime_text()");
275        let raw = unsafe { &*self.as_raw() };
276        {
277            let mut ime = self.state.ime.borrow_mut();
278            ime.reconcile_owner(ImeOwner::current(raw));
279            if matches!(
280                ime.session,
281                ImeSession::Cancelled { .. } | ImeSession::Disabled
282            ) || !(raw.PlatformImeData.WantVisible || raw.PlatformImeData.WantTextInput)
283            {
284                return false;
285            }
286            ime.reset_session();
287        }
288        let mut forwarded = false;
289        for ch in text.chars().filter(|ch| !ch.is_control()) {
290            self.io_mut().add_input_character(ch);
291            forwarded = true;
292        }
293        forwarded
294    }
295
296    /// Viewport whose composition is active or awaiting a native reset.
297    pub fn ime_session_viewport(&self) -> Option<Id> {
298        self.state.ime.borrow().session_viewport()
299    }
300
301    /// Cancel transient composition without submitting text.
302    ///
303    /// The platform must consume its reset request and report a fresh enabled
304    /// session before new IME events are accepted.
305    pub fn clear_ime_preedit(&mut self) {
306        self.state.ime.borrow_mut().cancel();
307    }
308
309    /// Viewport currently requesting text input, for native-window event routing.
310    pub fn text_input_viewport(&self) -> Option<Id> {
311        let _guard = CTX_MUTEX.lock();
312        self.assert_current_context("Context::text_input_viewport()");
313        let raw = unsafe { &*self.as_raw() };
314        (raw.PlatformImeData.WantVisible || raw.PlatformImeData.WantTextInput)
315            .then(|| Id::from(raw.PlatformImeData.ViewportId))
316    }
317
318    pub(crate) fn render_ime_preedit(&mut self) {
319        let raw = unsafe { &*self.as_raw() };
320        {
321            let mut state = self.state.ime.borrow_mut();
322            // Widget submission may start with inactive inputs. Only the frame
323            // boundary can require the owner to have submitted its IME data.
324            let current = ImeOwner::current(raw).filter(|owner| {
325                raw.PlatformImeData.WantVisible
326                    && state
327                        .presentation
328                        .is_some_and(|p| p.owner == owner.widget && p.frame == raw.FrameCount)
329            });
330            state.reconcile_owner(current);
331        }
332        // Do not hold RefCell borrows across font loading or native callbacks.
333        let (preedit, presentation) = {
334            let state = self.state.ime.borrow();
335            let Some(preedit) = state.preedit.clone() else {
336                return;
337            };
338            (preedit, state.presentation)
339        };
340        // Rendering runs under the Context lock, before native EndFrame/Render.
341        let ime = raw.PlatformImeData;
342        if raw.IO.AppFocusLost
343            || ImeOwner::current(raw) != Some(preedit.owner)
344            || !ime.WantVisible
345            || !presentation
346                .is_some_and(|p| p.owner == preedit.owner.widget && p.frame == raw.FrameCount)
347        {
348            self.clear_ime_preedit();
349            return;
350        }
351        let viewport = unsafe { sys::igFindViewportByID(ime.ViewportId) };
352        let presentation = presentation.expect("validated current-frame input presentation");
353        let size = presentation.size;
354        if viewport.is_null()
355            || presentation.font.is_null()
356            || !presentation.density.is_finite()
357            || presentation.density <= 0.0
358            || !size.is_finite()
359            || size <= 0.0
360            || !ime.InputPos.x.is_finite()
361            || !ime.InputPos.y.is_finite()
362        {
363            return;
364        }
365        let password = raw.InputTextState.Flags & sys::ImGuiInputTextFlags_Password != 0;
366        let masked;
367        let (text, cursor) = if password {
368            masked = "*".repeat(preedit.text.chars().count());
369            (
370                masked.as_str(),
371                preedit.cursor_range.map(|(a, b)| {
372                    (
373                        preedit.text[..a].chars().count(),
374                        preedit.text[..b].chars().count(),
375                    )
376                }),
377            )
378        } else {
379            (preedit.text.as_str(), preedit.cursor_range)
380        };
381        // Keep geometry transient: no InputText callbacks, text events, or undo edits.
382        unsafe {
383            let font = presentation.font;
384            let previous_density = (*font).CurrentRasterizerDensity;
385            (*font).CurrentRasterizerDensity = presentation.density;
386            draw_preedit(font, size, viewport, ime.InputPos, text, cursor);
387            (*font).CurrentRasterizerDensity = previous_density;
388        }
389    }
390}
391
392unsafe fn draw_preedit(
393    font: *mut sys::ImFont,
394    size: f32,
395    viewport: *mut sys::ImGuiViewport,
396    anchor: sys::ImVec2_c,
397    text: &str,
398    cursor: Option<(usize, usize)>,
399) {
400    // All pointers belong to the currently bound, live Context and frame.
401    unsafe {
402        let measure = |text: &str| {
403            sys::ImFont_CalcTextSizeA(
404                font,
405                size,
406                f32::MAX,
407                0.0,
408                text.as_ptr().cast(),
409                text.as_ptr().add(text.len()).cast(),
410                std::ptr::null_mut(),
411            )
412        };
413        let offset = |byte: usize| {
414            let prefix = &text[..byte];
415            let line = prefix.rsplit('\n').next().unwrap_or("");
416            sys::ImVec2_c {
417                x: measure(line).x,
418                y: size * prefix.bytes().filter(|&b| b == b'\n').count() as f32,
419            }
420        };
421        let extent = measure(text);
422        let vp = &*viewport;
423        if !extent.x.is_finite() || !extent.y.is_finite() || vp.Size.x <= 0.0 || vp.Size.y <= 0.0 {
424            return;
425        }
426        let padding = 3.0;
427        let width = (extent.x + padding * 2.0).min(vp.Size.x);
428        let height = (extent.y.max(size) + padding * 2.0).min(vp.Size.y);
429        let left = anchor.x.max(vp.Pos.x).min(vp.Pos.x + vp.Size.x - width);
430        let top = anchor.y.max(vp.Pos.y).min(vp.Pos.y + vp.Size.y - height);
431        let caret = cursor.map(|(_, end)| offset(end));
432        let scroll_x = caret.map_or(0.0, |caret| (caret.x + padding * 2.0 - width).max(0.0));
433        let scroll_y = caret.map_or(0.0, |caret| {
434            (caret.y + size + padding * 2.0 - height).max(0.0)
435        });
436        let origin = sys::ImVec2_c {
437            x: left + padding - scroll_x,
438            y: top + padding - scroll_y,
439        };
440        let min = sys::ImVec2_c { x: left, y: top };
441        let max = sys::ImVec2_c {
442            x: left + width,
443            y: top + height,
444        };
445        let draw = sys::igGetForegroundDrawList_ViewportPtr(viewport);
446        sys::ImDrawList_PushClipRect(draw, min, max, true);
447        sys::ImDrawList_AddRectFilled(
448            draw,
449            min,
450            max,
451            sys::igGetColorU32_Col(sys::ImGuiCol_PopupBg, 1.0),
452            0.0,
453            0,
454        );
455        if let Some((a, b)) = cursor {
456            let start = a.min(b);
457            let end = a.max(b);
458            let mut byte = 0;
459            for line in text.split_inclusive('\n') {
460                let line_end = byte + line.len();
461                if start != end && start < line_end && end > byte {
462                    let from = offset(start.max(byte));
463                    let to = offset(end.min(line_end - usize::from(line.ends_with('\n'))));
464                    sys::ImDrawList_AddRectFilled(
465                        draw,
466                        sys::ImVec2_c {
467                            x: origin.x + from.x,
468                            y: origin.y + from.y,
469                        },
470                        sys::ImVec2_c {
471                            x: origin.x + to.x.max(from.x + 1.0),
472                            y: origin.y + from.y + size,
473                        },
474                        sys::igGetColorU32_Col(sys::ImGuiCol_TextSelectedBg, 1.0),
475                        0.0,
476                        0,
477                    );
478                }
479                byte = line_end;
480            }
481        }
482        let color = sys::igGetColorU32_Col(sys::ImGuiCol_Text, 1.0);
483        sys::ImDrawList_AddText_FontPtr(
484            draw,
485            font,
486            size,
487            origin,
488            color,
489            text.as_ptr().cast(),
490            text.as_ptr().add(text.len()).cast(),
491            0.0,
492            std::ptr::null(),
493        );
494        sys::ImDrawList_AddLine(
495            draw,
496            sys::ImVec2_c {
497                x: origin.x,
498                y: origin.y + extent.y.max(size),
499            },
500            sys::ImVec2_c {
501                x: origin.x + extent.x,
502                y: origin.y + extent.y.max(size),
503            },
504            color,
505            1.0,
506            0,
507        );
508        if let Some(caret) = caret {
509            let position = sys::ImVec2_c {
510                x: origin.x + caret.x,
511                y: origin.y + caret.y,
512            };
513            sys::ImDrawList_AddLine(
514                draw,
515                position,
516                sys::ImVec2_c {
517                    x: position.x,
518                    y: position.y + size,
519                },
520                color,
521                1.0,
522                0,
523            );
524            (*sys::igGetCurrentContext()).PlatformImeData.InputPos = position;
525        }
526        sys::ImDrawList_PopClipRect(draw);
527    }
528}