1pub mod expr;
88mod gradient;
89pub(crate) mod ramp;
90mod range;
91
92pub use gradient::Gradient;
93pub use ramp::{Ramp, RampColor, RampMode, oklab_mix};
94pub use range::RangeSlider;
95
96use std::fmt;
97use std::ops::RangeInclusive;
98
99use egui::{
100 Color32, Id, Key, Modifiers, Rect, Response, Role, Sense, TextEdit, Ui, Vec2, Widget,
101 WidgetInfo, pos2, vec2,
102};
103use egui_pop_model::pointer::KnobDrag;
104use egui_pop_model::values::{Descriptor, Type};
105
106use crate::field::FieldState;
107use crate::icon::Icon;
108use crate::kit::{BoxStyle, Kit, KitCx, Part, State, Tone};
109use crate::state::Slot;
110use crate::theme::Tokens;
111
112#[derive(Clone, Copy, Debug, PartialEq)]
122pub struct Gestures {
123 pub fine: Modifiers,
125 pub coarse: Modifiers,
127 pub key_fine: Modifiers,
129 pub key_coarse: Modifiers,
131 pub wheel: Modifiers,
135 pub wheel_steps: bool,
138 pub panel: Modifiers,
141 pub typed_entry: Key,
143 pub cancel: Key,
145 pub reset_on_double_click: bool,
147 pub reset_click: Modifiers,
151 pub knob_drag: KnobDrag,
154 pub knob_hide_pointer: bool,
159}
160
161impl Default for Gestures {
162 fn default() -> Self {
164 Self::from_map(&crate::pointer::default_map())
165 }
166}
167
168impl Gestures {
169 pub fn from_map(map: &egui_pop_model::pointer::PointerMap) -> Self {
176 use egui_pop_model::keymap::{Button, Pointer};
177 use egui_pop_model::pointer::{SCOPE_VALUE, SliderWheel, gesture};
178 fn on(
179 map: &egui_pop_model::pointer::PointerMap,
180 command: &egui_pop_model::ids::CommandId,
181 pointer: Pointer,
182 ) -> Vec<Modifiers> {
183 map.chords(SCOPE_VALUE, command)
184 .filter(|c| c.pointer() == Some(pointer))
185 .map(crate::pointer::modifiers_of)
186 .collect()
187 }
188 let first = |mods: Vec<Modifiers>| mods.into_iter().find(|m| m.any());
189 let step = on(map, &gesture::VALUE_STEP, Pointer::Wheel);
190 let drag = Pointer::Drag(Button::Primary);
191 let fine = first(on(map, &gesture::VALUE_FINE, drag)).unwrap_or(Modifiers::NONE);
192 let coarse = first(on(map, &gesture::VALUE_COARSE, drag)).unwrap_or(Modifiers::NONE);
193 let keys = |text: &str, drag: Modifiers| {
194 if text.trim().is_empty() {
195 drag
196 } else {
197 crate::pointer::modifiers_from_text(text)
198 }
199 };
200 Self {
201 fine,
202 coarse,
203 key_fine: keys(&map.value_keys.fine, fine),
204 key_coarse: keys(&map.value_keys.coarse, coarse),
205 wheel: first(step.clone()).unwrap_or(Modifiers::NONE),
206 wheel_steps: map.options.slider_wheel == SliderWheel::Value
207 || step.iter().any(|m| !m.any()),
208 panel: first(on(map, &gesture::VALUE_PANEL, Pointer::Wheel)).unwrap_or(Modifiers::NONE),
209 typed_entry: Key::Enter,
210 cancel: Key::Escape,
211 reset_on_double_click: true,
212 reset_click: first(on(
213 map,
214 &gesture::VALUE_RESET,
215 Pointer::Click(Button::Primary),
216 ))
217 .unwrap_or(Modifiers::NONE),
218 knob_drag: map.options.knob_drag,
219 knob_hide_pointer: false,
220 }
221 }
222}
223
224const GESTURES: Slot<Gestures> = Slot::new("core.slider.gestures");
225const DRAG_ACC: Slot<f64> = Slot::new("core.slider.drag_acc");
227const DRAG_START: Slot<f64> = Slot::new("core.slider.drag_start");
229const TYPING: Slot<String> = Slot::new("core.slider.typing");
231const TYPING_FOCUS: Slot<bool> = Slot::new("core.slider.typing_focus");
233const TYPING_HELD: Slot<u64> = Slot::new("core.slider.typing_held");
235
236pub fn gestures(ctx: &egui::Context) -> Gestures {
239 GESTURES
240 .get(ctx)
241 .unwrap_or_else(|| Gestures::from_map(&crate::pointer::map(ctx)))
242}
243
244pub fn set_gestures(ctx: &egui::Context, gestures: Gestures) {
246 GESTURES.set(ctx, gestures);
247}
248
249#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
251pub enum Curve {
252 #[default]
253 Linear,
254 Logarithmic,
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
261pub enum Cause {
262 Drag,
263 Key,
264 Wheel,
265 Typed,
266 Reset,
268 Access,
270}
271
272impl Cause {
273 pub fn name(self) -> &'static str {
275 match self {
276 Cause::Drag => "drag",
277 Cause::Key => "key",
278 Cause::Wheel => "wheel",
279 Cause::Typed => "typed",
280 Cause::Reset => "reset",
281 Cause::Access => "access",
282 }
283 }
284}
285
286#[derive(Clone, Copy, Debug, PartialEq, Eq)]
288pub enum Thumb {
289 Value,
291 Low,
293 High,
295}
296
297impl Thumb {
298 pub fn name(self) -> &'static str {
300 match self {
301 Thumb::Value => "value",
302 Thumb::Low => "low",
303 Thumb::High => "high",
304 }
305 }
306}
307
308#[derive(Clone, Copy, Debug, PartialEq)]
310pub struct Change {
311 pub thumb: Thumb,
312 pub from: f64,
313 pub to: f64,
314 pub cause: Cause,
315 pub done: bool,
318 pub delta: f64,
324}
325
326#[derive(Clone, Copy, Debug, PartialEq)]
328pub enum Verdict {
329 Go,
331 Veto,
333 Redirect(f64),
335}
336
337pub(crate) struct Hook<'a>(pub(crate) Box<dyn FnMut(&Change) -> Verdict + 'a>);
339
340impl fmt::Debug for Hook<'_> {
341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342 f.write_str("Hook")
343 }
344}
345
346pub(crate) fn decide(hook: &mut Option<Hook<'_>>, change: Change, spec: &Spec) -> Option<Change> {
349 if !spec.state.is_editable() {
350 return None;
351 }
352 match hook.as_mut().map_or(Verdict::Go, |h| (h.0)(&change)) {
353 Verdict::Go => Some(change),
354 Verdict::Veto => None,
355 Verdict::Redirect(v) => {
356 let to = spec.settle(v, spec.hard);
357 Some(Change {
358 to,
359 delta: to - change.from,
360 ..change
361 })
362 }
363 }
364}
365
366#[derive(Debug)]
368pub struct SliderOutput {
369 pub response: Response,
372 pub changes: Vec<Change>,
374 pub quad: Option<Response>,
376}
377
378impl SliderOutput {
379 pub fn quad_clicked(&self) -> bool {
381 self.quad.as_ref().is_some_and(Response::clicked)
382 }
383}
384
385#[derive(Debug)]
387struct Quad<'a> {
388 icon: Icon,
389 label: String,
390 on: Option<&'a mut bool>,
392}
393
394#[derive(Clone, Debug)]
396pub(crate) struct Spec {
397 pub label: String,
398 pub soft: (f64, f64),
399 pub hard: (f64, f64),
400 pub step: f64,
401 pub coarse: f64,
402 pub unit: String,
403 pub precision: usize,
404 pub scale: f64,
405 pub integer: bool,
406 pub signed: bool,
407 pub curve: Curve,
408 pub gradient: Option<Gradient>,
409 pub ramp: Option<Ramp>,
411 pub ramp_mode: RampMode,
412 pub state: FieldState,
414}
415
416impl Spec {
417 pub(crate) fn new(label: &str, soft: RangeInclusive<f64>) -> Self {
418 let (lo, hi) = (*soft.start(), *soft.end());
419 let step = if hi > lo { (hi - lo) / 100.0 } else { 0.01 };
420 Self {
421 label: label.into(),
422 soft: (lo, hi),
423 hard: (lo, hi),
424 step,
425 coarse: step * 10.0,
426 unit: String::new(),
427 precision: precision_of(step),
428 scale: 1.0,
429 integer: false,
430 signed: false,
431 curve: Curve::Linear,
432 gradient: None,
433 ramp: None,
434 ramp_mode: RampMode::Value,
435 state: FieldState::default(),
436 }
437 }
438
439 fn from_descriptor(d: &Descriptor) -> Self {
440 let hard = d.hard.unwrap_or((0.0, 1.0));
441 let soft = d.soft.unwrap_or(hard);
442 let mut s = Self::new(&d.label, soft.0..=soft.1);
443 s.set_hard(hard.0..=hard.1);
444 s.set_step(d.step);
445 if d.coarse > 0.0 {
446 s.coarse = d.coarse;
447 }
448 s.precision = d.precision as usize;
449 s.scale = d.display_scale;
450 if let Some(u) = &d.unit {
451 s.unit = u.clone();
452 }
453 s.integer = d.ty == Type::Int;
454 s
455 }
456
457 pub(crate) fn set_hard(&mut self, hard: RangeInclusive<f64>) {
458 self.hard = (hard.start().min(self.soft.0), hard.end().max(self.soft.1));
459 }
460
461 pub(crate) fn set_step(&mut self, step: f64) {
462 if step > 0.0 {
463 self.step = step;
464 self.coarse = step * 10.0;
465 self.precision = precision_of(step);
466 }
467 }
468
469 fn log(&self) -> bool {
470 self.curve == Curve::Logarithmic && self.soft.0 > 0.0 && self.soft.1 > self.soft.0
471 }
472
473 pub(crate) fn frac(&self, v: f64) -> f64 {
476 let (lo, hi) = self.soft;
477 if self.log() {
478 (v.max(f64::MIN_POSITIVE).ln() - lo.ln()) / (hi.ln() - lo.ln())
479 } else if hi > lo {
480 (v - lo) / (hi - lo)
481 } else {
482 0.0
483 }
484 }
485
486 pub(crate) fn value_at(&self, frac: f64) -> f64 {
488 let (lo, hi) = self.soft;
489 if self.log() {
490 (lo.ln() + frac * (hi.ln() - lo.ln())).exp()
491 } else {
492 lo + frac * (hi - lo)
493 }
494 }
495
496 pub(crate) fn stepped(&self, v: f64, steps: f64, scale: f64) -> f64 {
500 if steps == 0.0 {
501 return v;
502 }
503 if self.log() {
504 return self.value_at(self.frac(v) + steps * 0.01 * scale);
505 }
506 let step = self.step * scale.min(self.coarse / self.step);
507 v + steps * step
508 }
509
510 pub(crate) fn settle(&self, v: f64, (lo, hi): (f64, f64)) -> f64 {
511 let v = if self.integer { v.round() } else { v };
512 v.clamp(lo, hi)
513 }
514
515 pub(crate) fn number(&self, ctx: &egui::Context, v: f64) -> String {
517 let shown = v * self.scale;
518 let n = crate::strings::number(ctx, shown, self.precision);
519 let nonzero = n.chars().any(|c| c.is_ascii_digit() && c != '0');
520 match n.strip_prefix('-') {
521 Some(rest) if !nonzero => rest.to_string(),
523 _ if self.signed && nonzero && shown > 0.0 => format!("+{n}"),
524 _ => n,
525 }
526 }
527
528 pub(crate) fn text(&self, ctx: &egui::Context, v: f64) -> String {
530 self.with_unit(ctx, &self.number(ctx, v))
531 }
532
533 pub(crate) fn with_unit(&self, ctx: &egui::Context, n: &str) -> String {
536 crate::strings::quantity(ctx, n, &self.unit)
537 }
538
539 pub(crate) fn parse(&self, text: &str, current: f64) -> Option<f64> {
541 expr::eval(text, current * self.scale).map(|v| v / self.scale)
542 }
543}
544
545fn precision_of(step: f64) -> usize {
546 if step >= 1.0 || step <= 0.0 {
547 0
548 } else {
549 (-step.log10()).ceil() as usize
550 }
551}
552
553macro_rules! spec_builders {
555 () => {
556 pub fn hard(mut self, hard: std::ops::RangeInclusive<f64>) -> Self {
559 self.spec.set_hard(hard);
560 self
561 }
562
563 pub fn step(mut self, step: f64) -> Self {
565 self.spec.set_step(step);
566 self
567 }
568
569 pub fn coarse(mut self, coarse: f64) -> Self {
571 if coarse > 0.0 {
572 self.spec.coarse = coarse;
573 }
574 self
575 }
576
577 pub fn unit(mut self, unit: &str) -> Self {
579 self.spec.unit = unit.into();
580 self
581 }
582
583 pub fn precision(mut self, decimals: usize) -> Self {
585 self.spec.precision = decimals;
586 self
587 }
588
589 pub fn display_scale(mut self, scale: f64) -> Self {
592 if scale != 0.0 {
593 self.spec.scale = scale;
594 }
595 self
596 }
597
598 pub fn integer(mut self) -> Self {
600 self.spec.integer = true;
601 self.spec.precision = 0;
602 self
603 }
604
605 pub fn signed(mut self) -> Self {
607 self.spec.signed = true;
608 self
609 }
610
611 pub fn logarithmic(mut self) -> Self {
613 self.spec.curve = $crate::slider::Curve::Logarithmic;
614 self
615 }
616
617 pub fn gradient(mut self, gradient: $crate::slider::Gradient) -> Self {
620 self.spec.gradient = Some(gradient);
621 self
622 }
623
624 pub fn state(mut self, state: $crate::field::FieldState) -> Self {
629 self.spec.state = state;
630 self
631 }
632 };
633}
634pub(crate) use spec_builders;
635
636macro_rules! ramp_builders {
639 () => {
640 pub fn ramp(
648 self,
649 min: impl Into<$crate::slider::RampColor>,
650 max: impl Into<$crate::slider::RampColor>,
651 ) -> Self {
652 self.ramp_with($crate::slider::Ramp::new(min, max))
653 }
654
655 pub fn ramp_stops(self, stops: &[(f32, $crate::slider::RampColor)]) -> Self {
658 self.ramp_with($crate::slider::Ramp::stops(stops))
659 }
660
661 pub fn ramp_with(mut self, ramp: $crate::slider::Ramp) -> Self {
663 self.spec.ramp = Some(ramp);
664 self
665 }
666
667 pub fn ramp_track(mut self) -> Self {
671 self.spec.ramp_mode = $crate::slider::RampMode::Track;
672 self
673 }
674 };
675}
676pub(crate) use ramp_builders;
677
678#[derive(Debug)]
682pub struct Slider<'a> {
683 value: &'a mut f64,
684 spec: Spec,
685 default: Option<f64>,
686 hook: Option<Hook<'a>>,
687 quad: Option<Quad<'a>>,
688 vertical: bool,
689 size: Option<Vec2>,
690 compact: bool,
691 scrub: bool,
692 menu: bool,
693 travel: Option<f32>,
694}
695
696pub const MIN_WIDTH: f32 = 24.0;
700
701pub const VERTICAL_LENGTH: f32 = 160.0;
703
704pub fn parse_typed(text: &str) -> Option<f64> {
707 expr::eval(text, f64::NAN)
708}
709
710impl<'a> Slider<'a> {
711 pub fn new(value: &'a mut f64, label: &str, soft: RangeInclusive<f64>) -> Self {
714 Self {
715 value,
716 spec: Spec::new(label, soft),
717 default: None,
718 hook: None,
719 quad: None,
720 vertical: false,
721 size: None,
722 compact: false,
723 scrub: false,
724 menu: true,
725 travel: None,
726 }
727 }
728
729 pub fn from_descriptor(value: &'a mut f64, d: &Descriptor) -> Self {
732 Self {
733 value,
734 spec: Spec::from_descriptor(d),
735 default: d.default.as_f64(),
736 hook: None,
737 quad: None,
738 vertical: false,
739 size: None,
740 compact: false,
741 scrub: false,
742 menu: true,
743 travel: None,
744 }
745 }
746
747 spec_builders!();
748 ramp_builders!();
749
750 pub fn default(mut self, default: f64) -> Self {
752 self.default = Some(default);
753 self
754 }
755
756 pub fn vertical(mut self) -> Self {
762 self.vertical = true;
763 self
764 }
765
766 pub fn size(mut self, size: Vec2) -> Self {
771 self.size = Some(size);
772 self
773 }
774
775 pub fn compact(mut self) -> Self {
780 self.compact = true;
781 self
782 }
783
784 pub fn scrub(mut self) -> Self {
797 self.scrub = true;
798 self
799 }
800
801 pub fn travel(mut self, points: f32) -> Self {
810 if points > 0.0 && points.is_finite() {
811 self.travel = Some(points);
812 }
813 self
814 }
815
816 pub fn menu(mut self, on: bool) -> Self {
821 self.menu = on;
822 self
823 }
824
825 pub fn on_change(mut self, hook: impl FnMut(&Change) -> Verdict + 'a) -> Self {
827 self.hook = Some(Hook(Box::new(hook)));
828 self
829 }
830
831 pub fn quad(mut self, icon: Icon, label: &str) -> Self {
834 self.quad = Some(Quad {
835 icon,
836 label: label.into(),
837 on: None,
838 });
839 self
840 }
841
842 pub fn quad_toggle(mut self, icon: Icon, label: &str, on: &'a mut bool) -> Self {
844 self.quad = Some(Quad {
845 icon,
846 label: label.into(),
847 on: Some(on),
848 });
849 self
850 }
851
852 pub fn show(self, ui: &mut Ui) -> SliderOutput {
854 if self.spec.state.is_disabled() {
855 return ui
856 .scope(|ui| {
857 ui.disable();
858 self.draw(ui)
859 })
860 .inner;
861 }
862 self.draw(ui)
863 }
864
865 fn draw(self, ui: &mut Ui) -> SliderOutput {
866 let Slider {
867 value,
868 spec,
869 default,
870 mut hook,
871 quad,
872 vertical,
873 size,
874 compact,
875 scrub,
876 menu,
877 travel,
878 } = self;
879 let row_height = ui.spacing().interact_size.y;
880 let wanted = match (size, vertical) {
881 (Some(s), false) => vec2(s.x.max(MIN_WIDTH), s.y.max(1.0)),
882 (Some(s), true) => vec2(s.x.max(1.0), s.y.max(MIN_WIDTH)),
883 (None, false) => vec2(room(ui).max(MIN_WIDTH), row_height),
884 (None, true) => vec2(row_height * 1.5, VERTICAL_LENGTH),
885 };
886 let (_, row) = ui.allocate_space(wanted);
887 let id = stable_id(ui, "egui_pop.slider", &spec.label);
888 let quad = if vertical { None } else { quad };
889 let (bar, quad_rect) = split_quad(row, quad.is_some(), ui);
890 let mut response = ui.interact(bar, id, Sense::click_and_drag());
891 let quad = quad.map(|q| show_quad(ui, quad_rect, id, q));
892 let before = *value;
893 let mut changes = Vec::new();
894 let mut apply = |change: Change, value: &mut f64| -> bool {
895 match decide(&mut hook, change, &spec) {
896 Some(c) => {
897 *value = c.to;
898 changes.push(c);
899 true
900 }
901 None => false,
902 }
903 };
904 let change = |from: f64, to: f64, cause: Cause, done: bool| Change {
905 thumb: Thumb::Value,
906 from,
907 to,
908 cause,
909 done,
910 delta: to - from,
911 };
912 let typing_id = typing_id(id);
913 if take_typed_request(ui.ctx(), id) && spec.state.is_editable() {
914 open_typed_entry(ui, typing_id, spec.number(ui.ctx(), *value));
915 }
916 let mut label_shown = true;
917 if let Some(text) = typing_text(ui.ctx(), typing_id) {
918 if let Some(end) = typed_entry(ui, bar, typing_id, text, &spec, *value) {
919 if let Some(v) = end.value {
920 let to = spec.settle(v, spec.hard);
921 if to != *value {
922 apply(change(*value, to, Cause::Typed, true), value);
923 }
924 }
925 if end.refocus {
926 response.request_focus();
927 }
928 }
929 } else {
930 keep_auto_ids(ui);
931 let g = gestures(ui.ctx());
932 let scale = modifier_scale(ui, &g);
933 let along = if vertical {
934 Axis::Vertical(travel.unwrap_or(bar.height()))
935 } else {
936 Axis::Horizontal(travel.unwrap_or(bar.width()))
937 };
938 match drag_along(ui, &response, &spec, *value, spec.soft, scale, along) {
939 Drag::None => {}
940 Drag::Moved(v) => {
941 let to = spec.settle(v, spec.hard);
942 if to != *value {
943 apply(change(*value, to, Cause::Drag, false), value);
944 }
945 }
946 Drag::Ended(start) => {
947 if start != *value && !apply(change(start, *value, Cause::Drag, true), value) {
948 *value = start;
949 crate::binding::cancel_gesture(ui.ctx(), response.id);
950 }
951 }
952 Drag::Cancelled(start) => {
953 *value = start;
954 crate::binding::cancel_gesture(ui.ctx(), response.id);
955 }
956 }
957 if g.reset_on_double_click
958 && response.double_clicked()
959 && let Some(d) = default
960 && d != *value
961 {
962 apply(change(*value, d, Cause::Reset, true), value);
963 }
964 if reset_clicked(ui, &response, &g)
965 && let Some(d) = default
966 && d != *value
967 {
968 apply(change(*value, d, Cause::Reset, true), value);
969 }
970 if response.clicked() {
971 response.request_focus();
973 }
974 if menu
975 && value_menu(&response, &spec, default.filter(|d| *d != *value).is_some())
976 && let Some(d) = default
977 {
978 apply(change(*value, d, Cause::Reset, true), value);
979 }
980 if let Some((v, cause)) =
981 keys_wheel_access(ui, &response, &spec, *value, spec.soft, scale, &g)
982 {
983 let to = spec.settle(v, spec.hard);
984 if to != *value {
985 apply(change(*value, to, cause, true), value);
986 }
987 }
988 if response.has_focus()
989 && spec.state.is_editable()
990 && ui.input(|i| i.key_pressed(g.typed_entry))
991 {
992 open_typed_entry(ui, typing_id, spec.number(ui.ctx(), *value));
993 }
994 let text = spec.text(ui.ctx(), *value);
995 let past = *value < spec.soft.0 || *value > spec.soft.1;
996 label_shown = if vertical {
997 paint_vertical(ui, bar, &response, &spec, *value, past)
998 } else {
999 paint_bar_fitted(
1000 ui,
1001 bar,
1002 &[&response],
1003 &spec,
1004 &[*value],
1005 &text,
1006 past,
1007 Fit {
1008 compact,
1009 track: !scrub,
1010 },
1011 )
1012 };
1013 if label_shown {
1014 paint_state(ui, bar, &spec);
1015 }
1016 }
1017 if *value != before {
1018 response.mark_changed();
1019 }
1020 let enabled = ui.is_enabled();
1021 let v = *value;
1022 response.widget_info(|| WidgetInfo::slider(enabled, v, &spec.label));
1023 access(ui, response.id, &spec, v, spec.soft);
1024 if vertical {
1025 ui.ctx().accesskit_node_builder(response.id, |node| {
1026 node.set_orientation(egui::accesskit::Orientation::Vertical);
1027 });
1028 }
1029 state_of(ui, &[&response], &spec, "slider");
1030 let mut response = crate::field::hover(ui, &response, &spec.state);
1031 if !label_shown {
1032 response = response.on_hover_text(&spec.label);
1034 }
1035 SliderOutput {
1036 response,
1037 changes,
1038 quad,
1039 }
1040 }
1041}
1042
1043impl Widget for Slider<'_> {
1044 fn ui(self, ui: &mut Ui) -> Response {
1045 self.show(ui).response
1046 }
1047}
1048
1049pub fn request_typed_entry(ctx: &egui::Context, widget: Id) {
1054 TYPE_REQUEST.keyed(widget).set(ctx, true);
1055 ctx.request_repaint();
1056}
1057
1058const TYPE_REQUEST: Slot<bool> = Slot::new("core.slider.type_request");
1060
1061pub(crate) fn take_typed_request(ctx: &egui::Context, widget: Id) -> bool {
1063 let slot = TYPE_REQUEST.keyed(widget);
1064 let asked = slot.get(ctx).unwrap_or(false);
1065 if asked {
1066 slot.remove(ctx);
1067 }
1068 asked
1069}
1070
1071pub(crate) fn reset_clicked(ui: &Ui, response: &Response, g: &Gestures) -> bool {
1074 g.reset_click.any()
1075 && response.clicked()
1076 && ui.input(|i| i.modifiers.matches_logically(g.reset_click))
1077}
1078
1079pub(crate) fn value_menu(response: &Response, spec: &Spec, reset: bool) -> bool {
1083 let editable = spec.state.is_editable();
1084 let mut chosen = false;
1085 crate::pointer::claim::context_menu(response, |ui| {
1086 let ctx = ui.ctx().clone();
1087 if ui
1088 .add_enabled(
1089 editable,
1090 egui::Button::new(crate::strings::tr(&ctx, &crate::strings::SLIDER_TYPE_VALUE)),
1091 )
1092 .clicked()
1093 {
1094 request_typed_entry(&ctx, response.id);
1095 ui.close();
1096 }
1097 if reset
1098 && ui
1099 .add_enabled(
1100 editable,
1101 egui::Button::new(crate::strings::tr(&ctx, &crate::strings::RESET)),
1102 )
1103 .clicked()
1104 {
1105 chosen = true;
1106 ui.close();
1107 }
1108 });
1109 chosen
1110}
1111
1112pub(crate) fn typing_text(ctx: &egui::Context, typing_id: Id) -> Option<String> {
1114 TYPING.keyed(typing_id).get(ctx)
1115}
1116
1117pub fn typing_id(slider: Id) -> Id {
1119 slider.with("egui_pop_slider_typing")
1120}
1121
1122fn room(ui: &Ui) -> f32 {
1127 let row = ui.available_rect_before_wrap();
1128 let shown = row.intersect(ui.clip_rect()).width();
1129 if shown >= MIN_WIDTH {
1130 row.width().min(shown)
1131 } else {
1132 row.width()
1133 }
1134}
1135
1136fn split_quad(row: Rect, quad: bool, ui: &Ui) -> (Rect, Rect) {
1138 if !quad {
1139 return (row, Rect::NOTHING);
1140 }
1141 let side = row.height();
1142 let gap = ui.spacing().item_spacing.x.min(4.0);
1143 let bar = Rect::from_min_max(row.min, pos2(row.right() - side - gap, row.bottom()));
1144 let quad = Rect::from_min_max(pos2(row.right() - side, row.top()), row.max);
1145 (bar, quad)
1146}
1147
1148fn show_quad(ui: &mut Ui, rect: Rect, id: Id, mut quad: Quad<'_>) -> Response {
1149 let mut r = ui.interact(rect, id.with("egui_pop_slider_quad"), Sense::click());
1150 if r.clicked()
1151 && let Some(on) = quad.on.as_deref_mut()
1152 {
1153 *on = !*on;
1154 r.mark_changed();
1155 }
1156 let enabled = ui.is_enabled();
1157 let state = quad.on.as_deref().copied();
1158 let label = quad.label.as_str();
1159 match state {
1160 Some(s) => r.widget_info(|| WidgetInfo::selected(Role::CheckBox, enabled, s, label)),
1161 None => r.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, label)),
1162 }
1163 if ui.is_rect_visible(rect) {
1164 let kit = Kit::of(ui.ctx());
1165 let toggle = &kit.slider_toggle;
1166 let part = Part {
1167 rect,
1168 room: rect,
1169 state: State::from_response(&r).with(State::SELECTED, state == Some(true)),
1170 label: None,
1171 };
1172 let painter = clipped(ui, rect, toggle.style(part.state));
1173 let cx = KitCx {
1174 painter: &painter,
1175 ppp: ui.ctx().pixels_per_point(),
1176 };
1177 toggle.paint(&cx, &part);
1178 quad.icon.paint(
1179 &painter,
1180 rect.shrink(rect.height() * 0.2),
1181 toggle.style(part.state).text,
1182 );
1183 }
1184 r
1185}
1186
1187fn clipped(ui: &Ui, rect: Rect, b: &BoxStyle) -> egui::Painter {
1190 let ring = if b.ring_width > 0.0 {
1191 (b.ring_offset + b.ring_width).max(0.0)
1192 } else {
1193 0.0
1194 };
1195 ui.painter_at(rect.expand(ring))
1196}
1197
1198pub(crate) fn modifier_scale(ui: &Ui, g: &Gestures) -> f64 {
1200 scale_of(ui, g.fine, g.coarse)
1201}
1202
1203fn key_scale(ui: &Ui, g: &Gestures) -> f64 {
1205 scale_of(ui, g.key_fine, g.key_coarse)
1206}
1207
1208fn scale_of(ui: &Ui, fine: Modifiers, coarse: Modifiers) -> f64 {
1209 let mods = ui.input(|i| i.modifiers);
1210 let held = |m: Modifiers| m.any() && mods.matches_logically(m);
1211 if held(fine) {
1212 0.1
1213 } else if held(coarse) {
1214 10.0
1215 } else {
1216 1.0
1217 }
1218}
1219
1220pub(crate) enum Drag {
1222 None,
1223 Moved(f64),
1225 Ended(f64),
1227 Cancelled(f64),
1229}
1230
1231#[derive(Clone, Copy, Debug)]
1233pub(crate) enum Axis {
1234 Horizontal(f32),
1235 Vertical(f32),
1237}
1238
1239pub(crate) fn drag(
1244 ui: &Ui,
1245 response: &Response,
1246 spec: &Spec,
1247 value: f64,
1248 bounds: (f64, f64),
1249 scale: f64,
1250 width: f32,
1251) -> Drag {
1252 drag_along(
1253 ui,
1254 response,
1255 spec,
1256 value,
1257 bounds,
1258 scale,
1259 Axis::Horizontal(width),
1260 )
1261}
1262
1263pub(crate) fn drag_along(
1265 ui: &Ui,
1266 response: &Response,
1267 spec: &Spec,
1268 value: f64,
1269 bounds: (f64, f64),
1270 scale: f64,
1271 axis: Axis,
1272) -> Drag {
1273 let acc = DRAG_ACC.keyed(response.id);
1274 let start = DRAG_START.keyed(response.id);
1275 crate::pointer::drag_cursor(response, crate::pointer::DragKind::Value);
1276 if response.drag_started() {
1277 acc.set(ui.ctx(), spec.frac(value));
1278 start.set(ui.ctx(), value);
1279 }
1280 if response.drag_stopped() {
1281 let start = start.get(ui.ctx()).unwrap_or(value);
1282 let cancel = gestures(ui.ctx()).cancel;
1284 return if crate::focus::cancel_pressed(ui.ctx(), cancel) {
1285 Drag::Cancelled(start)
1286 } else {
1287 Drag::Ended(start)
1288 };
1289 }
1290 if response.dragged() {
1291 let d = response.drag_delta();
1292 let (moved, length) = match axis {
1293 Axis::Horizontal(w) => (d.x, w),
1294 Axis::Vertical(h) => (-d.y, h),
1295 };
1296 let delta = f64::from(moved) / f64::from(length.max(1.0)) * scale;
1297 if delta != 0.0 {
1298 let slot = acc;
1299 let acc = slot.get(ui.ctx()).unwrap_or_else(|| spec.frac(value));
1300 let (lo, hi) = (spec.frac(bounds.0), spec.frac(bounds.1));
1301 let next = (acc + delta).clamp(lo.min(acc), hi.max(acc));
1302 slot.set(ui.ctx(), next);
1303 return Drag::Moved(spec.value_at(next));
1304 }
1305 }
1306 Drag::None
1307}
1308
1309const READS: [Key; 8] = [
1311 Key::ArrowLeft,
1312 Key::ArrowRight,
1313 Key::ArrowUp,
1314 Key::ArrowDown,
1315 Key::PageUp,
1316 Key::PageDown,
1317 Key::Home,
1318 Key::End,
1319];
1320
1321pub(crate) fn keys_wheel_access(
1325 ui: &mut Ui,
1326 response: &Response,
1327 spec: &Spec,
1328 value: f64,
1329 bounds: (f64, f64),
1330 scale: f64,
1331 g: &Gestures,
1332) -> Option<(f64, Cause)> {
1333 let (lo, hi) = bounds;
1334 let mut v = value;
1335 let mut cause = None;
1336 if response.has_focus() {
1337 ui.memory_mut(|m| {
1341 m.set_focus_lock_filter(
1342 response.id,
1343 egui::EventFilter {
1344 horizontal_arrows: true,
1345 vertical_arrows: true,
1346 ..Default::default()
1347 },
1348 );
1349 });
1350 crate::focus::reads_keys(ui.ctx(), response.id, &READS);
1351 let key_scale = key_scale(ui, g);
1352 ui.input(|i| {
1353 let count = |keys: &[Key]| keys.iter().map(|k| i.num_presses(*k) as f64).sum::<f64>();
1354 let steps =
1355 count(&[Key::ArrowRight, Key::ArrowUp]) - count(&[Key::ArrowLeft, Key::ArrowDown]);
1356 let pages = count(&[Key::PageUp]) - count(&[Key::PageDown]);
1357 if steps != 0.0 || pages != 0.0 {
1358 v = spec.stepped(v, steps, key_scale);
1359 v = spec.stepped(v, pages, 10.0);
1360 cause = Some(Cause::Key);
1361 }
1362 if i.key_pressed(Key::Home) {
1363 v = lo;
1364 cause = Some(Cause::Key);
1365 }
1366 if i.key_pressed(Key::End) {
1367 v = hi;
1368 cause = Some(Cause::Key);
1369 }
1370 });
1371 }
1372 let mods = ui.input(|i| i.modifiers);
1378 let wheel_held = g.wheel.any() && mods.matches_logically(g.wheel);
1379 let panel_held = g.panel.any() && mods.matches_logically(g.panel);
1380 if response.hovered() && !panel_held && (response.has_focus() || wheel_held || g.wheel_steps) {
1381 let steps = wheel_steps(ui, response.id);
1382 if steps != 0.0 {
1383 v = spec.stepped(v, steps, scale);
1384 cause = Some(Cause::Wheel);
1385 }
1386 ui.input_mut(|i| {
1390 i.smooth_scroll_delta = egui::Vec2::ZERO;
1391 i.events
1392 .retain(|e| !matches!(e, egui::Event::MouseWheel { .. }));
1393 });
1394 }
1395 let id = response.id;
1397 let (inc, dec, set) = ui.input(|i| {
1398 use egui::accesskit::{Action, ActionData};
1399 let set = i
1400 .accesskit_action_requests(id, Action::SetValue)
1401 .filter_map(|r| match r.data {
1402 Some(ActionData::NumericValue(n)) => Some(n),
1403 _ => None,
1404 })
1405 .last();
1406 (
1407 i.num_accesskit_action_requests(id, Action::Increment),
1408 i.num_accesskit_action_requests(id, Action::Decrement),
1409 set,
1410 )
1411 });
1412 if inc + dec > 0 {
1413 v = spec.stepped(v, inc as f64 - dec as f64, 1.0);
1414 cause = Some(Cause::Access);
1415 }
1416 if cause.is_some() {
1419 v = v.clamp(lo.min(value), hi.max(value));
1420 }
1421 if let Some(n) = set {
1422 v = n;
1423 cause = Some(Cause::Access);
1424 }
1425 cause.map(|c| (v, c))
1426}
1427
1428const WHEEL_REST: Slot<(f64, f64)> = Slot::new("core.slider.wheel_rest");
1431
1432const WHEEL_REST_PAUSE: f64 = 0.4;
1435
1436pub(crate) fn wheel_steps(ui: &Ui, id: Id) -> f64 {
1441 use egui_pop_model::keymap::Pointer;
1442 let device = crate::pointer::map(ui.ctx()).wheel_device;
1443 let line = f64::from(
1444 ui.ctx()
1445 .options(|o| o.input_options.line_scroll_speed)
1446 .max(1.0),
1447 );
1448 let (notches, points, now) = ui.input(|i| {
1449 let mut notches = 0.0;
1450 let mut points = 0.0;
1451 for e in &i.events {
1452 if let egui::Event::MouseWheel { unit, delta, .. } = e {
1453 let d = delta.y + delta.x;
1454 match crate::pointer::wheel_pointer(*unit, device) {
1455 Pointer::Scroll => {
1456 points += f64::from(match unit {
1457 egui::MouseWheelUnit::Point => d,
1458 egui::MouseWheelUnit::Line => d * line as f32,
1459 egui::MouseWheelUnit::Page => d * i.content_rect().height(),
1460 });
1461 }
1462 _ => notches += f64::from(d.signum()),
1463 }
1464 }
1465 }
1466 (notches, points, i.time)
1467 });
1468 if points == 0.0 {
1469 return notches;
1470 }
1471 let slot = WHEEL_REST.keyed(id);
1472 let rest = match slot.get(ui.ctx()) {
1473 Some((rest, at)) if now - at <= WHEEL_REST_PAUSE => rest,
1474 _ => 0.0,
1475 };
1476 let total = rest + points / line;
1477 let whole = total.trunc();
1478 slot.set(ui.ctx(), (total - whole, now));
1479 notches + whole
1480}
1481
1482pub(crate) fn open_typed_entry(ui: &Ui, typing_id: Id, text: String) {
1485 TYPING.keyed(typing_id).set(ui.ctx(), text);
1486 TYPING_FOCUS.keyed(typing_id).set(ui.ctx(), true);
1487 ui.ctx().request_repaint();
1488}
1489
1490pub(crate) fn stable_id(ui: &Ui, kind: &'static str, label: &str) -> Id {
1500 let base = ui.make_persistent_id((kind, label));
1501 let ctx = ui.ctx();
1502 let viewport = ctx.viewport_id();
1503 let pass = ctx.cumulative_pass_nr_for(viewport);
1504 let n = ctx.data_mut(|d| {
1505 let seen =
1506 d.get_temp_mut_or_default::<StableIds>(Id::unique(("egui_pop.stable_ids", viewport)));
1507 if seen.pass != pass {
1508 seen.pass = pass;
1509 seen.taken.clear();
1510 }
1511 let n = seen.taken.entry(base).or_insert(0);
1512 *n += 1;
1513 *n - 1
1514 });
1515 if n == 0 { base } else { base.with(n) }
1516}
1517
1518#[derive(Clone, Default)]
1520struct StableIds {
1521 pass: u64,
1522 taken: std::collections::HashMap<Id, u32>,
1523}
1524
1525pub(crate) fn keep_auto_ids(ui: &mut Ui) {
1530 ui.skip_ahead_auto_ids(1);
1531}
1532
1533pub(crate) struct TypedEnd {
1535 pub value: Option<f64>,
1537 pub refocus: bool,
1541}
1542
1543pub(crate) fn typed_entry(
1548 ui: &mut Ui,
1549 bar: Rect,
1550 typing_id: Id,
1551 mut text: String,
1552 spec: &Spec,
1553 current: f64,
1554) -> Option<TypedEnd> {
1555 let edit = ui
1558 .place(
1559 bar,
1560 TextEdit::singleline(&mut text)
1561 .id(typing_id.with("edit"))
1562 .align(egui::Align2::CENTER_TOP),
1563 )
1564 .accessible_name(crate::strings::tr_args(
1565 ui.ctx(),
1566 &crate::strings::SLIDER_ENTRY,
1567 &[("label", spec.label.as_str())],
1568 ));
1569 if TYPING_FOCUS.keyed(typing_id).remove(ui.ctx()).is_some() {
1570 edit.request_focus();
1571 }
1572 let (cancel, enter) = ui.input(|i| (pressed(i, Key::Escape), pressed(i, Key::Enter)));
1576 let cancel = cancel || crate::focus::escape_left(ui.ctx(), edit.id);
1577 if !cancel && !enter && (edit.has_focus() || held(ui, edit.id, typing_id)) {
1578 crate::focus::claim_keyboard(ui.ctx(), edit.id);
1580 TYPING.keyed(typing_id).set(ui.ctx(), text);
1581 return None;
1582 }
1583 TYPING_HELD.keyed(typing_id).remove(ui.ctx());
1584 TYPING.keyed(typing_id).remove(ui.ctx());
1585 if cancel || enter {
1586 ui.input_mut(|i| {
1588 i.consume_key(Modifiers::NONE, Key::Escape);
1589 i.consume_key(Modifiers::NONE, Key::Enter);
1590 });
1591 }
1592 Some(TypedEnd {
1593 value: if cancel {
1594 None
1595 } else {
1596 spec.parse(&text, current)
1597 },
1598 refocus: enter && !cancel,
1599 })
1600}
1601
1602fn held(ui: &Ui, edit: Id, typing_id: Id) -> bool {
1609 let moved = ui
1610 .input(|i| i.pointer.any_pressed() || i.pointer.any_released() || i.key_pressed(Key::Tab));
1611 let elsewhere = ui.memory(|m| m.focused()).is_some_and(|f| f != edit);
1612 let key = TYPING_HELD.keyed(typing_id);
1613 let now = ui.ctx().cumulative_pass_nr();
1614 let held_last = key.get(ui.ctx()).is_some_and(|p| p + 1 == now);
1615 if moved || elsewhere || held_last {
1616 return false;
1617 }
1618 key.set(ui.ctx(), now);
1619 ui.memory_mut(|m| m.request_focus(edit));
1620 ui.ctx().request_repaint();
1621 true
1622}
1623
1624fn pressed(i: &egui::InputState, key: Key) -> bool {
1627 i.key_pressed(key)
1628 || i.raw
1629 .events
1630 .iter()
1631 .any(|e| matches!(e, egui::Event::Key { key: k, pressed: true, .. } if *k == key))
1632}
1633
1634pub(crate) fn paint_bar(
1639 ui: &Ui,
1640 rect: Rect,
1641 responses: &[&Response],
1642 spec: &Spec,
1643 thumbs: &[f64],
1644 text: &str,
1645 past: bool,
1646) {
1647 paint_bar_fitted(
1648 ui,
1649 rect,
1650 responses,
1651 spec,
1652 thumbs,
1653 text,
1654 past,
1655 Fit::default(),
1656 );
1657}
1658
1659#[derive(Clone, Copy, Debug)]
1662pub(crate) struct Fit {
1663 pub compact: bool,
1664 pub track: bool,
1665}
1666
1667impl Default for Fit {
1668 fn default() -> Self {
1669 Fit {
1670 compact: false,
1671 track: true,
1672 }
1673 }
1674}
1675
1676#[allow(
1681 clippy::too_many_arguments,
1682 reason = "paint_bar's arguments and how it fits"
1683)]
1684pub(crate) fn paint_bar_fitted(
1685 ui: &Ui,
1686 rect: Rect,
1687 responses: &[&Response],
1688 spec: &Spec,
1689 thumbs: &[f64],
1690 text: &str,
1691 past: bool,
1692 fit: Fit,
1693) -> bool {
1694 let Fit { compact, track } = fit;
1695 let kit = Kit::of(ui.ctx());
1696 let font = egui::TextStyle::Button.resolve(ui.style());
1697 let pad = kit.slider.data.padding_x.max(0.0);
1698 let measure = |t: &str| {
1699 ui.painter()
1700 .layout_no_wrap(t.to_owned(), font.clone(), Color32::PLACEHOLDER)
1701 .size()
1702 .x
1703 };
1704 let galley =
1707 |t: &str| crate::fonts::number_galley(ui.ctx(), t, font.size, Color32::PLACEHOLDER);
1708 let value_pad = kit.slider_value.data.padding_x.max(0.0);
1709 let mut value = galley(text);
1710 let value_w = value.size().x;
1711 let gap = ui.spacing().item_spacing.x;
1712 let label_shown =
1713 !compact && measure(&spec.label) + value_w + gap + pad + value_pad <= rect.width();
1714 if !label_shown && value_w + 2.0 * value_pad > rect.width() && !spec.unit.is_empty() {
1716 let number = text
1717 .strip_suffix(spec.unit.as_str())
1718 .map_or(text, str::trim_end);
1719 value = galley(number);
1720 }
1721 if !ui.is_rect_visible(rect) {
1722 return label_shown;
1723 }
1724 let tone = if past { Tone::Warning } else { Tone::Neutral };
1725 let state = responses
1727 .iter()
1728 .fold(State::REST, |s, r| s | State::from_response(r))
1729 .toned(tone);
1730 let painter = clipped(ui, rect, kit.slider.style(state));
1731 let cx = KitCx {
1732 painter: &painter,
1733 ppp: ui.ctx().pixels_per_point(),
1734 };
1735 let label = painter.layout_no_wrap(spec.label.clone(), font.clone(), Color32::PLACEHOLDER);
1736 let bar = Part {
1737 rect,
1738 room: rect,
1739 state,
1740 label: label_shown.then_some(&label),
1741 };
1742 kit.slider.paint(&cx, &bar);
1743 if track {
1745 let x_of = |v: f64| rect.left() + rect.width() * spec.frac(v).clamp(0.0, 1.0) as f32;
1746 let tokens = Tokens::of(ui.ctx());
1750 let ramp = match thumbs {
1751 [_] => ramp::active(spec.ramp.as_ref(), &tokens),
1752 _ => None,
1753 };
1754 let taller = || {
1755 let strip = (rect.height() * 0.3).max(4.0);
1756 Rect::from_min_max(pos2(rect.left(), rect.bottom() - strip), rect.max)
1757 };
1758 if let (Some(r), RampMode::Track) = (ramp, spec.ramp_mode) {
1759 r.paint(&painter, taller(), &tokens, false);
1762 } else if let (Some(g), None) = (&spec.gradient, ramp) {
1763 g.paint(&painter, taller());
1765 } else {
1766 let fill = &kit.slider_fill;
1767 let strip = match fill.data.height {
1768 h if h > 0.0 => h.min(rect.height()),
1769 _ => (rect.height() * 0.15).max(3.0),
1770 };
1771 let (from, to) = match thumbs {
1772 [v] => (rect.left(), x_of(*v)),
1773 [a, b, ..] => (x_of(*a), x_of(*b)),
1774 [] => (rect.left(), rect.left()),
1775 };
1776 let strip =
1777 Rect::from_min_max(pos2(from, rect.bottom() - strip), pos2(to, rect.bottom()));
1778 match (ramp, thumbs) {
1779 (Some(r), [v]) => {
1782 let track = backdrop(kit.slider.style(state).fill, &tokens);
1783 let color = r.value_color(spec.frac(*v) as f32, &tokens, track);
1784 painter.rect_filled(strip, fill.style(state).radius, color);
1785 }
1786 _ => fill.paint_part(
1787 &cx,
1788 &Part {
1789 rect: strip,
1790 room: rect,
1791 state,
1792 label: None,
1793 },
1794 ),
1795 }
1796 }
1797 let thumb = &kit.slider_thumb;
1798 let width = thumb.data.width.max(0.0);
1799 for (i, v) in thumbs.iter().enumerate() {
1800 let x = x_of(*v);
1801 let state = responses
1802 .get(i)
1803 .map_or(State::REST, |r| State::from_response(r))
1804 .toned(tone);
1805 let r = Rect::from_min_max(
1806 pos2(x - width / 2.0, rect.top()),
1807 pos2(x + width / 2.0, rect.bottom()),
1808 );
1809 thumb.paint_part(
1810 &cx,
1811 &Part {
1812 rect: r,
1813 room: rect,
1814 state,
1815 label: None,
1816 },
1817 );
1818 }
1819 }
1820 kit.slider.paint_label(&cx, &bar);
1821 let painter = ui.painter_at(rect);
1825 let cx = KitCx {
1826 painter: &painter,
1827 ppp: cx.ppp,
1828 };
1829 kit.slider_value.paint_part(
1830 &cx,
1831 &Part {
1832 rect,
1833 room: rect,
1834 state,
1835 label: Some(&value),
1836 },
1837 );
1838 label_shown
1839}
1840
1841fn paint_vertical(
1846 ui: &Ui,
1847 rect: Rect,
1848 response: &Response,
1849 spec: &Spec,
1850 v: f64,
1851 past: bool,
1852) -> bool {
1853 let kit = Kit::of(ui.ctx());
1854 let font = egui::TextStyle::Button.resolve(ui.style());
1855 let tone = if past { Tone::Warning } else { Tone::Neutral };
1856 let state = State::from_response(response).toned(tone);
1857 let style = kit.slider.style(state);
1858 let line = ui.fonts_mut(|f| f.row_height(&font));
1859 let pad = 2.0;
1860 let fit = |text: String, color: Color32| {
1861 let mut job = egui::text::LayoutJob::simple_singleline(text, font.clone(), color);
1862 job.wrap = egui::text::TextWrapping::truncate_at_width((rect.width() - 2.0 * pad).max(1.0));
1863 ui.painter().layout_job(job)
1864 };
1865 let label = fit(spec.label.clone(), style.text);
1866 let label_shown = !label.elided;
1867 if !ui.is_rect_visible(rect) {
1868 return label_shown;
1869 }
1870 let full = spec.text(ui.ctx(), v);
1871 let mut value = fit(full.clone(), style.text);
1872 if value.elided {
1873 value = fit(spec.number(ui.ctx(), v), style.text);
1874 }
1875 let value_band = Rect::from_min_max(rect.min, pos2(rect.right(), rect.top() + line + pad));
1876 let label_band = Rect::from_min_max(pos2(rect.left(), rect.bottom() - line - pad), rect.max);
1877 let track = Rect::from_min_max(
1878 pos2(rect.left(), value_band.bottom()),
1879 pos2(rect.right(), label_band.top()),
1880 );
1881 let painter = clipped(ui, rect, style);
1882 let cx = KitCx {
1883 painter: &painter,
1884 ppp: ui.ctx().pixels_per_point(),
1885 };
1886 if track.height() > 0.0 {
1887 kit.slider.paint(
1888 &cx,
1889 &Part {
1890 rect: track,
1891 room: track,
1892 state,
1893 label: None,
1894 },
1895 );
1896 let y = track.bottom() - track.height() * spec.frac(v).clamp(0.0, 1.0) as f32;
1897 let strip = match kit.slider_fill.data.height {
1898 h if h > 0.0 => h.min(track.width()),
1899 _ => (track.width() * 0.15).max(3.0),
1900 };
1901 let tokens = Tokens::of(ui.ctx());
1902 let ramp = ramp::active(spec.ramp.as_ref(), &tokens);
1903 let side = Rect::from_min_max(
1904 pos2(track.left(), track.top()),
1905 pos2(track.left() + strip.max(4.0), track.bottom()),
1906 );
1907 if let (Some(r), RampMode::Track) = (ramp, spec.ramp_mode) {
1908 r.paint(&painter, side, &tokens, true);
1910 } else if let Some(r) = ramp {
1911 let back = backdrop(style.fill, &tokens);
1912 let color = r.value_color(spec.frac(v) as f32, &tokens, back);
1913 painter.rect_filled(
1914 Rect::from_min_max(
1915 pos2(track.left(), y),
1916 pos2(track.left() + strip, track.bottom()),
1917 ),
1918 kit.slider_fill.style(state).radius,
1919 color,
1920 );
1921 } else if let Some(g) = &spec.gradient {
1922 g.paint_vertical(&painter, side);
1924 } else {
1925 kit.slider_fill.paint_part(
1926 &cx,
1927 &Part {
1928 rect: Rect::from_min_max(
1929 pos2(track.left(), y),
1930 pos2(track.left() + strip, track.bottom()),
1931 ),
1932 room: track,
1933 state,
1934 label: None,
1935 },
1936 );
1937 }
1938 let thumb = kit.slider_thumb.style(state);
1940 let color = if thumb.fill == Color32::TRANSPARENT {
1941 style.text
1942 } else {
1943 thumb.fill
1944 };
1945 let thickness = kit.slider_thumb.data.width.max(2.0);
1946 painter.hline(track.x_range(), y, egui::Stroke::new(thickness, color));
1947 }
1948 let at = |band: Rect, g: &std::sync::Arc<egui::Galley>| {
1949 pos2(
1950 band.center().x - g.size().x / 2.0,
1951 band.center().y - g.size().y / 2.0,
1952 )
1953 };
1954 painter.galley(at(value_band, &value), value.clone(), style.text);
1955 painter.galley(at(label_band, &label), label.clone(), style.text);
1956 label_shown
1957}
1958
1959pub(crate) fn backdrop(fill: Color32, tokens: &Tokens) -> Color32 {
1962 if fill.a() < 128 {
1963 tokens.surface.panel
1964 } else {
1965 fill
1966 }
1967}
1968
1969pub(crate) fn paint_state(ui: &Ui, bar: Rect, spec: &Spec) {
1972 if spec.state.is_plain() || !ui.is_rect_visible(bar) {
1973 return;
1974 }
1975 crate::field::paint_edge(ui, bar, &spec.state);
1976 let t = Tokens::of(ui.ctx());
1977 let font = egui::TextStyle::Button.resolve(ui.style());
1978 let label = ui
1979 .painter()
1980 .layout_no_wrap(spec.label.clone(), font.clone(), t.text.default)
1981 .size()
1982 .x;
1983 let side = font.size * 0.8;
1984 crate::field::paint_markers(
1985 ui,
1986 pos2(
1987 bar.left() + Kit::of(ui.ctx()).slider.data.padding_x + label + t.space.xs,
1988 bar.center().y,
1989 ),
1990 side,
1991 t.space.xs / 2.0,
1992 &spec.state,
1993 );
1994}
1995
1996pub(crate) fn state_of(ui: &Ui, responses: &[&Response], spec: &Spec, kind: &str) {
2000 let group = format!("{:?}", responses.first().map(|r| r.id));
2001 for r in responses {
2002 crate::field::access(ui.ctx(), r.id, &spec.state);
2003 crate::tab::stop(
2004 ui,
2005 r,
2006 crate::tab::TabStop::new()
2007 .group(group.clone())
2008 .skip(!spec.state.is_focusable()),
2009 );
2010 }
2011 if let Some(r) = responses.first() {
2012 crate::field::record(ui.ctx(), r.id, &spec.label, kind, &spec.state);
2013 }
2014 match responses {
2015 [r] => crate::a11y::input(ui.ctx(), r.id, &spec.label),
2016 thumbs => {
2018 for r in thumbs {
2019 crate::a11y::drawn(ui.ctx(), r.id);
2020 }
2021 }
2022 }
2023}
2024
2025pub(crate) fn access(ui: &Ui, id: Id, spec: &Spec, value: f64, (lo, hi): (f64, f64)) {
2028 let text = spec.text(ui.ctx(), value);
2029 ui.ctx().accesskit_node_builder(id, |node| {
2030 use egui::accesskit::Action;
2031 node.set_min_numeric_value(lo.min(value));
2032 node.set_max_numeric_value(hi.max(value));
2033 node.set_numeric_value_step(spec.step);
2034 node.set_value(text);
2035 node.add_action(Action::SetValue);
2036 if value < hi {
2037 node.add_action(Action::Increment);
2038 }
2039 if value > lo {
2040 node.add_action(Action::Decrement);
2041 }
2042 });
2043}
2044
2045#[cfg(test)]
2046mod tests {
2047 use super::{Curve, Spec, parse_typed};
2048
2049 #[test]
2050 fn typed_values_keep_the_number_and_drop_the_unit() {
2051 assert_eq!(parse_typed("1,5 EV"), Some(1.5));
2052 assert_eq!(parse_typed(" -0.25"), Some(-0.25));
2053 assert_eq!(parse_typed("+3%"), Some(3.0));
2054 assert_eq!(parse_typed("EV"), None);
2055 assert_eq!(parse_typed("x"), None, "no current value");
2056 }
2057
2058 #[test]
2059 fn a_logarithmic_bar_gives_equal_ratios_equal_lengths() {
2060 let mut s = Spec::new("ISO", 100.0..=6400.0);
2061 s.curve = Curve::Logarithmic;
2062 assert!((s.frac(800.0) - 0.5).abs() < 1e-9);
2063 assert!((s.value_at(0.5) - 800.0).abs() < 1e-6);
2064 let up = s.stepped(800.0, 1.0, 1.0);
2066 assert!((s.frac(up) - 0.51).abs() < 1e-9);
2067 let mut z = Spec::new("Zero", 0.0..=10.0);
2069 z.curve = Curve::Logarithmic;
2070 assert!((z.frac(5.0) - 0.5).abs() < 1e-9);
2071 }
2072
2073 #[test]
2074 fn values_are_shown_signed_and_never_as_minus_zero() {
2075 let ctx = egui::Context::default();
2076 let mut s = Spec::new("Exposure", -3.0..=4.0);
2077 s.precision = 2;
2078 s.unit = "EV".into();
2079 assert_eq!(s.text(&ctx, -0.001), "0.00 EV");
2080 s.signed = true;
2081 assert_eq!(s.text(&ctx, 1.5), "+1.50 EV");
2082 assert_eq!(s.text(&ctx, 0.0), "0.00 EV");
2083 assert_eq!(s.text(&ctx, -1.5), "-1.50 EV");
2084 }
2085}