use super::{paint, Show};
use crate::theme::{radius, space, Text, Theme, BORDER};
use eframe::egui::{self, Rect, Stroke, Vec2};
pub struct InputOutput {
pub response: egui::Response,
pub rect: Rect,
pub cleared: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Lead {
None,
Search,
}
#[must_use = "an input does nothing until `show` is called"]
pub struct TextInput<'a> {
text: &'a mut String,
placeholder: &'a str,
error: Option<&'a str>,
width: Option<f32>,
enabled: bool,
lead: Lead,
suffix: Option<&'a str>,
right_aligned: bool,
id: Option<egui::Id>,
show: Show,
}
pub fn text_input(text: &mut String) -> TextInput<'_> {
TextInput { text, placeholder: "", error: None, width: None, enabled: true, lead: Lead::None, suffix: None, right_aligned: false, id: None, show: Show::Live }
}
pub fn search_input(text: &mut String) -> TextInput<'_> {
let mut input = text_input(text);
input.lead = Lead::Search;
input.placeholder = "Search";
input
}
impl<'a> TextInput<'a> {
pub fn placeholder(mut self, text: &'a str) -> Self {
self.placeholder = text;
self
}
pub fn error(mut self, message: Option<&'a str>) -> Self {
self.error = message;
self
}
pub fn width(mut self, width: f32) -> Self {
self.width = Some(width);
self
}
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
pub fn suffix(mut self, suffix: &'a str) -> Self {
self.suffix = Some(suffix);
self
}
pub fn right_aligned(mut self, right: bool) -> Self {
self.right_aligned = right;
self
}
pub fn id(mut self, id: egui::Id) -> Self {
self.id = Some(id);
self
}
pub fn show_state(mut self, show: Show) -> Self {
self.show = show;
self
}
pub fn show(self, ui: &mut egui::Ui) -> InputOutput {
let theme = Theme::of(ui);
let c = &theme.colors;
let width = self.width.unwrap_or_else(|| ui.spacing().text_edit_width.min(ui.available_width()));
let height = theme.control_height();
let id = self.id.unwrap_or_else(|| ui.next_auto_id().with("ui-kit-input"));
let (rect, hover) = ui.allocate_exact_size(Vec2::new(width, height), egui::Sense::hover());
let focused = (self.enabled && ui.memory(|m| m.has_focus(id))) || self.show == Show::Focus;
let hovered = self.enabled && (hover.hovered() || self.show == Show::Hover);
let focus = ui.ctx().animate_bool_with_time(id.with("focus"), focused, theme.motion_base());
let fill = if self.enabled { c.bg_input } else { crate::theme::over(c.bg_panel, c.hover) };
let border = if self.error.is_some() {
c.danger
} else if !self.enabled {
c.border_subtle
} else {
let rest = if hovered { crate::theme::mix(c.border_strong, c.text_secondary, 0.35) } else { c.border_strong };
paint::lerp_color(rest, c.accent_ring, focus)
};
ui.painter().rect(rect, radius::INPUT, fill, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
if focused {
paint::focus_ring(ui, rect, radius::INPUT, &theme);
}
let pad = space::MD;
let mut inner = rect.shrink2(Vec2::new(pad, 0.0));
if self.lead == Lead::Search {
let slot = Rect::from_min_size(inner.min, Vec2::new(14.0, height));
paint::magnifier(ui.painter(), slot.center(), 5.0, Stroke::new(1.4, c.text_secondary));
inner.min.x += 14.0 + space::SM;
}
let mut cleared = false;
if self.lead == Lead::Search && !self.text.is_empty() && self.enabled {
let slot = Rect::from_center_size(egui::pos2(inner.right() - 7.0, rect.center().y), Vec2::splat(16.0));
let clear = ui.interact(slot, id.with("clear"), egui::Sense::click());
clear.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Clear"));
if clear.hovered() {
ui.painter().rect_filled(slot, radius::INPUT, c.hover);
}
paint::cross(ui.painter(), slot.center(), 3.5, Stroke::new(1.4, c.text_secondary));
if clear.clicked() {
self.text.clear();
cleared = true;
}
inner.max.x -= 16.0 + space::XS;
}
if let Some(suffix) = self.suffix {
let g = paint::galley(ui, suffix, theme.font(Text::Body));
inner.max.x -= g.size().x;
ui.painter().galley(egui::pos2(inner.right(), rect.center().y - g.size().y / 2.0), g, if self.enabled { c.text_secondary } else { c.text_disabled });
inner.max.x -= space::XS;
}
let font = theme.font(Text::Body);
let row = ui.fonts_mut(|f| f.row_height(&font));
let text_rect = Rect::from_center_size(inner.center(), Vec2::new(inner.width(), row));
let edit = egui::TextEdit::singleline(self.text)
.id(id)
.frame(egui::Frame::NONE)
.margin(egui::Margin::ZERO)
.font(font)
.text_color(if self.enabled { c.text_primary } else { c.text_disabled })
.hint_text(egui::RichText::new(self.placeholder).color(c.text_disabled))
.horizontal_align(if self.right_aligned { egui::Align::RIGHT } else { egui::Align::LEFT })
.desired_width(inner.width())
.interactive(self.enabled);
let response = ui.put(text_rect, edit);
if let Some(message) = self.error {
ui.label(egui::RichText::new(message).font(theme.font(Text::Caption)).color(c.danger));
}
InputOutput { response, rect, cleared }
}
}
fn length_mm(unit: &str) -> Option<f64> {
Some(match unit {
"mm" => 1.0,
"cm" => 10.0,
"m" => 1000.0,
"um" | "µm" => 0.001,
"in" | "\"" => 25.4,
"ft" | "'" => 304.8,
"mil" | "thou" => 0.0254,
_ => return None,
})
}
fn angle_deg(unit: &str) -> Option<f64> {
Some(match unit {
"deg" | "°" => 1.0,
"rad" => 180.0 / std::f64::consts::PI,
_ => return None,
})
}
fn unit_factor(written: &str, unit: &str) -> Result<f64, String> {
if written == unit {
return Ok(1.0);
}
if let (Some(a), Some(b)) = (length_mm(written), length_mm(unit)) {
return Ok(a / b);
}
if let (Some(a), Some(b)) = (angle_deg(written), angle_deg(unit)) {
return Ok(a / b);
}
if unit.is_empty() {
return Err(format!("this field has no unit; `{written}` cannot be used here"));
}
Err(format!("`{written}` cannot be converted to {unit}"))
}
pub fn evaluate(text: &str, unit: &str) -> Result<f64, String> {
struct Parser<'a> {
chars: std::iter::Peekable<std::str::Chars<'a>>,
unit: &'a str,
}
impl Parser<'_> {
fn skip(&mut self) {
while self.chars.peek().is_some_and(|c| c.is_whitespace()) {
self.chars.next();
}
}
fn expr(&mut self) -> Result<f64, String> {
let mut value = self.term()?;
loop {
self.skip();
match self.chars.peek() {
Some('+') => {
self.chars.next();
value += self.term()?;
}
Some('-') => {
self.chars.next();
value -= self.term()?;
}
_ => return Ok(value),
}
}
}
fn term(&mut self) -> Result<f64, String> {
let mut value = self.factor()?;
loop {
self.skip();
match self.chars.peek().copied() {
Some('*') => {
self.chars.next();
value *= self.factor()?;
}
Some('/') => {
self.chars.next();
let d = self.factor()?;
if d == 0.0 {
return Err("division by zero".into());
}
value /= d;
}
Some(ch) if ch.is_alphabetic() || matches!(ch, '"' | '\'' | '°') => {
let mut name = String::new();
while let Some(ch) = self.chars.peek().copied().filter(|ch| ch.is_alphabetic() || matches!(ch, '"' | '\'' | '°')) {
name.push(ch);
self.chars.next();
}
value *= unit_factor(&name, self.unit)?;
}
_ => return Ok(value),
}
}
}
fn factor(&mut self) -> Result<f64, String> {
self.skip();
match self.chars.peek().copied() {
Some('-') => {
self.chars.next();
Ok(-self.factor()?)
}
Some('+') => {
self.chars.next();
self.factor()
}
Some('(') => {
self.chars.next();
let value = self.expr()?;
self.skip();
match self.chars.next() {
Some(')') => Ok(value),
_ => Err("a `(` is not closed".into()),
}
}
Some(ch) if ch.is_ascii_digit() || ch == '.' => {
let mut digits = String::new();
while let Some(ch) = self.chars.peek().copied().filter(|ch| ch.is_ascii_digit() || *ch == '.') {
digits.push(ch);
self.chars.next();
}
digits.parse().map_err(|_| format!("`{digits}` is not a number"))
}
Some(ch) => Err(format!("unexpected `{ch}`")),
None => Err("a value is missing".into()),
}
}
}
let mut parser = Parser { chars: text.chars().peekable(), unit };
let value = parser.expr()?;
parser.skip();
match parser.chars.peek() {
Some(ch) => Err(format!("unexpected `{ch}`")),
None if value.is_finite() => Ok(value),
None => Err("the value is not finite".into()),
}
}
pub fn format_number(value: f64) -> String {
let text = format!("{value:.6}");
let text = text.trim_end_matches('0').trim_end_matches('.');
if text == "-0" { "0".into() } else { text.into() }
}
#[must_use = "an input does nothing until `show` is called"]
pub struct NumberInput<'a> {
value: &'a mut f64,
unit: &'a str,
label: Option<&'a str>,
width: Option<f32>,
speed: f64,
enabled: bool,
id: Option<egui::Id>,
}
pub fn number_input(value: &mut f64) -> NumberInput<'_> {
NumberInput { value, unit: "", label: None, width: None, speed: 0.1, enabled: true, id: None }
}
pub struct NumberOutput {
pub input: InputOutput,
pub changed: bool,
pub error: Option<String>,
}
impl<'a> NumberInput<'a> {
pub fn unit(mut self, unit: &'a str) -> Self {
self.unit = unit;
self
}
pub fn label(mut self, label: &'a str) -> Self {
self.label = Some(label);
self
}
pub fn width(mut self, width: f32) -> Self {
self.width = Some(width);
self
}
pub fn speed(mut self, speed: f64) -> Self {
self.speed = speed;
self
}
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
pub fn id(mut self, id: egui::Id) -> Self {
self.id = Some(id);
self
}
pub fn show(self, ui: &mut egui::Ui) -> NumberOutput {
let theme = Theme::of(ui);
let id = self.id.unwrap_or_else(|| ui.next_auto_id().with("ui-kit-number"));
let buffer_id = id.with("buffer");
let error_id = id.with("error");
let mut changed = false;
ui.horizontal(|ui| {
if let Some(label) = self.label {
let g = paint::galley(ui, label, theme.font(Text::Label));
let sense = if self.enabled { egui::Sense::drag() } else { egui::Sense::hover() };
let (rect, drag) = ui.allocate_exact_size(Vec2::new(g.size().x, theme.control_height()), sense);
let ink = if !self.enabled {
theme.colors.text_disabled
} else if drag.hovered() || drag.dragged() {
theme.colors.text_primary
} else {
theme.colors.text_secondary
};
ui.painter().galley(egui::pos2(rect.left(), rect.center().y - g.size().y / 2.0), g, ink);
if self.enabled {
let drag = drag.on_hover_cursor(egui::CursorIcon::ResizeHorizontal);
if drag.dragged() {
let delta = f64::from(drag.drag_delta().x) * self.speed;
if delta != 0.0 {
*self.value += delta;
changed = true;
ui.data_mut(|d| {
d.remove::<String>(buffer_id);
d.remove::<String>(error_id);
});
}
}
}
}
ui.vertical(|ui| {
let stored = ui.data(|d| d.get_temp::<String>(buffer_id));
let mut text = stored.clone().unwrap_or_else(|| format_number(*self.value));
let error = ui.data(|d| d.get_temp::<String>(error_id));
let mut input = text_input(&mut text).id(id).right_aligned(true).enabled(self.enabled).error(error.as_deref());
if !self.unit.is_empty() {
input = input.suffix(self.unit);
}
if let Some(width) = self.width {
input = input.width(width);
}
let out = input.show(ui);
let mut error = error;
if out.response.changed() || (out.response.has_focus() && stored.is_none()) {
ui.data_mut(|d| d.insert_temp(buffer_id, text.clone()));
}
if out.response.lost_focus() {
match evaluate(&text, self.unit) {
Ok(value) => {
if value != *self.value {
*self.value = value;
changed = true;
}
error = None;
ui.data_mut(|d| {
d.remove::<String>(buffer_id);
d.remove::<String>(error_id);
});
}
Err(message) => {
ui.data_mut(|d| {
d.insert_temp(buffer_id, text.clone());
d.insert_temp(error_id, message.clone());
});
error = Some(message);
}
}
}
NumberOutput { input: out, changed, error }
})
.inner
})
.inner
}
}