use super::{Tree, find_node_by_id, find_node_by_path};
use crate::{
app::events::{ImeCursorArea, ImeEvent, KeyboardEvent},
core::NodeId,
node::node_kind::{NodeKind, TextInputState},
};
const PROCESS_KEY: &str = "Process";
const MAX_WITHHELD_KEYS: usize = 16;
#[derive(Default)]
pub(super) struct ImeKeys {
withheld: Vec<String>,
commit_release: bool,
}
impl Tree {
pub fn ime(&mut self, event: ImeEvent) {
self.rebuild_if_dirty();
if matches!(event, ImeEvent::Commit(_)) {
self.ime_keys.commit_release = true;
}
let Some(state) = self.focused_text_input_state() else {
return;
};
let changed = match event {
ImeEvent::Enabled => state.clear_composition(),
ImeEvent::Preedit { text, cursor } => state.set_composition(text, cursor),
ImeEvent::Disabled => state.clear_composition(),
ImeEvent::Commit(text) => {
let cleared = state.clear_composition();
let inserted = !text.is_empty() && state.insert(&text, &self.commit_keyboard_event(&text));
cleared || inserted
}
};
if changed {
self.needs_redraw = true;
self.reset_text_input_caret_blink();
}
self.apply_reactive_updates_after_event();
}
pub fn is_composing(&self) -> bool {
self
.focused_text_input_state()
.is_some_and(|state| state.is_composing())
}
pub fn ime_allowed(&self) -> bool {
self.ime_target().is_some()
}
pub(crate) fn ime_target(&self) -> Option<usize> {
let state = self.focused_text_input_state()?;
(!state.is_masked()).then(|| state.value_signal_id())
}
pub fn ime_cursor_area(&self) -> Option<ImeCursorArea> {
if !self.ime_allowed() {
return None;
}
self.layout_engine.ime_cursor_area()
}
pub(super) fn withhold_composition_key_down(&mut self, key: &str, code: &str) -> bool {
self.ime_keys.commit_release = false;
if key != PROCESS_KEY {
return false;
}
let withheld = &mut self.ime_keys.withheld;
if !withheld.iter().any(|existing| existing == code) {
if withheld.len() == MAX_WITHHELD_KEYS {
withheld.remove(0);
}
withheld.push(code.to_owned());
}
true
}
pub(super) fn is_composition_key_up(&mut self, key: &str, code: &str) -> bool {
let withheld = match self.ime_keys.withheld.iter().position(|existing| existing == code) {
Some(index) => {
self.ime_keys.withheld.remove(index);
true
}
None => false,
};
let commit_release = std::mem::take(&mut self.ime_keys.commit_release);
withheld || commit_release || key == PROCESS_KEY || self.is_composing()
}
fn focused_text_input_state(&self) -> Option<TextInputState> {
let root = self.root.as_ref()?;
let node = self
.focused_path
.as_deref()
.and_then(|path| find_node_by_path(root, path))
.or_else(|| self.focused_node.and_then(|id| find_node_by_id(root, id)))?;
match node.node_kind() {
NodeKind::TextInput { state, .. } => Some(state.clone()),
_ => None,
}
}
fn commit_keyboard_event(&self, text: &str) -> KeyboardEvent {
let target = self.focused_node.unwrap_or(NodeId::UNASSIGNED);
let mut event = KeyboardEvent::new(text, "", false, false, false, false, target);
event.text_input_focused = true;
event.composing = true;
event
}
}