xonecas.io
8447
Co

conveyor / files

conveyor / templates / library / widgets / canvas.rs

17.0 KB
1//! A free canvas: new widgets land where they were asked for, and a drag on one (outside its
2//! own controls) moves it. Its right edge, bottom edge and corner resize it, and a double
3//! click (or the header's □) maximizes it to the whole canvas. A click on a card brings it to the front. Cards stay inside the canvas
4//! as it resizes. Cards are frosted glass, as the theme sets it: see-through over a blur, with a shadow.
5//! Tiled (the title bar's toggle, shared as "canvas-layout"), cards fill the canvas i3-style with
6//! gaps instead: drag any gap between two cards to resize just those along it, and drag a card onto
7//! another to split just that one (near an edge) or swap with it (the middle), or to the canvas's
8//! edge to take that whole side, with the spot it will take lit up.
9//! Root shows one per project, under the title bar, over the project's background image when the
10//! title bar's button picked one.
11use super::{api::*, look, tiles::Tiles, ui};
12use rune::{Cursor, Drag, El, Image, Phase, Shape, SurfaceFit, Tx, el, text};
13use std::path::PathBuf;
14
15pub const WIDGET: Widget = Widget { title: "Canvas", size: (0.0, 0.0), new: |cx| Box::new(Canvas::load(cx)) };
16
17struct Child {
18    kind: String,
19    key: String,
20    x: f32,
21    y: f32,
22    w: f32,
23    h: f32,
24    /// Fills the canvas, keeping its spot and size for when it's restored.
25    max: bool,
26}
27
28/// The smallest a card resizes to.
29const MIN: (f32, f32) = (200.0, 120.0);
30
31/// What a drag on a card does: move it, or resize it from an edge or the corner.
32#[derive(Clone, Copy, PartialEq)]
33enum Grip { Move, Right, Bottom, Corner }
34
35pub struct Canvas {
36    children: Vec<Child>,
37    file: PathBuf,
38    /// Where the dragged child was (or its size, when resizing) when the drag started.
39    grab: Option<(f32, f32)>,
40    /// The canvas's laid-out size, kept as a "size" file: the app reloads widgets without
41    /// laying out again, so `on_layout` only speaks when the size changes.
42    size: (f32, f32),
43    /// Whether the canvas tiles its cards. Set in `update`.
44    tiled: bool,
45    /// The tiled layout, kept in step with the cards shown, tiled or not.
46    tiles: Tiles,
47    /// When tiled, the card being dragged to another tile, how far it has moved, and where the pointer is.
48    lift: Option<(String, (f32, f32), (f32, f32))>,
49    /// When tiled, the layout as it was when a gap's drag started.
50    held: Option<Tiles>,
51    /// The project's background image, with the path it came from. Set in `update`.
52    bg: Option<(String, Image)>,
53}
54
55/// The shared value that says how canvases lay out their cards: "tile", or anything else for floating.
56pub const LAYOUT: &str = "canvas-layout";
57
58/// Whether canvases tile their cards.
59pub fn tiled(cx: &Cx) -> bool { cx.shared(LAYOUT) == Some("tile") }
60
61/// The shared value that holds `project`'s background image path; empty or unset for none.
62pub fn background(project: &str) -> String { format!("background-{project}") }
63
64impl Canvas {
65    /// children: one line per child, "kind key x y w h max".
66    fn load(cx: &Cx) -> Self {
67        let file = cx.dir.join("children");
68        let children = std::fs::read_to_string(&file).unwrap_or_default().lines().filter_map(|l| {
69            let f: Vec<&str> = l.split(' ').collect();
70            let n = |i: usize| f.get(i)?.parse::<f32>().ok();
71            Some(Child { kind: f.first()?.to_string(), key: f.get(1)?.to_string(), x: n(2)?, y: n(3)?, w: n(4)?, h: n(5)?, max: f.get(6) == Some(&"1") })
72        }).collect();
73        let size = std::fs::read_to_string(cx.dir.join("size")).ok().and_then(|s| {
74            let (w, h) = s.split_once(' ')?;
75            Some((w.parse().ok()?, h.parse().ok()?))
76        }).unwrap_or((0.0, 0.0));
77        let tiles = Tiles::load(&cx.dir.join("layout"));
78        Canvas { children, file, grab: None, size, tiled: false, tiles, lift: None, held: None, bg: None }
79    }
80
81    fn save(&self) {
82        let lines: String = self.children.iter().map(|c| format!("{} {} {} {} {} {} {}\n", c.kind, c.key, c.x, c.y, c.w, c.h, c.max as u8)).collect();
83        let _ = std::fs::write(&self.file, lines);
84    }
85
86    /// Where child `c` shows: its spot, pulled back inside the canvas.
87    fn fit(&self, c: &Child) -> (f32, f32) {
88        if self.size.0 <= 0.0 { return (c.x, c.y) }
89        (c.x.min(self.size.0 - c.w).max(0.0), c.y.min(self.size.1 - c.h).max(0.0))
90    }
91
92    /// Child `c`'s shown rect: the whole canvas when maximized, its tile among `tiles` when tiled,
93    /// else its size at its fitted spot.
94    fn rect(&self, c: &Child, tiles: Option<&Tiles>) -> (f32, f32, f32, f32) {
95        if c.max && self.size.0 > 0.0 { return (0.0, 0.0, self.size.0, self.size.1) }
96        if let Some(r) = tiles.filter(|_| self.size.0 > 0.0).and_then(|t| t.rect(&c.key, self.size)) { return r }
97        let (x, y) = self.fit(c);
98        (x, y, c.w, c.h)
99    }
100
101    /// Maximizes the child keyed `key`, or restores it.
102    pub fn toggle_max(&mut self, key: &str) {
103        if let Some(c) = self.children.iter_mut().find(|c| c.key == key) { c.max = !c.max }
104        self.save();
105    }
106
107    /// Adds a `kind` of size `size` with its top-left at `at`.
108    pub fn add(&mut self, kind: &str, at: (f32, f32), (w, h): (f32, f32)) {
109        let key = (1..).map(|i| format!("{kind}{i}")).find(|k| !self.children.iter().any(|c| &c.key == k)).unwrap();
110        self.add_keyed(kind, key, at, (w, h));
111    }
112
113    fn add_keyed(&mut self, kind: &str, key: String, at: (f32, f32), (w, h): (f32, f32)) {
114        self.children.push(Child { kind: kind.into(), key, x: at.0, y: at.1, w, h, max: false });
115        self.save();
116    }
117
118    /// Adds a `kind` of size `size` near the top left, stepping down and right past anything already there.
119    pub fn add_free(&mut self, kind: &str, size: (f32, f32)) {
120        let mut at = (24.0, 24.0);
121        while self.children.iter().any(|c| (c.x, c.y) == at) { at = (at.0 + 28.0, at.1 + 28.0) }
122        self.add(kind, at, size);
123    }
124
125    /// Takes the child keyed `key` off the canvas.
126    pub fn remove(&mut self, key: &str) {
127        self.children.retain(|c| c.key != key);
128        self.save();
129    }
130
131    /// Brings the card keyed `key` to the front, or adds a `kind` keyed `key` beside the child keyed `beside`.
132    pub fn open_beside(&mut self, kind: &str, key: &str, size: (f32, f32), beside: &str) {
133        if let Some(i) = self.children.iter().position(|c| c.key == key) {
134            self.raise(i);
135            return self.save();
136        }
137        if let Some(at) = self.spot_beside(size, beside) { self.add_keyed(kind, key.into(), at, size) }
138    }
139
140    /// Moves child `i` to the end, drawn over the others; returns its new index.
141    fn raise(&mut self, i: usize) -> usize {
142        let c = self.children.remove(i);
143        self.children.push(c);
144        self.children.len() - 1
145    }
146
147    /// The cards shown: a discarded build's kinds go away, and come back if it's built again.
148    fn shown(&self, cx: &Cx) -> Vec<&Child> {
149        let kinds = cx.kinds();
150        self.children.iter().filter(|c| kinds.iter().any(|(n, _)| *n == c.kind)).collect()
151    }
152
153    /// The tiled layout of the cards shown.
154    fn tiling(&self, cx: &Cx) -> Tiles {
155        let mut tiles = self.tiles.clone();
156        tiles.sync(&self.shown(cx).iter().map(|c| c.key.clone()).collect::<Vec<_>>(), self.size);
157        tiles
158    }
159
160    /// Where a card of `size` goes beside the child keyed `beside`.
161    fn spot_beside(&self, size: (f32, f32), beside: &str) -> Option<(f32, f32)> {
162        let b = self.children.iter().find(|c| c.key == beside)?;
163        let (bx, by) = self.fit(b);
164        let right = bx + b.w + 16.0;
165        let x = if self.size.0 <= 0.0 || right + size.0 <= self.size.0 { right } else { (self.size.0 - size.0).max(0.0) };
166        let mut y = by;
167        while self.children.iter().any(|c| c.x == x && c.y == y) { y += 28.0; }
168        Some((x, y))
169    }
170}
171
172impl View for Canvas {
173    fn update(&mut self, cx: &Cx) {
174        self.tiled = tiled(cx);
175        let keys: Vec<String> = self.shown(cx).iter().map(|c| c.key.clone()).collect();
176        if self.tiles.sync(&keys, self.size) { self.tiles.save() }
177        // Root keys a project's canvas "canvas-<slug>"; the widgets project's is plain "canvas".
178        let project = cx.id.rsplit('.').next().and_then(|k| k.strip_prefix("canvas-")).unwrap_or("widgets");
179        let path = cx.shared(&background(project)).unwrap_or("");
180        if self.bg.as_ref().map(|b| b.0.as_str()) != Some(path) {
181            self.bg = (!path.is_empty()).then(|| (path.to_owned(), cx.images().file(path, 2048.0, 2.0)));
182        }
183    }
184
185    fn view(&self, cx: &Cx) -> El {
186        let t = look::of(cx);
187        let id = cx.id.to_owned();
188        let mut canvas = el().w_full().h_full().fill(t.bg)
189            .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(c) = get::<Canvas>(h, &id) {
190                c.size = (r[2], r[3]);
191                let _ = std::fs::write(c.file.with_file_name("size"), format!("{} {}", r[2], r[3]));
192            });
193        if let Some((_, i)) = &self.bg && i.size().is_some() {
194            canvas = canvas.child(el().key("background").absolute(0.0, 0.0).w_full().h_full().pixels_fit(i.pixels(), SurfaceFit::Fill));
195        }
196        if self.children.is_empty() {
197            canvas = canvas.center().child(text("Ctrl+click anywhere to make a widget").font(t.body).color(t.text_secondary));
198        }
199        // From `cx`, not `self.tiled`: a toggle can render before the next `update`.
200        let tiles = tiled(cx).then(|| self.tiling(cx));
201        let mut shown = self.shown(cx);
202        // Tiles don't overlap, so only a maximized one, or the one being dragged, draws over the rest.
203        let lifted = |c: &Child| self.lift.as_ref().filter(|l| l.0 == c.key).map(|l| l.1);
204        if tiles.is_some() { shown.sort_by_key(|c| (c.max, lifted(c).is_some())) }
205        let any_max = shown.iter().any(|c| c.max);
206        for c in shown {
207            let (x, y, w, h) = self.rect(c, tiles.as_ref());
208            let (x, y) = lifted(c).map_or((x, y), |(dx, dy)| (x + dx, y + dy));
209            let radius = if c.max { 0.0 } else { 10.0 };
210            let grip = |name: &str, g: Grip, cursor: Cursor| el().key(format!("resize-{name}")).cursor(cursor).on_drag(drag(cx.id, c.key.clone(), g));
211            // The shadow sits on the card; the rounded clip on its content, or it would clip the shadow too.
212            let mut card = t.glass(el().key(format!("card-{}", c.key)).w(w).h(h).absolute(x, y).radius(radius))
213                .child(el().w_full().h_full().clip_rounded(radius).padding(12.0).child(cx.child(&c.kind, &c.key)))
214                .on_drag(drag(cx.id, c.key.clone(), Grip::Move));
215            if !c.max && tiles.is_none() {
216                let corner = Shape::new().stroke(vec![[13.0, 5.0], [5.0, 13.0]], 1.5, t.text_secondary).stroke(vec![[13.0, 9.0], [9.0, 13.0]], 1.5, t.text_secondary);
217                card = card.child(grip("right", Grip::Right, Cursor::ResizeColumn).pin(None, Some(0.0), Some(0.0), Some(16.0)).w(6.0))
218                    .child(grip("bottom", Grip::Bottom, Cursor::ResizeRow).pin(Some(0.0), None, Some(16.0), Some(0.0)).h(6.0))
219                    .child(grip("corner", Grip::Corner, Cursor::Crosshair).pin(None, None, Some(0.0), Some(0.0)).w(16.0).h(16.0).shape(corner));
220            }
221            canvas = canvas.child(card);
222        }
223        let Some(tiles) = tiles.filter(|_| !any_max && self.size.0 > 0.0) else { return canvas };
224        // The spot a dragged card will take, lit up over the rest.
225        if let Some((key, _, p)) = &self.lift {
226            let hint = tiles.target(key, *p, self.size).and_then(|(on, zone)| tiles.hint(key, on.as_deref(), zone, self.size));
227            if let Some((x, y, w, h)) = hint {
228                canvas = canvas.child(el().key("drop-hint").absolute(x, y).w(w).h(h).radius(10.0).fill(t.accent.alpha(0.18)).border(2.0, t.accent));
229            }
230            return canvas;
231        }
232        for (a, b, ax, (x, y, w, h)) in tiles.gaps(self.size) {
233            let cursor = if ax == 0 { Cursor::ResizeColumn } else { Cursor::ResizeRow };
234            canvas = canvas.child(el().key(format!("gap-{a}-{b}")).absolute(x, y).w(w).h(h).cursor(cursor).on_drag(gap(cx.id, a, b, ax)));
235        }
236        canvas
237    }
238
239    fn mount(&mut self, kind: &str, at: (f32, f32), cx: &Cx) -> bool {
240        let (w, h) = cx.kinds().iter().find(|(n, _)| *n == kind).map(|(_, w)| w.size).filter(|s| s.0 > 0.0).unwrap_or((320.0, 240.0));
241        self.add(kind, at, (w, h));
242        true
243    }
244}
245
246/// A □ for a card's header that maximizes the card (instance `cx.id`) to its canvas, or restores it.
247pub fn maximize(cx: &Cx) -> El {
248    let id = cx.id.to_owned();
249    ui::icon(&look::of(cx), "maximize", "□", "Maximize or restore", move |h: &mut HostState, _: &mut Tx| {
250        let Some((parent, key)) = id.rsplit_once('.') else { return };
251        if let Some(canvas) = get::<Canvas>(h, parent) { canvas.toggle_max(key) }
252    })
253}
254
255/// A × for a card's header that takes the card (instance `cx.id`) off its canvas.
256pub fn close(cx: &Cx, label: &str) -> El {
257    let id = cx.id.to_owned();
258    ui::icon(&look::of(cx), "close", "×", label, move |h: &mut HostState, _: &mut Tx| {
259        let Some((parent, key)) = id.rsplit_once('.') else { return };
260        if let Some(canvas) = get::<Canvas>(h, parent) { canvas.remove(key) }
261    })
262}
263
264/// A drag for a part of a card (instance `cx.id`) that takes presses itself, such as a header in a
265/// focusable widget: it moves the card as a drag on the card does.
266pub fn mover(cx: &Cx) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
267    let (parent, key) = cx.id.rsplit_once('.').unwrap_or(("", cx.id));
268    drag(parent, key.to_owned(), Grip::Move)
269}
270
271/// A drag on card `key`: a press brings it to the front, a double click maximizes or restores it; otherwise `g` moves or resizes it,
272/// unless it's maximized.
273fn drag(id: &str, key: String, g: Grip) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
274    let id = id.to_owned();
275    move |h: &mut HostState, d: &mut Drag, _: &mut Tx| {
276        let Some(canvas) = get::<Canvas>(h, &id) else { return };
277        let Some(mut i) = canvas.children.iter().position(|c| c.key == key) else { return };
278        if canvas.tiled && !(d.phase == Phase::Down && d.clicks == 2) { return swap(canvas, i, d) }
279        // A press anywhere on a card brings it to the front.
280        if d.phase == Phase::Down { i = canvas.raise(i) }
281        let ((x, y, _, _), size) = (canvas.rect(&canvas.children[i], None), canvas.size);
282        let c = &mut canvas.children[i];
283        // Up to the canvas's far edge, once its size is known.
284        let room = |s: f32, at: f32| if s > 0.0 { s - at } else { f32::INFINITY };
285        let w = |a: f32| (a + d.dx).min(room(size.0, x)).max(MIN.0);
286        let h = |b: f32| (b + d.dy).min(room(size.1, y)).max(MIN.1);
287        match (d.phase, canvas.grab) {
288            (Phase::Down, _) if g == Grip::Move && d.clicks == 2 => { canvas.grab = None; canvas.toggle_max(&key) }
289            _ if c.max => {}
290            (Phase::Down, _) => { (c.x, c.y) = (x, y); canvas.grab = Some(if g == Grip::Move { (x, y) } else { (c.w, c.h) }) }
291            (Phase::Move, Some((a, b))) => match g {
292                Grip::Move => (c.x, c.y) = ((a + d.dx).max(0.0), (b + d.dy).max(0.0)),
293                Grip::Right => c.w = w(a),
294                Grip::Bottom => c.h = h(b),
295                Grip::Corner => (c.w, c.h) = (w(a), h(b)),
296            },
297            (Phase::Up, Some((a, b))) => {
298                if d.cancelled() { if g == Grip::Move { (c.x, c.y) = (a, b) } else { (c.w, c.h) = (a, b) } }
299                canvas.grab = None;
300                canvas.save();
301            }
302            _ => {}
303        }
304    }
305}
306
307/// A drag on tile `i` of a tiled canvas: the card follows the pointer, and dropped on another tile,
308/// splits it or takes its place.
309fn swap(canvas: &mut Canvas, i: usize, d: &Drag) {
310    let c = &canvas.children[i];
311    if c.max { return }
312    let Some((x, y, _, _)) = canvas.tiles.rect(&c.key, canvas.size) else { return };
313    let (key, p) = (c.key.clone(), (x + d.start_x + d.dx, y + d.start_y + d.dy));
314    match d.phase {
315        Phase::Down | Phase::Move => canvas.lift = Some((key, (d.dx, d.dy), p)),
316        Phase::Up => {
317            canvas.lift = None;
318            if d.cancelled() { return }
319            let Some((on, zone)) = canvas.tiles.target(&key, p, canvas.size) else { return };
320            canvas.tiles.drop(&key, on.as_deref(), zone, canvas.size);
321            canvas.tiles.save();
322        }
323    }
324}
325
326/// A drag on the gap between card `a` and card `b` after it along axis `ax`: moves that gap.
327fn gap(id: &str, a: String, b: String, ax: usize) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
328    let id = id.to_owned();
329    move |h: &mut HostState, d: &mut Drag, _: &mut Tx| {
330        let Some(canvas) = get::<Canvas>(h, &id) else { return };
331        if d.phase == Phase::Down { canvas.held = Some(canvas.tiles.clone()) }
332        let Some(mut tiles) = canvas.held.clone() else { return };
333        let moved = if d.cancelled() { 0.0 } else if ax == 0 { d.dx } else { d.dy };
334        tiles.slide(&a, &b, ax, moved, canvas.size);
335        canvas.tiles = tiles;
336        if d.phase == Phase::Up { canvas.held = None; canvas.tiles.save() }
337    }
338}