1use crate::component::ComponentId;
18use crate::geometry::SizeF;
19use crate::prop::{PropEnum, PropValue};
20use crate::ui::Ui;
21
22pub const PARENT: &str = "parent";
25pub const INDEX: &str = "index";
27
28pub const PLATFORMS: [&str; 6] = ["windows", "linux", "macos", "android", "ios", "web"];
30
31pub fn current_platform() -> &'static str {
33 if cfg!(target_arch = "wasm32") {
34 "web"
35 } else if cfg!(target_os = "android") {
36 "android"
37 } else if cfg!(target_os = "ios") {
38 "ios"
39 } else if cfg!(target_os = "macos") {
40 "macos"
41 } else if cfg!(target_os = "windows") {
42 "windows"
43 } else {
44 "linux"
45 }
46}
47
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
50pub enum ViewOrientation {
51 #[default]
52 Any,
53 Portrait,
55 Landscape,
57}
58
59impl PropEnum for ViewOrientation {
60 const NAMES: &'static [&'static str] = &["any", "portrait", "landscape"];
61
62 fn from_index(index: usize) -> Option<Self> {
63 [ViewOrientation::Any, ViewOrientation::Portrait, ViewOrientation::Landscape].get(index).copied()
64 }
65
66 fn index(self) -> usize {
67 self as usize
68 }
69}
70
71#[derive(Clone, Debug, PartialEq)]
74pub struct FormView {
75 pub name: String,
77 pub min_width: f32,
78 pub max_width: f32,
79 pub min_height: f32,
80 pub max_height: f32,
81 pub orientation: ViewOrientation,
82 pub platforms: Vec<String>,
84 pub font_scale: f32,
86 pub spacing_scale: f32,
89 pub changes: Vec<ViewChange>,
90}
91
92impl FormView {
93 pub fn new(name: impl Into<String>, max_width: f32) -> Self {
95 FormView {
96 name: name.into(),
97 min_width: 0.0,
98 max_width,
99 min_height: 0.0,
100 max_height: 0.0,
101 orientation: ViewOrientation::Any,
102 platforms: Vec::new(),
103 font_scale: 1.0,
104 spacing_scale: 1.0,
105 changes: Vec::new(),
106 }
107 }
108
109 pub fn matches(&self, size: SizeF, platform: &str) -> bool {
111 let within = |v: f32, min: f32, max: f32| (min <= 0.0 || v >= min) && (max <= 0.0 || v <= max);
112 within(size.width, self.min_width, self.max_width)
113 && within(size.height, self.min_height, self.max_height)
114 && match self.orientation {
115 ViewOrientation::Any => true,
116 ViewOrientation::Portrait => size.height > size.width,
117 ViewOrientation::Landscape => size.width >= size.height,
118 }
119 && (self.platforms.is_empty() || self.platforms.iter().any(|p| p == platform))
120 }
121
122 fn width_key(&self) -> f32 {
124 if self.max_width > 0.0 { self.max_width } else { f32::INFINITY }
125 }
126
127 fn scales(&self) -> (f32, f32) {
129 let clean = |s: f32| if s.is_finite() && (0.25..=4.0).contains(&s) { s } else { 1.0 };
130 (clean(self.font_scale), clean(self.spacing_scale))
131 }
132}
133
134#[derive(Clone, Debug, PartialEq)]
137pub struct ViewChange {
138 pub component: String,
140 pub property: String,
141 pub value: PropValue,
142}
143
144#[derive(Default)]
146pub(crate) struct ViewState {
147 views: Vec<FormView>,
148 active: Option<String>,
150 forced: Option<Option<String>>,
152 base: Vec<(ComponentId, String, PropValue)>,
154 moves: Vec<(ComponentId, ComponentId, usize)>,
157 scales: (f32, f32),
159}
160
161impl Ui {
162 pub fn set_views(&mut self, form: ComponentId, mut views: Vec<FormView>) {
165 views.sort_by(|a, b| a.width_key().total_cmp(&b.width_key()));
166 self.restore_view_base(form);
167 let state = self.views.entry(form).or_default();
168 state.views = views;
169 state.active = None;
170 self.layout_dirty = true;
171 self.request_repaint();
172 }
173
174 pub fn views(&self, form: ComponentId) -> &[FormView] {
175 self.views.get(&form).map_or(&[], |s| &s.views)
176 }
177
178 pub fn active_view(&self, form: ComponentId) -> Option<&str> {
180 self.views.get(&form)?.active.as_deref()
181 }
182
183 pub fn view_scales(&self, form: ComponentId) -> (f32, f32) {
185 self.own_view_scales(form).unwrap_or((1.0, 1.0))
186 }
187
188 pub(crate) fn own_view_scales(&self, form: ComponentId) -> Option<(f32, f32)> {
190 self.views.get(&form).filter(|s| s.active.is_some()).map(|s| s.scales)
191 }
192
193 pub fn force_view(&mut self, form: ComponentId, view: Option<&str>) {
196 let state = self.views.entry(form).or_default();
197 state.forced = view.map(|v| (!v.is_empty()).then(|| v.to_string()));
198 self.restore_view_base(form);
201 self.layout_dirty = true;
202 self.request_repaint();
203 }
204
205 pub fn view_base(&self, id: ComponentId, property: &str) -> Option<&PropValue> {
208 let form = self.form_of(id);
209 self.views.get(&form)?.base.iter().find(|(c, p, _)| *c == id && p == property).map(|(_, _, v)| v)
210 }
211
212 pub fn base_children(&self, id: ComponentId) -> Vec<ComponentId> {
215 let mut list = self.children(id).to_vec();
216 let form = self.form_of(id);
217 let Some(state) = self.views.get(&form).filter(|s| !s.moves.is_empty()) else { return list };
218 for &(moved, old_parent, old_index) in state.moves.iter().rev() {
220 list.retain(|&c| c != moved);
221 if old_parent == id {
222 list.insert(old_index.min(list.len()), moved);
223 }
224 }
225 list
226 }
227
228 pub fn view_base_place(&self, id: ComponentId) -> Option<(ComponentId, usize)> {
230 let form = self.form_of(id);
231 self.views.get(&form)?.moves.iter().find(|m| m.0 == id).map(|&(_, p, i)| (p, i))
232 }
233
234 pub fn update_active_view(
239 &mut self,
240 form: ComponentId,
241 changes: Vec<ViewChange>,
242 base: Vec<(ComponentId, String, PropValue)>,
243 moves: Vec<(ComponentId, ComponentId, usize)>,
244 ) {
245 let Some(state) = self.views.get_mut(&form) else { return };
246 let Some(active) = state.active.clone() else { return };
247 if let Some(view) = state.views.iter_mut().find(|v| v.name == active) {
248 view.changes = changes;
249 }
250 state.base = base;
251 state.moves = moves;
252 }
253
254 pub fn set_view_scales(&mut self, form: ComponentId, name: &str, font_scale: f32, spacing_scale: f32) {
256 let Some(state) = self.views.get_mut(&form) else { return };
257 let Some(view) = state.views.iter_mut().find(|v| v.name == name) else { return };
258 view.font_scale = font_scale;
259 view.spacing_scale = spacing_scale;
260 if state.active.as_deref() == Some(name) {
261 state.scales = view.scales();
262 }
263 self.layout_dirty = true;
264 self.request_repaint();
265 }
266
267 fn restore_view_base(&mut self, form: ComponentId) {
269 let Some(state) = self.views.get_mut(&form) else { return };
270 let base = std::mem::take(&mut state.base);
271 let moves = std::mem::take(&mut state.moves);
272 let had_scales = state.scales != (1.0, 1.0);
273 state.active = None;
274 state.scales = (1.0, 1.0);
275 for (id, prop, value) in base.into_iter().rev() {
276 let _ = self.set_prop_quiet(id, &prop, value);
277 }
278 for (id, parent, index) in moves.into_iter().rev() {
279 if self.parent(id) != Some(parent) {
280 let _ = self.set_parent(id, Some(parent));
281 }
282 let _ = self.set_child_index(id, index);
283 }
284 if had_scales {
285 self.invalidate_form(form);
286 }
287 }
288
289 fn view_target(&self, form: ComponentId, component: &str) -> Option<ComponentId> {
291 if component.is_empty() { Some(form) } else { self.find_in(form, component) }
292 }
293
294 pub(crate) fn apply_views(&mut self) {
296 let forms: Vec<ComponentId> = self.views.keys().copied().collect();
297 let platform = current_platform();
298 for form in forms {
299 let Some(size) = self.cb(form).map(|cb| SizeF::new(cb.width(), cb.height())) else {
300 self.views.remove(&form);
301 continue;
302 };
303 let state = &self.views[&form];
304 let wanted = match &state.forced {
305 Some(view) => view.clone(),
306 None => state.views.iter().find(|v| v.matches(size, platform)).map(|v| v.name.clone()),
307 };
308 if wanted == state.active {
309 continue;
310 }
311 self.restore_view_base(form);
312 if !self.design_mode {
316 self.queue_event(form, "on_view_change", crate::EventArgs::Text(wanted.clone().unwrap_or_default()));
317 }
318 let Some(view) = wanted.as_ref().and_then(|w| self.views[&form].views.iter().find(|v| &v.name == w).cloned()) else { continue };
319 let mut moves = Vec::new();
321 for change in view.changes.iter().filter(|c| c.property == PARENT).chain(view.changes.iter().filter(|c| c.property == INDEX)) {
322 let Some(id) = self.view_target(form, &change.component) else { continue };
323 let Some(old_parent) = self.parent(id) else { continue };
324 let old_index = self.children(old_parent).iter().position(|&c| c == id).unwrap_or(0);
325 let done = if change.property == PARENT {
326 let target = match change.value.to_str().unwrap_or("") {
327 "" => Some(form),
328 name => self.find_in(form, name).or_else(|| (self.name(form) == Some(name)).then_some(form)),
329 };
330 target.is_some_and(|t| t == old_parent || self.set_parent(id, Some(t)).is_ok())
331 } else {
332 let index = change.value.to_f64().map_or(0, |i| i.max(0.0) as usize);
333 self.set_child_index(id, index).is_ok()
334 };
335 if done {
336 moves.push((id, old_parent, old_index));
337 }
338 }
339 let mut base = Vec::new();
340 for change in view.changes.iter().filter(|c| c.property != PARENT && c.property != INDEX) {
341 let Some(id) = self.view_target(form, &change.component) else { continue };
342 let Ok(old) = self.get_prop(id, &change.property) else { continue };
343 if self.set_prop_quiet(id, &change.property, change.value.clone()).is_ok() {
344 base.push((id, change.property.clone(), old));
345 }
346 }
347 let scales = view.scales();
348 if scales != (1.0, 1.0) {
349 self.invalidate_form(form);
350 }
351 if let Some(state) = self.views.get_mut(&form) {
352 state.base = base;
353 state.moves = moves;
354 state.active = wanted;
355 state.scales = scales;
356 }
357 }
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364
365 fn size(width: f32, height: f32) -> SizeF {
366 SizeF::new(width, height)
367 }
368
369 #[test]
370 fn the_limits_include_the_edges_and_zero_is_no_limit() {
371 let mut v = FormView::new("faixa", 599.0);
372 v.min_width = 400.0;
373 assert!(v.matches(size(599.0, 800.0), "windows"), "o máximo vale");
374 assert!(v.matches(size(400.0, 800.0), "windows"), "o mínimo vale");
375 assert!(!v.matches(size(599.5, 800.0), "windows"));
376 assert!(!v.matches(size(399.0, 800.0), "windows"));
377 let open = FormView::new("sem limite", 0.0);
378 assert!(open.matches(size(10.0, 10.0), "web") && open.matches(size(99_999.0, 99_999.0), "web"));
379 let mut tall = FormView::new("alta", 0.0);
380 (tall.min_height, tall.max_height) = (500.0, 900.0);
381 assert!(tall.matches(size(300.0, 500.0), "linux") && tall.matches(size(300.0, 900.0), "linux"));
382 assert!(!tall.matches(size(300.0, 901.0), "linux") && !tall.matches(size(300.0, 499.0), "linux"));
383 }
384
385 #[test]
386 fn a_square_form_is_landscape() {
387 let mut portrait = FormView::new("retrato", 0.0);
388 portrait.orientation = ViewOrientation::Portrait;
389 let mut landscape = FormView::new("paisagem", 0.0);
390 landscape.orientation = ViewOrientation::Landscape;
391 assert!(landscape.matches(size(500.0, 500.0), "ios") && !portrait.matches(size(500.0, 500.0), "ios"));
392 assert!(portrait.matches(size(500.0, 501.0), "ios") && !landscape.matches(size(500.0, 501.0), "ios"));
393 }
394
395 #[test]
396 fn the_platforms_restrict_and_empty_means_all() {
397 let mut mobile = FormView::new("móvel", 0.0);
398 mobile.platforms = vec!["android".into(), "ios".into()];
399 assert!(mobile.matches(size(400.0, 800.0), "android"));
400 assert!(!mobile.matches(size(400.0, 800.0), "windows"));
401 assert!(FormView::new("todas", 0.0).matches(size(400.0, 800.0), "windows"));
402 assert!(PLATFORMS.contains(¤t_platform()));
403 }
404
405 #[test]
406 fn invalid_scales_become_one() {
407 let mut v = FormView::new("x", 0.0);
408 for (font, spacing, expected) in [(0.5, 2.0, (0.5, 2.0)), (0.0, 5.0, (1.0, 1.0)), (f32::NAN, 0.25, (1.0, 0.25)), (4.0, f32::INFINITY, (4.0, 1.0))] {
409 (v.font_scale, v.spacing_scale) = (font, spacing);
410 assert_eq!(v.scales(), expected, "{font} {spacing}");
411 }
412 }
413
414 #[test]
415 fn the_narrowest_view_comes_first_and_no_limit_last() {
416 let mut ui = Ui::new();
417 let form = ComponentId { index: 0, generation: 0 };
418 ui.set_views(form, vec![FormView::new("larga", 0.0), FormView::new("tablet", 1023.0), FormView::new("phone", 599.0)]);
419 let names: Vec<&str> = ui.views(form).iter().map(|v| v.name.as_str()).collect();
420 assert_eq!(names, ["phone", "tablet", "larga"]);
421 }
422}