@@ -1,9 +1,15 @@
11 //! A free canvas: new widgets land where they were asked for, and a drag on one (outside its
22 //! 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. Cards stay inside the canvas
4-//! as it resizes. Root shows one per project, under the title bar.
5-use super::api::*;
6-use rune::{Cursor, Drag, El, Phase, Shape, Tx, el, row, text, tok};
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.
11+use super::{api::*, look, tiles::Tiles, ui};
12+use rune::{Cursor, Drag, El, Image, Phase, Shape, SurfaceFit, Tx, el, text};
713 use std::path::PathBuf;
814
915 pub const WIDGET: Widget = Widget { title: "Canvas", size: (0.0, 0.0), new: |cx| Box::new(Canvas::load(cx)) };
@@ -34,8 +40,27 @@ pub struct Canvas {
3440 /// The canvas's laid-out size, kept as a "size" file: the app reloads widgets without
3541 /// laying out again, so `on_layout` only speaks when the size changes.
3642 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)>,
3753 }
3854
55+/// The shared value that says how canvases lay out their cards: "tile", or anything else for floating.
56+pub const LAYOUT: &str = "canvas-layout";
57+
58+/// Whether canvases tile their cards.
59+pub 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.
62+pub fn background(project: &str) -> String { format!("background-{project}") }
63+
3964 impl Canvas {
4065 /// children: one line per child, "kind key x y w h max".
4166 fn load(cx: &Cx) -> Self {
@@ -49,7 +74,8 @@ impl Canvas {
4974 let (w, h) = s.split_once(' ')?;
5075 Some((w.parse().ok()?, h.parse().ok()?))
5176 }).unwrap_or((0.0, 0.0));
52- Canvas { children, file, grab: None, size }
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 }
5379 }
5480
5581 fn save(&self) {
@@ -63,9 +89,11 @@ impl Canvas {
6389 (c.x.min(self.size.0 - c.w).max(0.0), c.y.min(self.size.1 - c.h).max(0.0))
6490 }
6591
66- /// Child `c`'s shown rect: the whole canvas when maximized, else its size at its fitted spot.
67- fn rect(&self, c: &Child) -> (f32, f32, f32, f32) {
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) {
6895 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 }
6997 let (x, y) = self.fit(c);
7098 (x, y, c.w, c.h)
7199 }
@@ -100,22 +128,35 @@ impl Canvas {
100128 self.save();
101129 }
102130
103- /// Adds a `kind` beside the child keyed `beside`: to its right if it fits, else against the
104- /// canvas's right edge, stepping down past anything already there.
105- pub fn add_beside(&mut self, kind: &str, size: (f32, f32), beside: &str) {
106- if let Some(at) = self.spot_beside(size, beside) { self.add(kind, at, size) }
107- }
108-
109131 /// Brings the card keyed `key` to the front, or adds a `kind` keyed `key` beside the child keyed `beside`.
110132 pub fn open_beside(&mut self, kind: &str, key: &str, size: (f32, f32), beside: &str) {
111133 if let Some(i) = self.children.iter().position(|c| c.key == key) {
112- let c = self.children.remove(i);
113- self.children.push(c);
134+ self.raise(i);
114135 return self.save();
115136 }
116137 if let Some(at) = self.spot_beside(size, beside) { self.add_keyed(kind, key.into(), at, size) }
117138 }
118139
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+
119160 /// Where a card of `size` goes beside the child keyed `beside`.
120161 fn spot_beside(&self, size: (f32, f32), beside: &str) -> Option<(f32, f32)> {
121162 let b = self.children.iter().find(|c| c.key == beside)?;
@@ -129,26 +170,49 @@ impl Canvas {
129170 }
130171
131172 impl 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+
132185 fn view(&self, cx: &Cx) -> El {
133- let t = tok::theme(true);
186+ let t = look::of(cx);
134187 let id = cx.id.to_owned();
135188 let mut canvas = el().w_full().h_full().fill(t.bg)
136189 .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(c) = get::<Canvas>(h, &id) {
137190 c.size = (r[2], r[3]);
138191 let _ = std::fs::write(c.file.with_file_name("size"), format!("{} {}", r[2], r[3]));
139192 });
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+ }
140196 if self.children.is_empty() {
141- canvas = canvas.center().child(text("Ctrl+click anywhere to make a widget").color(t.text_secondary));
197+ canvas = canvas.center().child(text("Ctrl+click anywhere to make a widget").font(t.body).color(t.text_secondary));
142198 }
143- // A discarded build's kinds go away, and come back if it's built again.
144- for c in self.children.iter().filter(|c| cx.kinds().iter().any(|(n, _)| *n == c.kind)) {
145- let (x, y, w, h) = self.rect(c);
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));
146209 let radius = if c.max { 0.0 } else { 10.0 };
147210 let grip = |name: &str, g: Grip, cursor: Cursor| el().key(format!("resize-{name}")).cursor(cursor).on_drag(drag(cx.id, c.key.clone(), g));
148- let mut card = el().key(format!("card-{}", c.key)).w(w).h(h).absolute(x, y).radius(radius).clip_rounded(radius).fill(t.card).padding(12.0)
149- .child(cx.child(&c.kind, &c.key))
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)))
150214 .on_drag(drag(cx.id, c.key.clone(), Grip::Move));
151- if !c.max {
215+ if !c.max && tiles.is_none() {
152216 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);
153217 card = card.child(grip("right", Grip::Right, Cursor::ResizeColumn).pin(None, Some(0.0), Some(0.0), Some(16.0)).w(6.0))
154218 .child(grip("bottom", Grip::Bottom, Cursor::ResizeRow).pin(Some(0.0), None, Some(16.0), Some(0.0)).h(6.0))
@@ -156,6 +220,19 @@ impl View for Canvas {
156220 }
157221 canvas = canvas.child(card);
158222 }
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+ }
159236 canvas
160237 }
161238
@@ -168,36 +245,40 @@ impl View for Canvas {
168245
169246 /// A □ for a card's header that maximizes the card (instance `cx.id`) to its canvas, or restores it.
170247 pub fn maximize(cx: &Cx) -> El {
171- let t = tok::theme(true);
172248 let id = cx.id.to_owned();
173- row().key("maximize").w(24.0).h(24.0).center().radius(6.0).role("button").label("Maximize").help("Maximize or restore").hover(t.press)
174- .child(text("□").font(tok::type_::LABEL).color(t.text_secondary))
175- .on_press_tx(move |h: &mut HostState, _: &mut Tx| {
176- let Some((parent, key)) = id.rsplit_once('.') else { return };
177- if let Some(canvas) = get::<Canvas>(h, parent) { canvas.toggle_max(key) }
178- })
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+ })
179253 }
180254
181255 /// A × for a card's header that takes the card (instance `cx.id`) off its canvas.
182256 pub fn close(cx: &Cx, label: &str) -> El {
183- let t = tok::theme(true);
184257 let id = cx.id.to_owned();
185- row().key("close").w(24.0).h(24.0).center().radius(6.0).role("button").label(label).help("Close").hover(t.press)
186- .child(text("×").font(tok::type_::BODY).color(t.text_secondary))
187- .on_press_tx(move |h: &mut HostState, _: &mut Tx| {
188- let Some((parent, key)) = id.rsplit_once('.') else { return };
189- if let Some(canvas) = get::<Canvas>(h, parent) { canvas.remove(key) }
190- })
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.
266+pub 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)
191269 }
192270
193-/// A drag on card `key`: a double click maximizes or restores it; otherwise `g` moves or resizes it,
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,
194272 /// unless it's maximized.
195273 fn drag(id: &str, key: String, g: Grip) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
196274 let id = id.to_owned();
197275 move |h: &mut HostState, d: &mut Drag, _: &mut Tx| {
198276 let Some(canvas) = get::<Canvas>(h, &id) else { return };
199- let Some(i) = canvas.children.iter().position(|c| c.key == key) else { return };
200- let ((x, y, _, _), size) = (canvas.rect(&canvas.children[i]), canvas.size);
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);
201282 let c = &mut canvas.children[i];
202283 // Up to the canvas's far edge, once its size is known.
203284 let room = |s: f32, at: f32| if s > 0.0 { s - at } else { f32::INFINITY };
@@ -222,3 +303,36 @@ fn drag(id: &str, key: String, g: Grip) -> impl Fn(&mut HostState, &mut Drag, &m
222303 }
223304 }
224305 }
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.
309+fn 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.
327+fn 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+}