Skip to main content

bhoo/systems/android/
reference.rs

1//! Static Android resource trees with explicit custom-view adapters.
2//! This is a view/layout bridge, not an Android runtime or general ConstraintLayout solver.
3use crate::*;
4use std::collections::{HashMap, HashSet};
5pub struct NativeNode {
6    pub kind: &'static str,
7    pub id: &'static str,
8    pub attrs: &'static [(&'static str, &'static str)],
9    pub children: &'static [NativeNode],
10}
11#[derive(Default)]
12pub struct NativeState {
13    pub text: HashMap<String, String>,
14    pub hidden: HashSet<String>,
15    pub slots: HashMap<String, Rect>,
16}
17fn hash(s: &str, seed: u64) -> u64 {
18    s.bytes().fold(seed + 1469598103934665603, |h, b| {
19        (h ^ b as u64).wrapping_mul(1099511628211)
20    }) & ((1 << 52) - 1)
21}
22impl NativeNode {
23    pub fn attr(&self, key: &str) -> &str {
24        self.attrs
25            .iter()
26            .find(|(k, _)| *k == key)
27            .map_or("", |(_, v)| v)
28    }
29    fn n(&self, key: &str, default: f32) -> f32 {
30        self.attr(key)
31            .trim_end_matches("dp")
32            .trim_end_matches("sp")
33            .trim_end_matches("px")
34            .parse()
35            .unwrap_or(default)
36    }
37    fn gone(&self, s: &NativeState) -> bool {
38        self.attr("visibility") == "gone" || s.hidden.contains(self.id)
39    }
40    fn content<'a>(&'a self, s: &'a NativeState) -> &'a str {
41        s.text
42            .get(self.id)
43            .map_or(self.attr("text"), String::as_str)
44    }
45    fn edges(&self, prefix: &str) -> [f32; 4] {
46        let all = self.n(prefix, 0.);
47        let horizontal = self.n(&format!("{prefix}Horizontal"), all);
48        let vertical = self.n(&format!("{prefix}Vertical"), all);
49        [
50            self.n(
51                &format!("{prefix}Start"),
52                self.n(&format!("{prefix}Left"), horizontal),
53            ),
54            self.n(&format!("{prefix}Top"), vertical),
55            self.n(
56                &format!("{prefix}End"),
57                self.n(&format!("{prefix}Right"), horizontal),
58            ),
59            self.n(&format!("{prefix}Bottom"), vertical),
60        ]
61    }
62    fn measure(&self, axis: usize, available: f32, f: &Frame<'_>, s: &NativeState) -> f32 {
63        if self.gone(s) {
64            return 0.;
65        }
66        let key = if axis == 0 {
67            "layout_width"
68        } else {
69            "layout_height"
70        };
71        let v = self.attr(key);
72        if matches!(v, "match_parent" | "fill_parent") {
73            return available;
74        }
75        if let Ok(n) = v
76            .trim_end_matches("dp")
77            .trim_end_matches("sp")
78            .parse::<f32>()
79        {
80            return n.max(0.);
81        }
82        let padding = self.edges("padding");
83        let extra = padding[axis] + padding[axis + 2];
84        let intrinsic = match self.kind {
85            "Text" => {
86                if axis == 0 {
87                    f.text_width(
88                        self.content(s),
89                        TextStyle {
90                            size: self.n("textSize", 16.),
91                            ..TextStyle::default()
92                        },
93                    )
94                } else {
95                    self.n("textSize", 16.) * 1.45
96                }
97            }
98            "Avatar" | "Icon" => 48.,
99            "Slot" => self.n(if axis == 0 { "minWidth" } else { "minHeight" }, 0.),
100            _ => {
101                let sum = self.kind == "Linear"
102                    && ((self.attr("orientation") == "horizontal") == (axis == 0));
103                let mut value: f32 = 0.;
104                for c in self.children {
105                    let m = c.edges("layout_margin");
106                    let size = c.measure(axis, available, f, s) + m[axis] + m[axis + 2];
107                    value = if sum { value + size } else { value.max(size) }
108                }
109                value
110            }
111        };
112        (intrinsic + extra)
113            .max(self.n(if axis == 0 { "minWidth" } else { "minHeight" }, 0.))
114            .min(available)
115    }
116    pub fn render(
117        &'static self,
118        f: &mut Frame<'_>,
119        b: Rect,
120        s: &mut NativeState,
121        instance: u64,
122    ) -> bool {
123        self.draw(f, b, s, instance)
124    }
125    fn draw(&'static self, f: &mut Frame<'_>, b: Rect, s: &mut NativeState, instance: u64) -> bool {
126        if self.gone(s) || self.attr("visibility") == "invisible" || b.width <= 0. || b.height <= 0.
127        {
128            return false;
129        }
130        let id = hash(self.id, instance);
131        s.slots.insert(self.id.into(), b);
132        let theme = f.theme();
133        let mut clicked = false;
134        if let Some(color) = color(self.attr("background")) {
135            f.paint_rect(b, self.n("cornerRadius", 0.), color)
136        }
137        if self.attr("clickable") == "true" {
138            let r = f.target(id, b, self.content(s), true, Role::Button);
139            f.state_layer(r, 12., theme.primary);
140            clicked = r.clicked;
141        }
142        let p = self.edges("padding");
143        let inner = Rect {
144            x: b.x + p[0],
145            y: b.y + p[1],
146            width: (b.width - p[0] - p[2]).max(0.),
147            height: (b.height - p[1] - p[3]).max(0.),
148        };
149        match self.kind {
150            "Slot" => {}
151            "Avatar" => {
152                f.paint_rect(
153                    inner,
154                    inner.width.min(inner.height) / 2.,
155                    color(self.attr("tint")).unwrap_or(theme.secondary),
156                );
157                let name = self.content(s);
158                let initials = name
159                    .split_whitespace()
160                    .filter_map(|w| w.chars().next())
161                    .take(2)
162                    .collect::<String>()
163                    .to_uppercase();
164                f.styled_text(
165                    inner,
166                    &initials,
167                    theme.on_secondary,
168                    TextStyle {
169                        size: 18.,
170                        align: 1,
171                        ..TextStyle::default()
172                    },
173                );
174            }
175            "Text" => {
176                let text = self.content(s);
177                let style = TextStyle {
178                    size: self.n("textSize", 16.),
179                    weight: if self.attr("textStyle") == "bold" {
180                        700
181                    } else {
182                        400
183                    },
184                    align: if self.attr("gravity").contains("center_horizontal")
185                        || self.attr("gravity") == "center"
186                    {
187                        1
188                    } else if self.attr("gravity").contains("end") {
189                        2
190                    } else {
191                        0
192                    },
193                    ..TextStyle::default()
194                };
195                let ink = color(self.attr("textColor")).unwrap_or(theme.text);
196                if self.attr("maxLines") == "1"
197                    || self.attr("singleLine") == "true"
198                    || inner.height < style.size * 2.
199                {
200                    let shortened;
201                    let text = if f.text_width(text, style) > inner.width {
202                        let chars: Vec<char> = text.chars().collect();
203                        let mut lo = 0;
204                        let mut hi = chars.len();
205                        while lo < hi {
206                            let mid = (lo + hi).div_ceil(2);
207                            let candidate = chars[..mid].iter().collect::<String>() + "…";
208                            if f.text_width(&candidate, style) <= inner.width {
209                                lo = mid;
210                            } else {
211                                hi = mid - 1;
212                            }
213                        }
214                        shortened = chars[..lo].iter().collect::<String>() + "…";
215                        shortened.as_str()
216                    } else {
217                        text
218                    };
219                    f.styled_text(inner, text, ink, style);
220                } else {
221                    f.paragraph(inner, text, ink, style, style.size * 1.45);
222                }
223            }
224            "Icon" => {
225                let icon = match self.attr("icon") {
226                    "search" => MaterialIcon::Search,
227                    "add" => MaterialIcon::Add,
228                    "back" => MaterialIcon::ArrowBack,
229                    "send" => MaterialIcon::ArrowForward,
230                    "more" => MaterialIcon::MoreVert,
231                    "check" => MaterialIcon::Check,
232                    _ => MaterialIcon::Menu,
233                };
234                f.paint_material_icon(
235                    Rect {
236                        x: inner.x + (inner.width - 24.) / 2.,
237                        y: inner.y + (inner.height - 24.) / 2.,
238                        width: 24.,
239                        height: 24.,
240                    },
241                    icon,
242                    color(self.attr("textColor")).unwrap_or(theme.text),
243                );
244            }
245            "Picture" => {
246                let shades = [
247                    Color(71, 121, 72, 255),
248                    Color(47, 111, 91, 255),
249                    Color(96, 133, 60, 255),
250                ];
251                let ink = shades[(instance as usize) % 3];
252                f.paint_rect(inner, 12., ink.opacity(0.14));
253                let stem = Rect {
254                    x: inner.x + inner.width / 2. - 2.,
255                    y: inner.y + inner.height * 0.3,
256                    width: 4.,
257                    height: inner.height * 0.55,
258                };
259                f.paint_rect(stem, 2., ink);
260                for j in 0..4 {
261                    let left = j % 2 == 0;
262                    let w = inner.width * 0.22;
263                    f.paint_rect(
264                        Rect {
265                            x: stem.x + if left { -w } else { 0. },
266                            y: stem.y + 8. + j as f32 * inner.height * 0.09,
267                            width: w,
268                            height: inner.height * 0.18,
269                        },
270                        inner.height * 0.09,
271                        ink,
272                    );
273                }
274            }
275            "Linear" => {
276                let horiz = self.attr("orientation") == "horizontal";
277                let axis = usize::from(!horiz);
278                let avail = if horiz { inner.width } else { inner.height };
279                let mut fixed = 0.;
280                let mut weights = 0.;
281                for c in self.children {
282                    if c.gone(s) {
283                        continue;
284                    }
285                    let m = c.edges("layout_margin");
286                    let weight = c.n("layout_weight", 0.);
287                    weights += weight;
288                    fixed += if weight > 0. {
289                        m[axis] + m[axis + 2]
290                    } else {
291                        c.measure(axis, avail, f, s) + m[axis] + m[axis + 2]
292                    };
293                }
294                let mut cursor = if horiz { inner.x } else { inner.y };
295                let gravity = self.attr("gravity");
296                if weights == 0.
297                    && ((!horiz && gravity.contains("center_vertical")) || gravity == "center")
298                {
299                    cursor += (avail - fixed).max(0.) / 2.;
300                }
301                for (i, c) in self.children.iter().enumerate() {
302                    if c.gone(s) {
303                        continue;
304                    }
305                    let m = c.edges("layout_margin");
306                    let len = if c.n("layout_weight", 0.) > 0. {
307                        (avail - fixed).max(0.) * c.n("layout_weight", 0.) / weights
308                    } else {
309                        c.measure(axis, avail, f, s)
310                    };
311                    let cross = if horiz { inner.height } else { inner.width };
312                    let crosslen =
313                        c.measure(1 - axis, (cross - m[1 - axis] - m[3 - axis]).max(0.), f, s);
314                    let align = if c.attr("layout_gravity").is_empty() {
315                        gravity
316                    } else {
317                        c.attr("layout_gravity")
318                    };
319                    let shift = if align.contains("center") {
320                        (cross - crosslen) / 2.
321                    } else if align.contains("end") {
322                        cross - crosslen - m[2]
323                    } else {
324                        m[1 - axis]
325                    };
326                    let r = if horiz {
327                        Rect {
328                            x: cursor + m[0],
329                            y: inner.y + shift,
330                            width: len,
331                            height: crosslen,
332                        }
333                    } else {
334                        Rect {
335                            x: inner.x + shift,
336                            y: cursor + m[1],
337                            width: crosslen,
338                            height: len,
339                        }
340                    };
341                    clicked |= c.draw(f, r, s, instance.wrapping_add(i as u64 * 100));
342                    cursor += len + m[axis] + m[axis + 2];
343                }
344            }
345            _ => {
346                let mut rects: Vec<Rect> = self
347                    .children
348                    .iter()
349                    .map(|c| Rect {
350                        x: inner.x,
351                        y: inner.y,
352                        width: c.measure(0, inner.width, f, s),
353                        height: c.measure(1, inner.height, f, s),
354                    })
355                    .collect();
356                // Bounded relaxation supports the sibling constraints in the imported templates.
357                for _ in 0..10 {
358                    for (i, c) in self.children.iter().enumerate() {
359                        let lookup = |reference: &str| {
360                            let name = reference.rsplit('/').next().unwrap_or(reference);
361                            if name == "parent" {
362                                inner
363                            } else {
364                                self.children
365                                    .iter()
366                                    .position(|n| n.id == name)
367                                    .map_or(inner, |j| rects[j])
368                            }
369                        };
370                        let mut r = rects[i];
371                        let m = c.edges("layout_margin");
372                        if c.kind == "Guideline" {
373                            let pos = c.n("layout_constraintGuide_begin", 0.);
374                            if c.attr("orientation") == "vertical" {
375                                r.x = inner.x + pos;
376                                r.width = 0.
377                            } else {
378                                r.y = if c.attr("layout_constraintGuide_end").is_empty() {
379                                    inner.y + pos
380                                } else {
381                                    inner.y + inner.height - c.n("layout_constraintGuide_end", 0.)
382                                };
383                                r.height = 0.
384                            }
385                            rects[i] = r;
386                            continue;
387                        }
388                        if c.kind == "Barrier" {
389                            let refs = c.attr("constraint_referenced_ids");
390                            let end = c.attr("barrierDirection") == "end";
391                            let val = refs
392                                .split(',')
393                                .map(|v| lookup(v.trim()))
394                                .map(|v| if end { v.x + v.width } else { v.y + v.height })
395                                .fold(if end { inner.x } else { inner.y }, f32::max);
396                            if end {
397                                r.x = val;
398                                r.width = 0.
399                            } else {
400                                r.y = val;
401                                r.height = 0.
402                            }
403                            rects[i] = r;
404                            continue;
405                        }
406                        let mut start = [None, None];
407                        let mut end = [None, None];
408                        for (key, axis, side, target_end) in [
409                            ("layout_constraintStart_toStartOf", 0, 0, false),
410                            ("layout_constraintStart_toEndOf", 0, 0, true),
411                            ("layout_constraintEnd_toStartOf", 0, 1, false),
412                            ("layout_constraintEnd_toEndOf", 0, 1, true),
413                            ("layout_constraintTop_toTopOf", 1, 0, false),
414                            ("layout_constraintTop_toBottomOf", 1, 0, true),
415                            ("layout_constraintBottom_toTopOf", 1, 1, false),
416                            ("layout_constraintBottom_toBottomOf", 1, 1, true),
417                            ("layout_below", 1, 0, true),
418                            ("layout_toEndOf", 0, 0, true),
419                            ("layout_toRightOf", 0, 0, true),
420                            ("layout_toStartOf", 0, 1, false),
421                            ("layout_above", 1, 1, false),
422                        ] {
423                            let v = c.attr(key);
424                            if !v.is_empty() {
425                                let q = lookup(v);
426                                let value = if axis == 0 {
427                                    q.x + if target_end { q.width } else { 0. }
428                                } else {
429                                    q.y + if target_end { q.height } else { 0. }
430                                };
431                                if side == 0 {
432                                    start[axis] = Some(value)
433                                } else {
434                                    end[axis] = Some(value)
435                                }
436                            }
437                        }
438                        if c.attr("layout_alignParentEnd") == "true"
439                            || c.attr("layout_gravity").contains("end")
440                        {
441                            end[0] = Some(inner.x + inner.width)
442                        }
443                        if c.attr("layout_alignParentBottom") == "true"
444                            || c.attr("layout_gravity").contains("bottom")
445                        {
446                            end[1] = Some(inner.y + inner.height)
447                        }
448                        for axis in 0..2 {
449                            let key = if axis == 0 {
450                                "layout_width"
451                            } else {
452                                "layout_height"
453                            };
454                            let mut len = c.measure(
455                                axis,
456                                if axis == 0 { inner.width } else { inner.height },
457                                f,
458                                s,
459                            );
460                            let origin = if axis == 0 { inner.x } else { inner.y };
461                            let available = if axis == 0 { inner.width } else { inner.height };
462                            let lo = start[axis].map(|v| v + m[axis]);
463                            let hi = end[axis].map(|v| v - m[axis + 2]);
464                            let matching =
465                                matches!(c.attr(key), "match_parent" | "fill_parent" | "0dp");
466                            if matching {
467                                len = (hi.unwrap_or(origin + available - m[axis + 2])
468                                    - lo.unwrap_or(origin + m[axis]))
469                                .max(0.);
470                            }
471                            let pos = match (lo, hi) {
472                                (Some(l), Some(h)) => {
473                                    len = len.min((h - l).max(0.));
474                                    l + (h - l - len)
475                                        * c.n(
476                                            if axis == 0 {
477                                                "layout_constraintHorizontal_bias"
478                                            } else {
479                                                "layout_constraintVertical_bias"
480                                            },
481                                            0.5,
482                                        )
483                                }
484                                (Some(l), _) => l,
485                                (_, Some(h)) => h - len,
486                                _ => origin + m[axis],
487                            };
488                            let center = c.attr(if axis == 0 {
489                                "layout_centerHorizontal"
490                            } else {
491                                "layout_centerVertical"
492                            }) == "true"
493                                || c.attr("layout_centerInParent") == "true";
494                            let pos = if center {
495                                origin + (available - len) / 2.
496                            } else {
497                                pos
498                            };
499                            if axis == 0 {
500                                r.x = pos;
501                                r.width = len
502                            } else {
503                                r.y = pos;
504                                r.height = len
505                            }
506                        }
507                        if c.gone(s) {
508                            r.width = 0.;
509                            r.height = 0.;
510                        }
511                        rects[i] = r;
512                    }
513                }
514                for (i, (c, r)) in self.children.iter().zip(rects).enumerate() {
515                    clicked |= c.draw(f, r, s, instance.wrapping_add(i as u64 * 100));
516                }
517            }
518        }
519        clicked
520    }
521}
522fn color(s: &str) -> Option<Color> {
523    let s = s.strip_prefix('#')?;
524    let n = u32::from_str_radix(s, 16).ok()?;
525    Some(Color(
526        (n >> 16) as u8,
527        (n >> 8) as u8,
528        n as u8,
529        if s.len() == 8 { (n >> 24) as u8 } else { 255 },
530    ))
531}