1use crate::geom::LogicalPoint;
16use crate::validate::ValidationError;
17
18const INSET: f64 = 0.10;
24
25#[derive(Debug, Clone, Copy, PartialEq)]
27pub struct Position {
28 pub x: f64,
30 pub y: f64,
32}
33
34impl Position {
35 pub const fn new(x: f64, y: f64) -> Self {
37 Self { x, y }
38 }
39
40 pub fn parse(raw: &str) -> Result<Self, ValidationError> {
46 let text = raw.trim().to_ascii_lowercase();
47 if text.is_empty() {
48 return Err(ValidationError::Empty { field: "at" });
49 }
50
51 let (near, mid, far) = (INSET, 0.5, 1.0 - INSET);
52 let named = match text.replace('_', "-").as_str() {
53 "top-left" => Some((near, near)),
54 "top" | "top-center" | "top-centre" => Some((mid, near)),
55 "top-right" => Some((far, near)),
56 "left" | "center-left" | "centre-left" => Some((near, mid)),
57 "center" | "centre" | "middle" => Some((mid, mid)),
58 "right" | "center-right" | "centre-right" => Some((far, mid)),
59 "bottom-left" => Some((near, far)),
60 "bottom" | "bottom-center" | "bottom-centre" => Some((mid, far)),
61 "bottom-right" => Some((far, far)),
62 _ => None,
63 };
64 if let Some((x, y)) = named {
65 return Ok(Self::new(x, y));
66 }
67
68 Self::parse_percentages(&text, raw)
69 }
70
71 fn parse_percentages(text: &str, raw: &str) -> Result<Self, ValidationError> {
73 let (left, right) = text
74 .split_once(',')
75 .ok_or(ValidationError::UnknownPosition {
76 got: raw.to_owned(),
77 })?;
78
79 let percentage = |part: &str| -> Result<f64, ValidationError> {
83 let value = part
84 .trim()
85 .strip_suffix('%')
86 .ok_or(ValidationError::UnknownPosition {
87 got: raw.to_owned(),
88 })?;
89 let value: f64 =
90 value
91 .trim()
92 .parse()
93 .map_err(|_| ValidationError::UnknownPosition {
94 got: raw.to_owned(),
95 })?;
96 if !value.is_finite() || !(0.0..=100.0).contains(&value) {
97 return Err(ValidationError::PositionOutOfRange {
98 got: part.trim().to_owned(),
99 });
100 }
101 Ok(value / 100.0)
102 };
103
104 Ok(Self::new(percentage(left)?, percentage(right)?))
105 }
106
107 pub fn resolve(self, logical_size: [f64; 2]) -> LogicalPoint {
109 LogicalPoint::new(self.x * logical_size[0], self.y * logical_size[1])
110 }
111
112 pub const NAMES: &'static [&'static str] = &[
114 "top-left",
115 "top",
116 "top-right",
117 "left",
118 "center",
119 "right",
120 "bottom-left",
121 "bottom",
122 "bottom-right",
123 ];
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129
130 const DISPLAY: [f64; 2] = [1512.0, 982.0];
131
132 #[test]
133 fn every_documented_name_parses() {
134 for name in Position::NAMES {
135 assert!(Position::parse(name).is_ok(), "{name} should parse");
136 }
137 }
138
139 #[test]
140 fn the_corners_are_inset_rather_than_at_the_origin() {
141 let at = Position::parse("top-left").unwrap().resolve(DISPLAY);
143 assert!(at.x > 0.0 && at.y > 0.0, "{at:?} is in the corner itself");
144 assert!(at.x < DISPLAY[0] / 2.0 && at.y < DISPLAY[1] / 2.0);
145
146 let at = Position::parse("bottom-right").unwrap().resolve(DISPLAY);
147 assert!(
148 at.x < DISPLAY[0] && at.y < DISPLAY[1],
149 "{at:?} is off screen"
150 );
151 assert!(at.x > DISPLAY[0] / 2.0 && at.y > DISPLAY[1] / 2.0);
152 }
153
154 #[test]
155 fn center_is_the_middle_of_the_display() {
156 let at = Position::parse("center").unwrap().resolve(DISPLAY);
157 assert_eq!(at.x, DISPLAY[0] / 2.0);
158 assert_eq!(at.y, DISPLAY[1] / 2.0);
159 }
160
161 #[test]
162 fn both_spellings_of_centre_agree() {
163 assert_eq!(Position::parse("center"), Position::parse("centre"));
164 assert_eq!(Position::parse("top"), Position::parse("top-centre"));
165 }
166
167 #[test]
168 fn case_space_and_underscores_are_forgiven() {
169 let expected = Position::parse("top-left").unwrap();
170 for spelling in [" TOP-LEFT ", "Top-Left", "top_left"] {
171 assert_eq!(Position::parse(spelling).unwrap(), expected, "{spelling:?}");
172 }
173 }
174
175 #[test]
176 fn percentages_resolve_against_the_display() {
177 let at = Position::parse("50%,30%").unwrap().resolve(DISPLAY);
178 assert_eq!(at.x, DISPLAY[0] * 0.5);
179 assert!((at.y - DISPLAY[1] * 0.3).abs() < 1e-9);
180 }
181
182 #[test]
183 fn percentages_tolerate_spacing_and_decimals() {
184 let at = Position::parse(" 12.5% , 7.5% ").unwrap();
185 assert!((at.x - 0.125).abs() < 1e-9);
186 assert!((at.y - 0.075).abs() < 1e-9);
187 }
188
189 #[test]
190 fn the_edges_of_the_range_are_allowed() {
191 assert_eq!(Position::parse("0%,0%").unwrap(), Position::new(0.0, 0.0));
192 assert_eq!(
193 Position::parse("100%,100%").unwrap(),
194 Position::new(1.0, 1.0)
195 );
196 }
197
198 #[test]
202 fn a_bare_number_pair_is_refused() {
203 assert!(matches!(
204 Position::parse("50,30"),
205 Err(ValidationError::UnknownPosition { .. })
206 ));
207 assert!(matches!(
208 Position::parse("50%,30"),
209 Err(ValidationError::UnknownPosition { .. })
210 ));
211 }
212
213 #[test]
214 fn nonsense_is_refused_with_what_was_sent() {
215 let Err(ValidationError::UnknownPosition { got }) = Position::parse("north-by-northwest")
216 else {
217 panic!("expected an unknown position");
218 };
219 assert_eq!(got, "north-by-northwest");
220 }
221
222 #[test]
223 fn a_percentage_off_the_display_is_refused() {
224 assert!(matches!(
225 Position::parse("150%,30%"),
226 Err(ValidationError::PositionOutOfRange { .. })
227 ));
228 assert!(matches!(
229 Position::parse("-10%,30%"),
230 Err(ValidationError::PositionOutOfRange { .. })
231 ));
232 }
233
234 #[test]
235 fn an_empty_position_is_refused() {
236 assert!(matches!(
237 Position::parse(" "),
238 Err(ValidationError::Empty { .. })
239 ));
240 }
241
242 #[test]
243 fn every_name_lands_on_the_display() {
244 for name in Position::NAMES {
245 let at = Position::parse(name).unwrap().resolve(DISPLAY);
246 assert!(
247 (0.0..=DISPLAY[0]).contains(&at.x) && (0.0..=DISPLAY[1]).contains(&at.y),
248 "{name} resolved off the display to {at:?}"
249 );
250 }
251 }
252}