use std::time::Duration;
pub use canvist_headless::canvist_core::Modifiers;
use kurbo::Point;
use crate::Clipboard;
use crate::DesktopEditor;
use crate::DesktopResult;
#[derive(Clone, Debug, PartialEq)]
pub enum InputEvent {
Key(KeyInput),
Ime(Ime),
PointerDown {
position: Point,
button: PointerButton,
modifiers: Modifiers,
},
PointerMove {
position: Point,
},
PointerUp {
button: PointerButton,
},
Scroll(ScrollDelta),
Focus(bool),
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct KeyInput {
pub key: String,
pub text: Option<String>,
pub modifiers: Modifiers,
}
impl KeyInput {
#[must_use]
pub fn named(key: &str, modifiers: Modifiers) -> Self {
Self {
key: key.to_owned(),
text: None,
modifiers,
}
}
#[must_use]
pub fn text(text: &str, modifiers: Modifiers) -> Self {
Self {
key: text.to_owned(),
text: Some(text.to_owned()),
modifiers,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Ime {
Enabled,
Preedit(String),
Commit(String),
Disabled,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PointerButton {
Primary,
Secondary,
Middle,
Other,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ScrollDelta {
Lines {
x: f32,
y: f32,
},
Pixels {
x: f32,
y: f32,
},
}
pub struct Context<'a> {
pub now: Duration,
pub clipboard: &'a mut dyn Clipboard,
}
impl std::fmt::Debug for Context<'_> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Context")
.field("now", &self.now)
.finish_non_exhaustive()
}
}
impl<'a> Context<'a> {
pub fn new(now: Duration, clipboard: &'a mut dyn Clipboard) -> Self {
Self { now, clipboard }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[must_use]
pub struct Response {
pub consumed: bool,
pub repaint: bool,
}
impl Response {
pub const CHANGED: Self = Self {
consumed: true,
repaint: true,
};
pub const IGNORED: Self = Self {
consumed: false,
repaint: false,
};
pub(crate) const fn changed(changed: bool) -> Self {
Self {
consumed: changed,
repaint: changed,
}
}
}
impl<Handles: Copy> DesktopEditor<Handles> {
pub fn handle(&mut self, event: &InputEvent, cx: &mut Context<'_>) -> DesktopResult<Response> {
self.now = self.now.max(cx.now);
let response = match event {
InputEvent::Key(key) => self.key(key, cx)?,
InputEvent::Ime(ime) => self.ime(ime)?,
InputEvent::PointerDown {
position,
button,
modifiers,
} => self.pointer_down(*position, *button, *modifiers)?,
InputEvent::PointerMove { position } => self.pointer_move(*position)?,
InputEvent::PointerUp { button } => self.pointer_up(*button),
InputEvent::Scroll(delta) => self.scroll(*delta),
InputEvent::Focus(focused) => self.focus(*focused),
};
self.dirty |= response.repaint;
Ok(response)
}
#[must_use]
pub fn is_focused(&self) -> bool {
self.focused
}
fn focus(&mut self, focused: bool) -> Response {
if focused == self.focused {
return Response::IGNORED;
}
self.focused = focused;
self.blink_from = self.now;
self.pointer.release();
Response::CHANGED
}
}