use std::{ops::Range, sync::Arc};
use parking_lot::Mutex;
#[cfg(feature = "markdown")]
mod styled;
use crate::{
app::{ctx::Ctx, events::KeyboardEvent},
core::{ElementRef, ElementRefMut, NodeId},
node::node_kind::{TextInputState, WeakTextInputState},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InputSelection {
pub caret: usize,
pub anchor: Option<usize>,
}
impl InputSelection {
pub fn range(self) -> Range<usize> {
let anchor = self.anchor.unwrap_or(self.caret);
anchor.min(self.caret)..anchor.max(self.caret)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct InputCaretPoint {
pub x: f32,
pub y: f32,
pub height: f32,
}
#[derive(Debug, PartialEq, Eq)]
pub enum InputEditError {
NotMounted,
Masked,
Composing,
InvalidSelection,
}
impl std::fmt::Display for InputEditError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::NotMounted => "input controller not mounted",
Self::Masked => "masked input does not expose controller selection",
Self::Composing => "finish the input-method composition before editing",
Self::InvalidSelection => "selection is not a source UTF-8 boundary",
})
}
}
impl std::error::Error for InputEditError {}
#[derive(Default)]
struct Binding {
state: Option<WeakTextInputState>,
}
#[derive(Clone, Default)]
pub struct TextInputController {
binding: Arc<Mutex<Binding>>,
element: ElementRefMut,
}
impl TextInputController {
pub fn new() -> Self {
Self::default()
}
pub(crate) fn bind(&self, state: &TextInputState) {
let mut binding = self.binding.lock();
binding.state = Some(state.downgrade());
}
pub(crate) fn reference(&self) -> ElementRefMut {
self.element.clone()
}
fn state(&self) -> Result<TextInputState, InputEditError> {
if !self.element.is_attached() {
return Err(InputEditError::NotMounted);
}
let state = self
.binding
.lock()
.state
.as_ref()
.and_then(WeakTextInputState::upgrade)
.ok_or(InputEditError::NotMounted)?;
if state.is_masked() {
return Err(InputEditError::Masked);
}
if state.is_composing() {
return Err(InputEditError::Composing);
}
Ok(state)
}
pub fn selection(&self) -> Result<InputSelection, InputEditError> {
let (caret, anchor) = self.state()?.controller_selection();
Ok(InputSelection { caret, anchor })
}
pub fn select(&self, anchor: usize, caret: usize) -> Result<(), InputEditError> {
if self.state()?.controller_select(anchor, caret) {
Ok(())
} else {
Err(InputEditError::InvalidSelection)
}
}
pub fn replace_selection(&self, text: &str) -> Result<bool, InputEditError> {
let state = self.state()?;
state.sync_external_value();
let keyboard = KeyboardEvent::new(text, "InsertText", false, false, false, false, NodeId::UNASSIGNED);
Ok(state.replace_selection_text(text, &keyboard))
}
pub fn undo(&self) -> Result<bool, InputEditError> {
let state = self.state()?;
if state.history_depths().0 == 0 {
return Ok(false);
}
Ok(state.undo(&crate::app::events::EditCommand::Undo.keyboard_event()))
}
pub fn redo(&self) -> Result<bool, InputEditError> {
let state = self.state()?;
if state.history_depths().1 == 0 {
return Ok(false);
}
Ok(state.redo(&crate::app::events::EditCommand::Redo.keyboard_event()))
}
pub fn can_undo(&self) -> bool {
self.state().is_ok_and(|state| state.history_depths().0 > 0)
}
pub fn can_redo(&self) -> bool {
self.state().is_ok_and(|state| state.history_depths().1 > 0)
}
pub fn caret_point(&self, byte: usize) -> Result<InputCaretPoint, InputEditError> {
let (x, y, height) = self.state()?.controller_point(byte);
Ok(InputCaretPoint { x, y, height })
}
pub fn focus(&self, ctx: &Ctx) {
ctx.focus(&self.element.as_ref());
}
pub fn element_ref(&self) -> ElementRef {
self.element.as_ref()
}
}