xonecas.io
8447
Co

conveyor / files

conveyor / templates / library / widgets / tiles.rs

10.9 KB
1//! The tiled canvas's layout, i3-style: the canvas cut into rectangles, one per card, with a gap
2//! between neighbours. Every gap between two cards drags on its own: it moves the cards along that
3//! stretch of the line only, up to where another gap crosses it. A card dropped near another's edge
4//! takes half of it; dropped on its middle, the two swap; dropped at the canvas's edge, it takes
5//! that whole side. A closed card's room goes to its neighbours along one of its sides.
6use std::path::{Path, PathBuf};
7
8/// The gap around and between tiles.
9pub const GAP: f32 = 8.0;
10/// The smallest a tile shrinks to when a gap beside it is dragged.
11const MIN: f32 = 120.0;
12/// How near the canvas's edge a drop takes that whole side.
13const EDGE: f32 = 24.0;
14/// How near two edges are to count as one.
15const EPS: f32 = 1e-4;
16
17pub type Rect = (f32, f32, f32, f32);
18
19/// A card's key and its edges as fractions of the canvas: left, top, right, bottom. Along axis
20/// `a` (0 across, 1 down) a tile runs from `e[a]` to `e[a + 2]`.
21type Tile = (String, [f32; 4]);
22
23/// Where a dropped card goes against the tile under it.
24#[derive(Clone, Copy, PartialEq)]
25pub enum Zone { Left, Right, Top, Bottom, Swap }
26
27#[derive(Clone)]
28pub struct Tiles {
29    tiles: Vec<Tile>,
30    file: PathBuf,
31}
32
33fn near(a: f32, b: f32) -> bool { (a - b).abs() < EPS }
34
35/// Whether `e` and `f` share more than a point along axis `a`.
36fn overlap(e: &[f32; 4], f: &[f32; 4], a: usize) -> bool { e[a] < f[a + 2] - EPS && f[a] < e[a + 2] - EPS }
37
38/// The tile with edges `e` on a canvas of `size`, in points: `GAP` from the canvas's edge and between neighbours.
39fn px(e: &[f32; 4], (w, h): (f32, f32)) -> Rect {
40    let (sw, sh) = (w - GAP, h - GAP);
41    (e[0] * sw + GAP, e[1] * sh + GAP, (e[2] - e[0]) * sw - GAP, (e[3] - e[1]) * sh - GAP)
42}
43
44fn inside(p: (f32, f32), (x, y, w, h): Rect) -> bool { p.0 >= x && p.0 < x + w && p.1 >= y && p.1 < y + h }
45
46/// The axis a drop in `zone` halves along, and whether the new card takes the first half.
47fn halves(zone: Zone) -> (usize, bool) { (matches!(zone, Zone::Top | Zone::Bottom) as usize, matches!(zone, Zone::Left | Zone::Top)) }
48
49impl Tiles {
50    /// The file holds the tiles as JSON: `[[key, [left, top, right, bottom]], ..]`.
51    pub fn load(file: &Path) -> Self {
52        let tiles = std::fs::read_to_string(file).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
53        Tiles { tiles, file: file.to_owned() }
54    }
55
56    pub fn save(&self) { let _ = std::fs::write(&self.file, serde_json::to_string(&self.tiles).unwrap_or_default()); }
57
58    fn find(&self, key: &str) -> Option<usize> { self.tiles.iter().position(|t| t.0 == key) }
59
60    /// The rect of the card keyed `key` on a canvas of `size`.
61    pub fn rect(&self, key: &str, size: (f32, f32)) -> Option<Rect> { self.find(key).map(|i| px(&self.tiles[i].1, size)) }
62
63    /// Makes the layout hold exactly `keys`: drops the others, and fits each new one by halving
64    /// the biggest tile along its longer side. Says whether anything changed.
65    pub fn sync(&mut self, keys: &[String], size: (f32, f32)) -> bool {
66        let before = self.tiles.clone();
67        let size = if size.0 > 0.0 { size } else { (1600.0, 1000.0) };
68        for (k, _) in before.iter().filter(|t| !keys.contains(&t.0)) { self.remove(k, size) }
69        for k in keys.iter().filter(|k| before.iter().all(|t| &t.0 != *k)) { self.add(k, size) }
70        before != self.tiles
71    }
72
73    /// Fits a card keyed `key` in by halving the biggest tile along its longer side.
74    fn add(&mut self, key: &str, size: (f32, f32)) {
75        let area = |t: &Tile| { let r = px(&t.1, size); r.2 * r.3 };
76        let Some(big) = self.tiles.iter().max_by(|a, b| area(a).total_cmp(&area(b))) else {
77            return self.tiles.push((key.to_owned(), [0.0, 0.0, 1.0, 1.0]));
78        };
79        let r = px(&big.1, size);
80        let on = big.0.clone();
81        self.split(key, &on, if r.2 >= r.3 { Zone::Right } else { Zone::Bottom });
82    }
83
84    /// Gives a card keyed `key` the half of card `on`'s tile on the side `zone` says.
85    fn split(&mut self, key: &str, on: &str, zone: Zone) {
86        let Some(i) = self.find(on) else { return };
87        let ((a, first), e) = (halves(zone), &mut self.tiles[i].1);
88        let (mid, mut new) = ((e[a] + e[a + 2]) / 2.0, *e);
89        if first { (new[a + 2], e[a]) = (mid, mid) } else { (new[a], e[a + 2]) = (mid, mid) }
90        self.tiles.push((key.to_owned(), new));
91    }
92
93    /// Takes the card keyed `key` out. Its room goes to the neighbours along the side with the fewest
94    /// of them that all fit within it; when no side has such (a pinwheel), the rest are laid out afresh.
95    fn remove(&mut self, key: &str, size: (f32, f32)) {
96        let Some(i) = self.find(key) else { return };
97        let (_, e) = self.tiles.remove(i);
98        // The neighbours on side (a, far) of `e`, if there are some and they all fit within it.
99        let side = |a: usize, far: bool| {
100            let touch = |t: &[f32; 4]| if far { near(t[a], e[a + 2]) } else { near(t[a + 2], e[a]) };
101            let n: Vec<usize> = (0..self.tiles.len()).filter(|&j| touch(&self.tiles[j].1) && overlap(&self.tiles[j].1, &e, 1 - a)).collect();
102            let fits = n.iter().all(|&j| self.tiles[j].1[1 - a] > e[1 - a] - EPS && self.tiles[j].1[3 - a] < e[3 - a] + EPS);
103            (fits && !n.is_empty()).then_some((a, far, n))
104        };
105        let best = [(0, false), (1, false), (0, true), (1, true)].into_iter().filter_map(|(a, far)| side(a, far)).min_by_key(|s| s.2.len());
106        let Some((a, far, n)) = best else {
107            let keys: Vec<String> = self.tiles.drain(..).map(|t| t.0).collect();
108            return keys.iter().for_each(|k| self.add(k, size));
109        };
110        for j in n { if far { self.tiles[j].1[a] = e[a] } else { self.tiles[j].1[a + 2] = e[a + 2] } }
111    }
112
113    /// The draggable gaps: each between card `a` and card `b` after it along axis `ax`
114    /// (0 side by side, 1 stacked), with the gap's rect, a little wider than the gap to grab it.
115    pub fn gaps(&self, size: (f32, f32)) -> Vec<(String, String, usize, Rect)> {
116        let pad = 3.0;
117        let mut out = Vec::new();
118        for (a, e) in &self.tiles {
119            for (b, f) in &self.tiles {
120                for ax in 0..2 {
121                    if !near(e[ax + 2], f[ax]) || !overlap(e, f, 1 - ax) { continue }
122                    let (r, s) = (px(e, size), px(f, size));
123                    let rect = if ax == 0 {
124                        let (y0, y1) = (r.1.max(s.1), (r.1 + r.3).min(s.1 + s.3));
125                        (r.0 + r.2 - pad, y0, GAP + 2.0 * pad, y1 - y0)
126                    } else {
127                        let (x0, x1) = (r.0.max(s.0), (r.0 + r.2).min(s.0 + s.2));
128                        (x0, r.1 + r.3 - pad, x1 - x0, GAP + 2.0 * pad)
129                    };
130                    out.push((a.clone(), b.clone(), ax, rect));
131                }
132            }
133        }
134        out
135    }
136
137    /// Moves the gap between card `a` and card `b` after it along axis `ax` by `d` points. With it
138    /// move the other cards along that line as far as it runs unbroken from them, up to where
139    /// another gap crosses it, each kept at least `MIN` unless it already was smaller.
140    pub fn slide(&mut self, a: &str, b: &str, ax: usize, d: f32, size: (f32, f32)) {
141        let (Some(i), Some(j)) = (self.find(a), self.find(b)) else { return };
142        let (e, f, c) = (self.tiles[i].1, self.tiles[j].1, 1 - ax);
143        let line = e[ax + 2];
144        // The stretch of the line that must move together: grown until no card on the line straddles its ends.
145        let (mut lo, mut hi) = (e[c].min(f[c]), e[c + 2].max(f[c + 2]));
146        let on = |t: &[f32; 4], lo: f32, hi: f32| (near(t[ax], line) || near(t[ax + 2], line)) && t[c] < hi - EPS && t[c + 2] > lo + EPS;
147        loop {
148            let grown = self.tiles.iter().filter(|t| on(&t.1, lo, hi)).fold((lo, hi), |(l, h), t| (l.min(t.1[c]), h.max(t.1[c + 2])));
149            if grown == (lo, hi) { break }
150            (lo, hi) = grown;
151        }
152        let moving: Vec<usize> = (0..self.tiles.len()).filter(|&k| on(&self.tiles[k].1, lo, hi)).collect();
153        let span = (if ax == 0 { size.0 } else { size.1 }) - GAP;
154        let m = MIN / span;
155        let (mut min, mut max) = (0.0f32, 1.0f32);
156        for t in moving.iter().map(|&k| &self.tiles[k].1) {
157            if near(t[ax + 2], line) { min = min.max(t[ax] + m) } else { max = max.min(t[ax + 2] - m) }
158        }
159        let to = (line + d / span).clamp(min.min(line), max.max(line));
160        for k in moving {
161            let t = &mut self.tiles[k].1;
162            if near(t[ax + 2], line) { t[ax + 2] = to } else { t[ax] = to }
163        }
164    }
165
166    /// What a card keyed `key` dropped at `p` lands on, and where against it: a side of the whole
167    /// canvas (no key) near its edge, else the card under `p`.
168    pub fn target(&self, key: &str, p: (f32, f32), size: (f32, f32)) -> Option<(Option<String>, Zone)> {
169        let others = || self.tiles.iter().filter(|t| t.0 != key);
170        let edges = [(p.0, Zone::Left), (size.0 - p.0, Zone::Right), (p.1, Zone::Top), (size.1 - p.1, Zone::Bottom)];
171        let near = edges.into_iter().filter(|e| e.0 < EDGE).min_by(|a, b| a.0.total_cmp(&b.0));
172        if let Some((_, zone)) = near.filter(|_| others().next().is_some()) { return Some((None, zone)) }
173        let (k, (x, y, w, h)) = others().map(|t| (&t.0, px(&t.1, size))).find(|(_, r)| inside(p, *r))?;
174        let (u, v) = ((p.0 - x) / w, (p.1 - y) / h);
175        let mid = 0.25..0.75;
176        if mid.contains(&u) && mid.contains(&v) { return Some((Some(k.clone()), Zone::Swap)) }
177        let edges = [(u, Zone::Left), (1.0 - u, Zone::Right), (v, Zone::Top), (1.0 - v, Zone::Bottom)];
178        edges.into_iter().min_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, z)| (Some(k.clone()), z))
179    }
180
181    /// Where the card keyed `key` will show once dropped against `target` in `zone`.
182    pub fn hint(&self, key: &str, target: Option<&str>, zone: Zone, size: (f32, f32)) -> Option<Rect> {
183        let mut after = self.clone();
184        after.drop(key, target, zone, size);
185        after.rect(key, size)
186    }
187
188    /// Drops the card keyed `key` against `target` (or the whole canvas): swaps them, or takes
189    /// the half of that tile (or the canvas) on the side `zone` says.
190    pub fn drop(&mut self, key: &str, target: Option<&str>, zone: Zone, size: (f32, f32)) {
191        match (target, zone) {
192            (Some(t), Zone::Swap) => if let (Some(i), Some(j)) = (self.find(key), self.find(t)) { (self.tiles[i].1, self.tiles[j].1) = (self.tiles[j].1, self.tiles[i].1) },
193            (None, Zone::Swap) => {}
194            (Some(t), _) => { self.remove(key, size); self.split(key, t, zone) }
195            (None, _) => {
196                self.remove(key, size);
197                let (a, first) = halves(zone);
198                for (_, e) in &mut self.tiles { for v in [a, a + 2] { e[v] = e[v] / 2.0 + if first { 0.5 } else { 0.0 } } }
199                let mut new = [0.0, 0.0, 1.0, 1.0];
200                new[if first { a + 2 } else { a }] = 0.5;
201                self.tiles.push((key.to_owned(), new));
202            }
203        }
204    }
205}