1use egui::{
78 Align2, Color32, CornerRadius, FontId, Id, Rect, Response, Role, Sense, Stroke, StrokeKind,
79 TextStyle, Ui, Vec2, WidgetInfo, pos2, vec2,
80};
81use egui_pop_model::field::FieldState;
82
83use crate::field;
84use crate::icon::{Icon, IconRef};
85use crate::kit::{Kit, State, Tone};
86use crate::state;
87use crate::strings::{self, FIELD_RESET, INPUT_CHOICES, INPUT_CLEAR, INPUT_MORE};
88use crate::tab::{self, TabStop};
89use crate::theme::Tokens;
90use crate::widgets;
91
92const BUFFER: state::Slot<String> = state::Slot::new("core.input.buffer");
94
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum Kind {
98 Text,
99 Number,
101 Path,
103 Search,
105}
106
107impl Kind {
108 pub fn name(self) -> &'static str {
109 match self {
110 Kind::Text => "text",
111 Kind::Number => "number",
112 Kind::Path => "path",
113 Kind::Search => "search",
114 }
115 }
116}
117
118#[derive(Clone, Debug, PartialEq)]
120pub enum Slot {
121 Icon(Icon),
122 Text(String),
124}
125
126#[derive(Clone, Debug, PartialEq)]
128pub struct Attached {
129 icon: Option<Icon>,
130 text: Option<String>,
131 label: String,
132 menu: Vec<String>,
133}
134
135impl Attached {
136 pub fn icon(icon: impl Into<IconRef>, label: &str) -> Self {
140 Self {
141 icon: Some(icon.into().or_placeholder("input button")),
142 text: None,
143 label: label.into(),
144 menu: Vec::new(),
145 }
146 }
147
148 pub fn text(text: &str, label: &str) -> Self {
150 Self {
151 icon: None,
152 text: Some(text.into()),
153 label: label.into(),
154 menu: Vec::new(),
155 }
156 }
157
158 pub fn menu<S: Into<String>>(mut self, items: impl IntoIterator<Item = S>) -> Self {
161 self.menu = items.into_iter().map(Into::into).collect();
162 self
163 }
164}
165
166enum Value<'a> {
167 Text(&'a mut String),
168 Number(&'a mut f64),
169}
170
171#[must_use]
173pub struct Input<'a> {
174 value: Value<'a>,
175 kind: Kind,
176 label: String,
177 placeholder: Option<String>,
178 leading: Vec<Slot>,
179 trailing: Vec<Slot>,
180 clearable: bool,
181 buttons: Vec<Attached>,
182 choices: Vec<String>,
183 state: FieldState,
184 stop: TabStop,
185 width: Option<f32>,
186 cell: Option<Vec2>,
187 salt: Option<Id>,
188 default: Option<String>,
189 precision: Option<usize>,
190 masked: bool,
191 lines: Option<Lines>,
192}
193
194#[derive(Clone, Copy, Debug)]
196struct Lines {
197 rows: usize,
198 max_rows: usize,
199 submit_on_enter: bool,
200}
201
202impl std::fmt::Debug for Input<'_> {
203 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204 f.debug_struct("Input")
205 .field("kind", &self.kind)
206 .field("label", &self.label)
207 .field("masked", &self.masked)
208 .field("multiline", &self.lines.is_some())
209 .field("state", &self.state)
210 .finish_non_exhaustive()
211 }
212}
213
214#[derive(Debug)]
216pub struct InputOutput {
217 pub response: Response,
219 pub changed: bool,
221 pub cleared: bool,
223 pub reset: bool,
225 pub submitted: bool,
228 pub button: Option<usize>,
230 pub menu: Option<(usize, usize)>,
232 pub choice: Option<usize>,
234}
235
236impl<'a> Input<'a> {
237 fn with(value: Value<'a>, kind: Kind, label: &str) -> Self {
238 Self {
239 value,
240 kind,
241 label: label.into(),
242 placeholder: None,
243 leading: Vec::new(),
244 trailing: Vec::new(),
245 clearable: matches!(kind, Kind::Search),
246 buttons: Vec::new(),
247 choices: Vec::new(),
248 state: FieldState::default(),
249 stop: TabStop::new(),
250 width: None,
251 cell: None,
252 salt: None,
253 default: None,
254 precision: None,
255 masked: false,
256 lines: None,
257 }
258 }
259
260 pub fn text(value: &'a mut String, label: &str) -> Self {
266 Self::with(Value::Text(value), Kind::Text, label)
267 }
268
269 pub fn masked(value: &'a mut String, label: &str) -> Self {
276 let mut input = Self::with(Value::Text(value), Kind::Text, label);
277 input.masked = true;
278 input
279 }
280
281 pub fn multiline(value: &'a mut String, label: &str) -> Self {
289 let mut input = Self::with(Value::Text(value), Kind::Text, label);
290 input.lines = Some(Lines {
291 rows: 2,
292 max_rows: 8,
293 submit_on_enter: false,
294 });
295 input
296 }
297
298 pub fn rows(mut self, rows: usize) -> Self {
302 if let Some(l) = &mut self.lines {
303 l.rows = rows.max(1);
304 l.max_rows = l.max_rows.max(l.rows);
305 }
306 self
307 }
308
309 pub fn max_rows(mut self, max_rows: usize) -> Self {
313 if let Some(l) = &mut self.lines {
314 l.max_rows = max_rows.max(l.rows);
315 }
316 self
317 }
318
319 pub fn submit_on_enter(mut self, on: bool) -> Self {
323 if let Some(l) = &mut self.lines {
324 l.submit_on_enter = on;
325 }
326 self
327 }
328
329 pub fn search(value: &'a mut String, label: &str) -> Self {
334 Self::with(Value::Text(value), Kind::Search, label).leading_icon(Icon::Search)
335 }
336
337 pub fn path(value: &'a mut String, label: &str) -> Self {
341 Self::with(Value::Text(value), Kind::Path, label)
342 }
343
344 pub fn number(value: &'a mut f64, label: &str) -> Self {
349 Self::with(Value::Number(value), Kind::Number, label)
350 }
351
352 pub fn placeholder(mut self, text: &str) -> Self {
354 self.placeholder = Some(text.into());
355 self
356 }
357
358 pub fn leading_icon(mut self, icon: impl Into<IconRef>) -> Self {
361 self.leading
362 .push(Slot::Icon(icon.into().or_placeholder("input icon")));
363 self
364 }
365
366 pub fn prefix(mut self, text: &str) -> Self {
368 self.leading.push(Slot::Text(text.into()));
369 self
370 }
371
372 pub fn suffix(mut self, text: &str) -> Self {
374 self.trailing.push(Slot::Text(text.into()));
375 self
376 }
377
378 pub fn unit(self, unit: &str) -> Self {
380 self.suffix(unit)
381 }
382
383 pub fn trailing_icon(mut self, icon: impl Into<IconRef>) -> Self {
385 self.trailing
386 .push(Slot::Icon(icon.into().or_placeholder("input icon")));
387 self
388 }
389
390 pub fn clearable(mut self, on: bool) -> Self {
393 self.clearable = on;
394 self
395 }
396
397 pub fn button(mut self, button: Attached) -> Self {
400 self.buttons.push(button);
401 self
402 }
403
404 pub fn choices<S: Into<String>>(mut self, items: impl IntoIterator<Item = S>) -> Self {
406 self.choices = items.into_iter().map(Into::into).collect();
407 self
408 }
409
410 pub fn state(mut self, state: FieldState) -> Self {
413 self.state = state;
414 self
415 }
416
417 pub fn tab(mut self, stop: TabStop) -> Self {
419 self.stop = stop;
420 self
421 }
422
423 pub fn width(mut self, width: f32) -> Self {
426 self.width = Some(width);
427 self
428 }
429
430 pub fn cell(mut self, size: Vec2) -> Self {
437 self.cell = Some(size);
438 self
439 }
440
441 pub fn id_salt(mut self, salt: impl std::hash::Hash + std::fmt::Debug) -> Self {
443 self.salt = Some(Id::unique(salt));
444 self
445 }
446
447 pub fn default_value(mut self, value: &str) -> Self {
450 self.default = Some(value.into());
451 self
452 }
453
454 pub fn precision(mut self, decimals: usize) -> Self {
456 self.precision = Some(decimals);
457 self
458 }
459
460 pub fn show(self, ui: &mut Ui) -> InputOutput {
462 let base = match self.salt {
463 Some(s) => ui.make_persistent_id(("egui_pop_input", s)),
464 None => ui.make_persistent_id(("egui_pop_input", &self.label)),
465 };
466 let disabled = self.state.is_disabled();
467 ui.scope(|ui| {
468 if disabled {
469 ui.disable();
470 }
471 self.draw(ui, base)
472 })
473 .inner
474 }
475
476 fn draw(self, ui: &mut Ui, base: Id) -> InputOutput {
477 let Input {
478 mut value,
479 kind,
480 label,
481 placeholder,
482 leading,
483 trailing,
484 clearable,
485 buttons,
486 choices,
487 state,
488 stop,
489 width,
490 cell,
491 salt: _,
492 default,
493 precision,
494 masked,
495 lines,
496 } = self;
497 let ctx = ui.ctx().clone();
498 let t = Tokens::of(&ctx);
499 let kit = Kit::of(&ctx);
500 let fk = &kit.field;
501 let h = cell.map_or(ui.spacing().interact_size.y, |c| c.y.max(1.0));
502 if cell.is_some() {
503 ui.spacing_mut().interact_size.y = h;
506 }
507 let pad = if cell.is_some() {
508 t.space.xs
509 } else {
510 t.space.s
511 };
512 let gap = t.space.xs;
513 let side = t.size.icon_inline.min(h - 2.0);
514 let font = TextStyle::Body.resolve(ui.style());
515 let measure = ui.painter().clone();
516 let text_w = |s: &str| {
517 measure
518 .layout_no_wrap(s.to_string(), font.clone(), Color32::WHITE)
519 .size()
520 .x
521 };
522 let button_font = TextStyle::Button.resolve(ui.style());
523 let button_w = |s: &str| {
524 measure
525 .layout_no_wrap(s.to_string(), button_font.clone(), Color32::WHITE)
526 .size()
527 .x
528 };
529 let editable = state.is_editable();
530 let group = stop
531 .group_name()
532 .map_or_else(|| format!("{base:?}"), str::to_string);
533 let mut part_stop = TabStop::new().group(group);
534 if let Some(i) = stop.explicit_index() {
535 part_stop = part_stop.index(i);
536 }
537
538 let widths: Vec<(f32, f32)> = buttons
540 .iter()
541 .map(|b| {
542 let main = match &b.text {
543 Some(s) => button_w(s) + 2.0 * pad,
544 None => h,
545 };
546 let chevron = if b.menu.is_empty() { 0.0 } else { h * 0.8 };
547 (main, chevron)
548 })
549 .collect();
550 let attached: f32 = widths.iter().map(|(a, b)| a + b).sum();
551 let total = match cell {
552 Some(c) => c.x.max(attached + h),
553 None => width
554 .unwrap_or_else(|| ui.available_width())
555 .max(attached + h * 4.0),
556 };
557 let text_id = base.with("text");
558
559 let typing = ui.memory(|m| m.has_focus(text_id));
561 let buffer_id = BUFFER.keyed(base);
562 let mut buffer = match &value {
563 Value::Text(s) => (*s).clone(),
564 Value::Number(v) => match buffer_id.get(&ctx) {
565 Some(b) if typing => b,
566 _ => format_number(&ctx, **v, precision),
567 },
568 };
569 let has_value = !buffer.is_empty();
570 let mut changed = false;
571 let mut cleared = false;
572 let mut reset_pressed = false;
573 let mut clicked = None;
574 let mut menu = None;
575 let mut choice = None;
576
577 let slot_w = |s: &Slot| match s {
579 Slot::Icon(_) => side + gap,
580 Slot::Text(x) => text_w(x) + gap,
581 };
582 let has_chevron = !choices.is_empty() && editable;
583 let show_clear = clearable && kind != Kind::Number && editable && has_value;
584 let markers_w = field::markers_width(&state, side * 0.8, gap / 2.0);
585 let parts = [has_chevron, state.is_resettable(), show_clear]
586 .iter()
587 .filter(|on| **on)
588 .count() as f32;
589 let right_used = gap
590 + parts * h * 0.8
591 + trailing.iter().map(slot_w).sum::<f32>()
592 + if markers_w > 0.0 {
593 markers_w + gap
594 } else {
595 0.0
596 };
597 let left_used = field::edge_width(&t) + pad + leading.iter().map(slot_w).sum::<f32>();
598
599 let row_h = ui.text_style_height(&TextStyle::Body);
602 let inset = ((h - row_h) / 2.0).max(0.0);
603 let (field_h, shown_rows) = match lines {
604 None => (h, 1),
605 Some(l) => {
606 let wrap = (total - attached - right_used - left_used).max(h);
607 let n = measure
608 .layout(buffer.clone(), font.clone(), Color32::WHITE, wrap)
609 .rows
610 .len()
611 .max(1);
612 let shown = n.clamp(l.rows, l.max_rows);
613 (h.max(shown as f32 * row_h + 2.0 * inset), shown)
614 }
615 };
616 let (_, row) = ui.allocate_space(vec2(total, field_h));
617 let field = Rect::from_min_max(row.min, pos2(row.right() - attached, row.bottom()));
618 let line = Rect::from_min_max(field.min, pos2(field.right(), field.top() + h));
619
620 let mut right = line.right() - gap;
623 let mut take = |w: f32| {
624 let r = Rect::from_min_max(pos2(right - w, line.top()), pos2(right, line.bottom()));
625 right -= w;
626 r
627 };
628 let chevron_rect = has_chevron.then(|| take(h * 0.8));
629 let reset_rect = state.is_resettable().then(|| take(h * 0.8));
630 let clear_rect = show_clear.then(|| take(h * 0.8));
631 let mut trailing_rects = Vec::new();
632 for s in trailing.iter().rev() {
633 trailing_rects.push((take(slot_w(s)), s));
634 }
635 let markers_rect = (markers_w > 0.0).then(|| take(markers_w + gap));
636 let mut left = line.left() + field::edge_width(&t) + pad;
637 let mut leading_rects = Vec::new();
638 for s in &leading {
639 let w = slot_w(s);
640 leading_rects.push((
641 Rect::from_min_max(pos2(left, line.top()), pos2(left + w, line.bottom())),
642 s,
643 ));
644 left += w;
645 }
646 let text_rect = if lines.is_some() {
647 Rect::from_min_max(
648 pos2(left, field.top() + inset),
649 pos2(right.max(left + h), field.bottom() - inset),
650 )
651 } else {
652 Rect::from_min_max(
653 pos2(left, field.top()),
654 pos2(right.max(left + h), field.bottom()),
655 )
656 };
657
658 if ui.is_rect_visible(field) {
661 let radius = CornerRadius::same(t.radius.widget.round().clamp(0.0, 255.0) as u8);
662 let fill = if state.read_only {
663 fk.style_toned(Tone::Muted, State::REST).fill
664 } else {
665 fk.style(State::REST).fill
666 };
667 ui.painter().rect_filled(field, radius, fill);
668 }
669 let look = Look {
670 id: text_id,
671 width: text_rect.width(),
672 color: fk.style(State::REST).text,
673 number: kind == Kind::Number,
674 masked,
675 lines: lines.map(|l| (l, shown_rows)),
676 };
677 let response = if editable {
678 let mut text = look.apply(if lines.is_some() {
679 egui::TextEdit::multiline(&mut buffer)
680 } else {
681 egui::TextEdit::singleline(&mut buffer)
682 });
683 if let Some(p) = &placeholder {
684 text = text.hint_text(
685 egui::RichText::new(p).color(fk.style_toned(Tone::Muted, State::REST).text),
686 );
687 }
688 put_text(ui, text_rect, base, lines.is_some(), text)
689 } else {
690 let shown_text = buffer.clone();
693 let mut shown: &str = shown_text.as_str();
694 let text = look.apply(if lines.is_some() {
695 egui::TextEdit::multiline(&mut shown)
696 } else {
697 egui::TextEdit::singleline(&mut shown)
698 });
699 put_text(ui, text_rect, base, lines.is_some(), text)
700 };
701 tab::stop(ui, &response, part_stop.clone().skip(!state.is_focusable()));
702
703 let clear = clear_rect.map(|r| {
706 let label = strings::tr_args(&ctx, &INPUT_CLEAR, &[("label", label.as_str())]);
707 part(
708 ui,
709 r,
710 base.with("clear"),
711 PartLook::Icon(Icon::Close),
712 &label,
713 )
714 });
715 if let Some(c) = &clear {
716 tab::stop(ui, c, part_stop.clone());
717 if c.clicked() {
718 buffer.clear();
719 cleared = true;
720 ui.memory_mut(|m| m.request_focus(text_id));
721 ui.ctx().request_repaint();
722 }
723 }
724 let reset = reset_rect.map(|r| {
725 let label = strings::tr_args(&ctx, &FIELD_RESET, &[("label", label.as_str())]);
726 part(
727 ui,
728 r,
729 base.with("reset"),
730 PartLook::Icon(Icon::Reset),
731 &label,
732 )
733 });
734 if let Some(r) = &reset {
735 tab::stop(ui, r, part_stop.clone());
736 if r.clicked() {
737 reset_pressed = true;
738 if let Some(d) = &default {
739 buffer = d.clone();
740 }
741 }
742 }
743 let chevron = chevron_rect.map(|r| {
744 let label = strings::tr_args(&ctx, &INPUT_CHOICES, &[("label", label.as_str())]);
745 part(
746 ui,
747 r,
748 base.with("chevron"),
749 PartLook::Icon(Icon::ChevronDown),
750 &label,
751 )
752 });
753 if let Some(c) = &chevron {
754 tab::stop(ui, c, part_stop.clone());
755 let popup = egui::Popup::menu(c).id(base.with("choices"));
756 let popup_id = popup.get_id();
757 let open = egui::Popup::is_id_open(&ctx, popup_id);
758 ctx.accesskit_node_builder(c.id, |n| {
759 n.set_has_popup(egui::accesskit::HasPopup::Listbox);
760 n.set_expanded(open);
761 });
762 popup.show(|ui| {
763 for (i, item) in choices.iter().enumerate() {
764 if widgets::selectable_label(ui, *item == buffer, item).clicked() {
765 choice = Some(i);
766 }
767 }
768 });
769 if let Some(i) = choice {
770 buffer = choices[i].clone();
771 }
772 }
773
774 let submitted = match lines {
775 None => response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)),
776 Some(l) => {
779 response.has_focus()
780 && ui.input(|i| {
781 i.events.iter().any(|e| match e {
782 egui::Event::Key {
783 key: egui::Key::Enter,
784 pressed: true,
785 modifiers,
786 ..
787 } => {
788 if l.submit_on_enter {
789 !modifiers.shift
790 } else {
791 modifiers.command
792 }
793 }
794 _ => false,
795 })
796 })
797 }
798 };
799
800 match &mut value {
802 Value::Text(s) => {
803 if **s != buffer {
804 **s = buffer.clone();
805 changed = true;
806 }
807 }
808 Value::Number(v) => {
809 let commit = choice.is_some() || reset_pressed || !response.has_focus();
810 if response.has_focus() {
811 buffer_id.set(&ctx, buffer.clone());
812 }
813 if commit {
814 buffer_id.remove(&ctx);
815 let escaped =
818 typing && !response.has_focus() && crate::focus::escape_left(&ctx, text_id);
819 let typed_now = (typing || response.lost_focus()) && !escaped;
820 if (typed_now || choice.is_some() || reset_pressed)
821 && let Some(n) = crate::slider::parse_typed(&buffer)
822 && n != **v
823 && n.is_finite()
824 {
825 **v = n;
826 changed = true;
827 }
828 }
829 }
830 }
831
832 if ui.is_rect_visible(field) {
834 let painter = ui.painter();
835 let muted = if ui.is_enabled() {
836 t.text.muted
837 } else {
838 t.text.muted.gamma_multiply(0.6)
839 };
840 for (r, s) in leading_rects.iter().chain(trailing_rects.iter()) {
841 paint_slot(ui, *r, s, side, &font, muted);
842 }
843 if let Some(r) = markers_rect {
844 field::paint_markers(
845 ui,
846 pos2(r.left() + gap, r.center().y),
847 side * 0.8,
848 gap / 2.0,
849 &state,
850 );
851 }
852 let radius = CornerRadius::same(t.radius.widget.round().clamp(0.0, 255.0) as u8);
853 let focused = response.has_focus()
854 || [&clear, &reset, &chevron]
855 .iter()
856 .any(|r| r.as_ref().is_some_and(Response::has_focus));
857 for r in [
859 Some(&response),
860 clear.as_ref(),
861 reset.as_ref(),
862 chevron.as_ref(),
863 ]
864 .into_iter()
865 .flatten()
866 {
867 crate::focus::own_ring(&r.ctx, r.id);
868 }
869 let stroke = if focused {
870 Stroke::new(2.0, t.focus_ring)
871 } else if response.hovered() && ui.is_enabled() {
872 Stroke::new(1.0, fk.style(State::HOVER).border_color)
873 } else {
874 Stroke::new(1.0, fk.style(State::REST).border_color)
875 };
876 painter.rect_stroke(field, radius, stroke, StrokeKind::Inside);
877 field::paint_edge(ui, field, &state);
878 }
879
880 let mut x = field.right();
882 for (i, (b, (main_w, chevron_w))) in buttons.iter().zip(&widths).enumerate() {
883 let r = Rect::from_min_max(pos2(x, row.top()), pos2(x + main_w, row.bottom()));
884 x += main_w;
885 let look = match (&b.text, b.icon) {
886 (Some(s), _) => PartLook::Text(s),
887 (None, Some(icon)) => PartLook::Icon(icon),
888 (None, None) => PartLook::Text(&b.label),
889 };
890 let resp = attached_part(ui, r, base.with(("button", i)), look, &b.label);
891 tab::stop(ui, &resp, part_stop.clone());
892 if resp.clicked() {
893 clicked = Some(i);
894 }
895 if b.menu.is_empty() {
896 continue;
897 }
898 let r = Rect::from_min_max(pos2(x, row.top()), pos2(x + chevron_w, row.bottom()));
899 x += chevron_w;
900 let more = strings::tr_args(&ctx, &INPUT_MORE, &[("label", b.label.as_str())]);
901 let resp = attached_part(
902 ui,
903 r,
904 base.with(("menu", i)),
905 PartLook::Icon(Icon::ChevronDown),
906 &more,
907 );
908 tab::stop(ui, &resp, part_stop.clone());
909 if let Some(item) = split_menu(ui, &resp, base.with(("menu-popup", i)), &b.menu) {
910 menu = Some((i, item));
911 }
912 }
913
914 let shown_label = label.clone();
916 let hint = placeholder.clone();
917 ctx.accesskit_node_builder(response.id, |n| {
918 n.set_label(shown_label);
919 if let Some(p) = hint {
921 n.set_placeholder(p);
922 }
923 });
924 field::access(&ctx, response.id, &state);
925 let kind_name = if masked {
927 "masked"
928 } else if lines.is_some() {
929 "multiline"
930 } else {
931 kind.name()
932 };
933 field::record(&ctx, response.id, &label, kind_name, &state);
934 crate::a11y::input(&ctx, response.id, &label);
935 for slot in leading.iter().chain(trailing.iter()) {
937 if let Slot::Icon(i) = slot {
938 crate::icon::registry::record(&ctx, "input", &label, i.name());
939 }
940 }
941 for b in &buttons {
942 if let Some(i) = b.icon {
943 crate::icon::registry::record(&ctx, "input button", &b.label, i.name());
944 }
945 }
946 let mut response = field::hover(ui, &response, &state);
947 if changed {
948 response.mark_changed();
949 }
950 InputOutput {
951 response,
952 changed,
953 cleared,
954 reset: reset_pressed,
955 submitted,
956 button: clicked,
957 menu,
958 choice,
959 }
960 }
961}
962
963struct Look {
967 id: Id,
968 width: f32,
969 color: Color32,
970 number: bool,
971 masked: bool,
972 lines: Option<(Lines, usize)>,
974}
975
976impl Look {
977 fn apply<'t>(&self, text: egui::TextEdit<'t>) -> egui::TextEdit<'t> {
978 let align = match (self.lines, self.number) {
979 (Some(_), _) => Align2::LEFT_TOP,
980 (None, true) => Align2::RIGHT_CENTER,
981 (None, false) => Align2::LEFT_CENTER,
982 };
983 let mut text = text
984 .id(self.id)
985 .frame(egui::Frame::NONE)
986 .margin(egui::Margin::ZERO)
987 .align(align)
988 .desired_width(self.width)
989 .text_color(self.color)
990 .password(self.masked);
991 if let Some((l, shown)) = self.lines {
992 let newline = if l.submit_on_enter {
995 egui::Modifiers::SHIFT
996 } else {
997 egui::Modifiers::NONE
998 };
999 text = text
1000 .desired_rows(shown)
1001 .return_key(egui::KeyboardShortcut::new(newline, egui::Key::Enter));
1002 }
1003 text
1004 }
1005}
1006
1007fn put_text(
1010 ui: &mut Ui,
1011 rect: Rect,
1012 base: Id,
1013 multiline: bool,
1014 text: egui::TextEdit<'_>,
1015) -> Response {
1016 if !multiline {
1017 return ui.put(rect, text);
1018 }
1019 let builder = egui::UiBuilder::new()
1023 .id_salt(base.with("area"))
1024 .max_rect(rect)
1025 .layout(egui::Layout::top_down(egui::Align::Min));
1026 let mut child = ui.new_child(builder);
1027 child.set_clip_rect(rect.intersect(ui.clip_rect()));
1028 egui::ScrollArea::vertical()
1029 .id_salt(base.with("scroll"))
1030 .max_height(rect.height())
1031 .auto_shrink([false, true])
1032 .show(&mut child, |ui| ui.add(text))
1033 .inner
1034}
1035
1036fn format_number(ctx: &egui::Context, v: f64, precision: Option<usize>) -> String {
1037 match precision {
1038 Some(p) => strings::number(ctx, v, p),
1039 None => format!("{v}"),
1040 }
1041}
1042
1043fn paint_slot(ui: &Ui, rect: Rect, slot: &Slot, side: f32, font: &FontId, color: Color32) {
1044 match slot {
1045 Slot::Icon(i) => {
1046 let r = Rect::from_center_size(
1047 pos2(rect.left() + side / 2.0, rect.center().y),
1048 vec2(side, side),
1049 );
1050 i.paint(ui.painter(), r, color);
1051 }
1052 Slot::Text(s) => {
1053 ui.painter().text(
1054 pos2(rect.left(), rect.center().y),
1055 Align2::LEFT_CENTER,
1056 s,
1057 font.clone(),
1058 color,
1059 );
1060 }
1061 }
1062}
1063
1064#[derive(Clone, Copy)]
1065enum PartLook<'s> {
1066 Icon(Icon),
1067 Text(&'s str),
1068}
1069
1070fn part(ui: &mut Ui, rect: Rect, id: Id, look: PartLook<'_>, label: &str) -> Response {
1073 let r = ui.interact(rect, id, Sense::click());
1074 let enabled = ui.is_enabled();
1075 r.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, label));
1076 if ui.is_rect_visible(rect) {
1077 let t = Tokens::of(ui.ctx());
1078 let side = t.size.icon_inline.min(rect.height() - 4.0) * 0.8;
1079 let sq = Rect::from_center_size(rect.center(), vec2(side, side) + vec2(4.0, 4.0));
1080 let radius = CornerRadius::same(t.radius.widget.round().clamp(0.0, 255.0) as u8);
1081 if r.hovered() || r.has_focus() {
1082 ui.painter().rect_filled(sq, radius, t.surface.hover);
1083 }
1084 if r.has_focus() {
1085 crate::focus::own_ring(ui.ctx(), r.id);
1086 }
1087 if crate::focus::shows_ring(&r) {
1088 ui.painter().rect_stroke(
1089 sq,
1090 radius,
1091 Stroke::new(1.5, t.focus_ring),
1092 StrokeKind::Inside,
1093 );
1094 }
1095 let color = if !enabled {
1096 t.text.muted
1097 } else if r.hovered() {
1098 t.text.strong
1099 } else {
1100 t.text.default
1101 };
1102 if let PartLook::Icon(i) = look {
1103 i.paint(
1104 ui.painter(),
1105 Rect::from_center_size(rect.center(), vec2(side, side)),
1106 color,
1107 );
1108 }
1109 }
1110 r.on_hover_text(label)
1111}
1112
1113fn attached_part(ui: &mut Ui, rect: Rect, id: Id, look: PartLook<'_>, label: &str) -> Response {
1115 let r = ui.interact(rect, id, Sense::click());
1116 let enabled = ui.is_enabled();
1117 r.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, label));
1118 if ui.is_rect_visible(rect) {
1119 let t = Tokens::of(ui.ctx());
1120 let kit = Kit::of(ui.ctx());
1121 let b = |state| kit.button.style(state);
1122 let fill = if r.is_pointer_button_down_on() {
1123 b(State::ACTIVE).fill
1124 } else if r.hovered() {
1125 b(State::HOVER).fill
1126 } else {
1127 b(State::REST).fill
1128 };
1129 let radius = CornerRadius::same(b(State::REST).radius.round().clamp(0.0, 255.0) as u8);
1130 ui.painter().rect_filled(rect, radius, fill);
1131 if r.has_focus() {
1132 crate::focus::own_ring(ui.ctx(), r.id);
1133 }
1134 let stroke = if crate::focus::shows_ring(&r) {
1135 Stroke::new(2.0, t.focus_ring)
1136 } else {
1137 Stroke::new(1.0, kit.field.style(State::REST).border_color)
1138 };
1139 ui.painter()
1140 .rect_stroke(rect, radius, stroke, StrokeKind::Inside);
1141 let color = if enabled {
1142 b(State::REST).text
1143 } else {
1144 t.text.muted
1145 };
1146 match look {
1147 PartLook::Icon(i) => {
1148 let side = t.size.icon_inline.min(rect.height() - 4.0);
1149 i.paint(
1150 ui.painter(),
1151 Rect::from_center_size(rect.center(), vec2(side, side)),
1152 color,
1153 );
1154 }
1155 PartLook::Text(s) => {
1156 ui.painter().text(
1157 rect.center(),
1158 Align2::CENTER_CENTER,
1159 s,
1160 TextStyle::Button.resolve(ui.style()),
1161 color,
1162 );
1163 }
1164 }
1165 }
1166 if matches!(look, PartLook::Icon(_)) {
1167 r.on_hover_text(label)
1168 } else {
1169 r
1170 }
1171}
1172
1173fn split_menu(ui: &Ui, chevron: &Response, id: Id, items: &[String]) -> Option<usize> {
1175 let popup = egui::Popup::menu(chevron).id(id);
1176 let open = egui::Popup::is_id_open(ui.ctx(), id);
1177 ui.ctx().accesskit_node_builder(chevron.id, |n| {
1178 n.set_has_popup(egui::accesskit::HasPopup::Menu);
1179 n.set_expanded(open);
1180 });
1181 let mut chosen = None;
1182 popup.show(|ui| {
1183 for (i, item) in items.iter().enumerate() {
1184 if ui.button(item).clicked() {
1185 chosen = Some(i);
1186 }
1187 }
1188 });
1189 chosen
1190}
1191
1192#[derive(Debug)]
1194pub struct SplitOutput {
1195 pub response: Response,
1197 pub clicked: bool,
1199 pub chosen: Option<usize>,
1201}
1202
1203pub fn split_button(ui: &mut Ui, text: &str, items: &[&str]) -> SplitOutput {
1208 let t = Tokens::of(ui.ctx());
1209 let h = ui.spacing().interact_size.y;
1210 let font = TextStyle::Button.resolve(ui.style());
1211 let w = ui
1212 .painter()
1213 .layout_no_wrap(text.to_string(), font, Color32::WHITE)
1214 .size()
1215 .x
1216 + 2.0 * t.space.s;
1217 let (id, row) = ui.allocate_space(vec2(w + h * 0.8, h));
1218 let main = Rect::from_min_max(row.min, pos2(row.left() + w, row.bottom()));
1219 let chev = Rect::from_min_max(pos2(main.right(), row.top()), row.max);
1220 let group = format!("{id:?}");
1221 let response = attached_part(ui, main, id.with("action"), PartLook::Text(text), text);
1222 tab::stop(ui, &response, TabStop::new().group(group.clone()));
1223 let more = strings::tr_args(ui.ctx(), &INPUT_MORE, &[("label", text)]);
1224 let c = attached_part(
1225 ui,
1226 chev,
1227 id.with("chevron"),
1228 PartLook::Icon(Icon::ChevronDown),
1229 &more,
1230 );
1231 tab::stop(ui, &c, TabStop::new().group(group));
1232 let items: Vec<String> = items.iter().map(|s| s.to_string()).collect();
1233 let chosen = split_menu(ui, &c, id.with("menu"), &items);
1234 SplitOutput {
1235 clicked: response.clicked(),
1236 response,
1237 chosen,
1238 }
1239}