@@ -1,7 +1,9 @@
11 //! A free canvas: new widgets land where they were asked for, and a drag on one (outside its
2-//! own controls) moves it. Root puts it under the title bar.
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. Cards stay inside the canvas
4+//! as it resizes. Root shows one per project, under the title bar.
35 use super::api::*;
4-use rune::{Drag, El, Phase, Tx, el, text, tok};
6+use rune::{Cursor, Drag, El, Phase, Shape, Tx, el, row, text, tok};
57 use std::path::PathBuf;
68
79 pub const WIDGET: Widget = Widget { title: "Canvas", size: (0.0, 0.0), new: |cx| Box::new(Canvas::load(cx)) };
@@ -13,67 +15,211 @@ struct Child {
1315 y: f32,
1416 w: f32,
1517 h: f32,
18+ /// Fills the canvas, keeping its spot and size for when it's restored.
19+ max: bool,
1620 }
1721
22+/// The smallest a card resizes to.
23+const MIN: (f32, f32) = (200.0, 120.0);
24+
25+/// What a drag on a card does: move it, or resize it from an edge or the corner.
26+#[derive(Clone, Copy, PartialEq)]
27+enum Grip { Move, Right, Bottom, Corner }
28+
1829 pub struct Canvas {
1930 children: Vec<Child>,
2031 file: PathBuf,
21- /// Where the dragged child was when the drag started.
32+ /// Where the dragged child was (or its size, when resizing) when the drag started.
2233 grab: Option<(f32, f32)>,
34+ /// The canvas's laid-out size, kept as a "size" file: the app reloads widgets without
35+ /// laying out again, so `on_layout` only speaks when the size changes.
36+ size: (f32, f32),
37+ /// The taskbar's Library toggle hid this desktop's library cards; kept as a "library-hidden" file.
38+ library_hidden: bool,
2339 }
2440
2541 impl Canvas {
26- /// children: one line per child, "kind key x y w h".
42+ /// children: one line per child, "kind key x y w h max".
2743 fn load(cx: &Cx) -> Self {
2844 let file = cx.dir.join("children");
2945 let children = std::fs::read_to_string(&file).unwrap_or_default().lines().filter_map(|l| {
3046 let f: Vec<&str> = l.split(' ').collect();
3147 let n = |i: usize| f.get(i)?.parse::<f32>().ok();
32- 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)? })
48+ 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") })
3349 }).collect();
34- Canvas { children, file, grab: None }
50+ let library_hidden = cx.dir.join("library-hidden").exists();
51+ let size = std::fs::read_to_string(cx.dir.join("size")).ok().and_then(|s| {
52+ let (w, h) = s.split_once(' ')?;
53+ Some((w.parse().ok()?, h.parse().ok()?))
54+ }).unwrap_or((0.0, 0.0));
55+ Canvas { children, file, grab: None, size, library_hidden }
3556 }
3657
3758 fn save(&self) {
38- let lines: String = self.children.iter().map(|c| format!("{} {} {} {} {} {}\n", c.kind, c.key, c.x, c.y, c.w, c.h)).collect();
59+ 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();
3960 let _ = std::fs::write(&self.file, lines);
4061 }
62+
63+ /// Where child `c` shows: its spot, pulled back inside the canvas.
64+ fn fit(&self, c: &Child) -> (f32, f32) {
65+ if self.size.0 <= 0.0 { return (c.x, c.y) }
66+ (c.x.min(self.size.0 - c.w).max(0.0), c.y.min(self.size.1 - c.h).max(0.0))
67+ }
68+
69+ /// Child `c`'s shown rect: the whole canvas when maximized, else its size at its fitted spot.
70+ fn rect(&self, c: &Child) -> (f32, f32, f32, f32) {
71+ if c.max && self.size.0 > 0.0 { return (0.0, 0.0, self.size.0, self.size.1) }
72+ let (x, y) = self.fit(c);
73+ (x, y, c.w, c.h)
74+ }
75+
76+ /// Maximizes the child keyed `key`, or restores it.
77+ pub fn toggle_max(&mut self, key: &str) {
78+ if let Some(c) = self.children.iter_mut().find(|c| c.key == key) { c.max = !c.max }
79+ self.save();
80+ }
81+
82+ /// Adds a `kind` of size `size` with its top-left at `at`.
83+ pub fn add(&mut self, kind: &str, at: (f32, f32), (w, h): (f32, f32)) {
84+ let key = (1..).map(|i| format!("{kind}{i}")).find(|k| !self.children.iter().any(|c| &c.key == k)).unwrap();
85+ self.children.push(Child { kind: kind.into(), key, x: at.0, y: at.1, w, h, max: false });
86+ self.save();
87+ }
88+
89+ /// Whether a `kind` is on the canvas.
90+ pub fn has(&self, kind: &str) -> bool {
91+ self.children.iter().any(|c| c.kind == kind)
92+ }
93+
94+ /// Whether a library card shows here.
95+ pub fn library_shown(&self) -> bool {
96+ !self.library_hidden && self.has("library")
97+ }
98+
99+ /// Hides or shows this desktop's library cards, putting one in the top-left if showing and there's none.
100+ pub fn toggle_library(&mut self) {
101+ let shown = self.library_shown();
102+ if !shown && !self.has("library") { self.add("library", (24.0, 24.0), super::library::WIDGET.size) }
103+ self.library_hidden = shown;
104+ let flag = self.file.with_file_name("library-hidden");
105+ let _ = if shown { std::fs::write(flag, "") } else { std::fs::remove_file(flag) };
106+ }
107+
108+ /// Takes the child keyed `key` off the canvas.
109+ pub fn remove(&mut self, key: &str) {
110+ self.children.retain(|c| c.key != key);
111+ self.save();
112+ }
113+
114+ /// Adds a `kind` beside the child keyed `beside`: to its right if it fits, else to its left,
115+ /// stepping down past anything already there.
116+ pub fn add_beside(&mut self, kind: &str, size: (f32, f32), beside: &str) {
117+ let Some(b) = self.children.iter().find(|c| c.key == beside) else { return };
118+ let (bx, by) = self.fit(b);
119+ let right = bx + b.w + 16.0;
120+ let x = if self.size.0 <= 0.0 || right + size.0 <= self.size.0 { right } else { (bx - 16.0 - size.0).max(0.0) };
121+ let mut y = by;
122+ while self.children.iter().any(|c| c.x == x && c.y == y) { y += 28.0; }
123+ self.add(kind, (x, y), size);
124+ }
41125 }
42126
43127 impl View for Canvas {
44128 fn view(&self, cx: &Cx) -> El {
45129 let t = tok::theme(true);
46- let mut canvas = el().w_full().h_full().fill(t.bg);
130+ let id = cx.id.to_owned();
131+ let mut canvas = el().w_full().h_full().fill(t.bg)
132+ .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(c) = get::<Canvas>(h, &id) {
133+ c.size = (r[2], r[3]);
134+ let _ = std::fs::write(c.file.with_file_name("size"), format!("{} {}", r[2], r[3]));
135+ });
47136 if self.children.is_empty() {
48137 canvas = canvas.center().child(text("Ctrl+click anywhere to make a widget").color(t.text_secondary));
49138 }
50- for c in &self.children {
51- canvas = canvas.child(el().key(format!("card-{}", c.key)).w(c.w).h(c.h).absolute(c.x, c.y).radius(10.0).fill(t.card).padding(12.0)
139+ // A discarded build's kinds go away, and come back if it's built again.
140+ // The taskbar's Library toggle hides library cards.
141+ let hidden = |c: &&Child| c.kind == "library" && self.library_hidden;
142+ for c in self.children.iter().filter(|c| cx.kinds().iter().any(|(n, _)| *n == c.kind)).filter(|c| !hidden(c)) {
143+ let (x, y, w, h) = self.rect(c);
144+ let radius = if c.max { 0.0 } else { 10.0 };
145+ let grip = |name: &str, g: Grip, cursor: Cursor| el().key(format!("resize-{name}")).cursor(cursor).on_drag(drag(cx.id, c.key.clone(), g));
146+ 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)
52147 .child(cx.child(&c.kind, &c.key))
53- .on_drag(drag(cx.id, c.key.clone())));
148+ .on_drag(drag(cx.id, c.key.clone(), Grip::Move));
149+ if !c.max {
150+ 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);
151+ card = card.child(grip("right", Grip::Right, Cursor::ResizeColumn).pin(None, Some(0.0), Some(0.0), Some(16.0)).w(6.0))
152+ .child(grip("bottom", Grip::Bottom, Cursor::ResizeRow).pin(Some(0.0), None, Some(16.0), Some(0.0)).h(6.0))
153+ .child(grip("corner", Grip::Corner, Cursor::Crosshair).pin(None, None, Some(0.0), Some(0.0)).w(16.0).h(16.0).shape(corner));
154+ }
155+ canvas = canvas.child(card);
54156 }
55157 canvas
56158 }
57159
160+ /// The shown desktop tells the taskbar's Library toggle, through the shared "library", whether its library shows.
161+ fn update(&mut self, cx: &Cx) {
162+ let active = cx.id.rsplit_once('.').is_some_and(|(_, k)| k == super::root::desktop(cx));
163+ let v = if self.library_shown() { "shown" } else { "hidden" };
164+ if active && cx.shared("library") != Some(v) { cx.act(move |l| l.share("library", v)) }
165+ }
166+
58167 fn mount(&mut self, kind: &str, at: (f32, f32), cx: &Cx) -> bool {
59168 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));
60- let key = (1..).map(|i| format!("{kind}{i}")).find(|k| !self.children.iter().any(|c| &c.key == k)).unwrap();
61- self.children.push(Child { kind: kind.into(), key, x: at.0, y: at.1, w, h });
62- self.save();
169+ self.add(kind, at, (w, h));
63170 true
64171 }
65172 }
66173
67-fn drag(id: &str, key: String) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
174+/// A □ for a card's header that maximizes the card (instance `cx.id`) to its canvas, or restores it.
175+pub fn maximize(cx: &Cx) -> El {
176+ let t = tok::theme(true);
177+ let id = cx.id.to_owned();
178+ row().key("maximize").w(24.0).h(24.0).center().radius(6.0).role("button").label("Maximize").help("Maximize or restore").hover(t.press)
179+ .child(text("□").font(tok::type_::LABEL).color(t.text_secondary))
180+ .on_press_tx(move |h: &mut HostState, _: &mut Tx| {
181+ let Some((parent, key)) = id.rsplit_once('.') else { return };
182+ if let Some(canvas) = get::<Canvas>(h, parent) { canvas.toggle_max(key) }
183+ })
184+}
185+
186+/// A × for a card's header that takes the card (instance `cx.id`) off its canvas.
187+pub fn close(cx: &Cx, label: &str) -> El {
188+ let t = tok::theme(true);
189+ let id = cx.id.to_owned();
190+ row().key("close").w(24.0).h(24.0).center().radius(6.0).role("button").label(label).help("Close").hover(t.press)
191+ .child(text("×").font(tok::type_::BODY).color(t.text_secondary))
192+ .on_press_tx(move |h: &mut HostState, _: &mut Tx| {
193+ let Some((parent, key)) = id.rsplit_once('.') else { return };
194+ if let Some(canvas) = get::<Canvas>(h, parent) { canvas.remove(key) }
195+ })
196+}
197+
198+/// A drag on card `key`: a double click maximizes or restores it; otherwise `g` moves or resizes it,
199+/// unless it's maximized.
200+fn drag(id: &str, key: String, g: Grip) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
68201 let id = id.to_owned();
69202 move |h: &mut HostState, d: &mut Drag, _: &mut Tx| {
70203 let Some(canvas) = get::<Canvas>(h, &id) else { return };
71- let Some(c) = canvas.children.iter_mut().find(|c| c.key == key) else { return };
204+ let Some(i) = canvas.children.iter().position(|c| c.key == key) else { return };
205+ let ((x, y, _, _), size) = (canvas.rect(&canvas.children[i]), canvas.size);
206+ let c = &mut canvas.children[i];
207+ // Up to the canvas's far edge, once its size is known.
208+ let room = |s: f32, at: f32| if s > 0.0 { s - at } else { f32::INFINITY };
209+ let w = |a: f32| (a + d.dx).min(room(size.0, x)).max(MIN.0);
210+ let h = |b: f32| (b + d.dy).min(room(size.1, y)).max(MIN.1);
72211 match (d.phase, canvas.grab) {
73- (Phase::Down, _) => canvas.grab = Some((c.x, c.y)),
74- (Phase::Move, Some((x, y))) => (c.x, c.y) = ((x + d.dx).max(0.0), (y + d.dy).max(0.0)),
75- (Phase::Up, Some((x, y))) => {
76- if d.cancelled() { (c.x, c.y) = (x, y) }
212+ (Phase::Down, _) if g == Grip::Move && d.clicks == 2 => { canvas.grab = None; canvas.toggle_max(&key) }
213+ _ if c.max => {}
214+ (Phase::Down, _) => { (c.x, c.y) = (x, y); canvas.grab = Some(if g == Grip::Move { (x, y) } else { (c.w, c.h) }) }
215+ (Phase::Move, Some((a, b))) => match g {
216+ Grip::Move => (c.x, c.y) = ((a + d.dx).max(0.0), (b + d.dy).max(0.0)),
217+ Grip::Right => c.w = w(a),
218+ Grip::Bottom => c.h = h(b),
219+ Grip::Corner => (c.w, c.h) = (w(a), h(b)),
220+ },
221+ (Phase::Up, Some((a, b))) => {
222+ if d.cancelled() { if g == Grip::Move { (c.x, c.y) = (a, b) } else { (c.w, c.h) = (a, b) } }
77223 canvas.grab = None;
78224 canvas.save();
79225 }