@@ -1,8 +1,8 @@
11 //! The contract between this library and conveyor. Conveyor owns this file and replaces it
22 //! when it changes. Everything in widgets/ is the library's, starting with root.rs: the app
33 //! draws `root` and nothing else, so the whole UI is widgets.
4-use rune::{El, TextEdit, Tx, col, text, tok};
5-use std::{any::Any, cell::{Cell, RefCell}, collections::{BTreeMap, HashMap}, path::{Path, PathBuf}};
4+use rune::{El, TextEdit, Tx, col};
5+use std::{any::Any, cell::{Cell, RefCell}, collections::{BTreeMap, BTreeSet, HashMap}, path::{Path, PathBuf}};
66
77 // ── What widgets read: conveyor's state ─────────────────────────────────────────────────────
88
@@ -77,9 +77,9 @@ pub trait View: Any {
7777 fn event(&mut self, _event: &Event, _cx: &Cx) -> bool {
7878 false
7979 }
80- /// The user Ctrl+clicked inside this widget at `at` (its own points) and asked for
81- /// something that became a new widget `kind`. Keep it as a child and return true, or
82- /// return false and root gets it.
80+ /// A build asked (`conveyor place <kind> --in <this instance>`) to have the new widget
81+ /// `kind` placed here, at `at` in this widget's points: where the user Ctrl+clicked, when
82+ /// that was inside it. Keep it as a child and return true.
8383 fn mount(&mut self, _kind: &str, _at: (f32, f32), _cx: &Cx) -> bool {
8484 false
8585 }
@@ -128,6 +128,20 @@ impl Cx<'_> {
128128 pub fn kinds(&self) -> &'static [(&'static str, &'static Widget)] {
129129 super::ALL
130130 }
131+
132+ /// Acts on the app from anywhere a widget runs (view, update, event), not only handlers:
133+ /// `cx.act(move |l| l.share("note", &path))`. From update and event it runs right after
134+ /// them; from view, at the next update.
135+ pub fn act(&self, f: impl FnOnce(&mut Live) + 'static) {
136+ self.live.later.borrow_mut().push(Box::new(f));
137+ }
138+
139+ /// Call it from `update` while this instance has work that must go on when nothing shows
140+ /// it, such as music playing: the app brings it back after a restart (every library change
141+ /// restarts the app), even when no parent renders it. Stop calling it when the work stops.
142+ pub fn keep_running(&self) {
143+ self.live.running.borrow_mut().insert(self.id.to_owned());
144+ }
131145 }
132146
133147 // ── Handlers: reaching state and conveyor from a press, a key, an edit ──────────────────────
@@ -164,48 +178,37 @@ pub fn edit<W: View>(id: &str, f: impl Fn(&mut W) -> &mut TextEdit + 'static) ->
164178
165179 /// Sets a shared value; every widget sees it on its next render. Kept across restarts.
166180 pub fn share(h: &mut HostState, key: &str, value: &str) {
167- let live = Host::live(h);
168- live.shared.insert(key.to_owned(), value.to_owned());
169- live.dirty = true;
181+ Host::live(h).share(key, value)
170182 }
171183
172-/// Sends one request to conveyord, as `conveyor call` does. The ops are in conveyor's
173-/// server.rs: ticket (create), set (move a ticket to a state), state. Results show up in
174-/// `cx.data` within a second.
184+/// Sends one request to conveyord. The ops are in conveyor's server.rs.
175185 pub fn call(h: &mut HostState, request: String) {
176- Host::live(h).outbox.push(request);
186+ Host::live(h).call(request)
177187 }
178188
179-/// Moves a ticket: `set_state(h, "conveyor", 3, "review")`.
180-/// Shown at once: `cx.data` changes now, and conveyor's next snapshot confirms it.
181-/// Conveyor refuses moves into or out of running.
189+/// Moves a ticket: `set_state(h, "conveyor", 3, "review")`. See `Live::set_state`.
182190 pub fn set_state(h: &mut HostState, project: &str, id: u32, state: &str) {
183- let live = Host::live(h);
184- if let Some(t) = live.data.tickets.iter_mut().find(|t| t.project == project && t.id == id && t.state != "running") {
185- (t.state, t.since) = (state.to_owned(), now() as u64);
186- }
187- call(h, format!("{{\"op\":\"set\",\"project\":{},\"id\":{id},\"state\":{}}}", quote(project), quote(state)));
191+ Host::live(h).set_state(project, id, state)
188192 }
189193
190-/// Writes a ticket: `new_ticket(h, "conveyor", "Title", "What and why", "draft", &[])`.
191-/// `files` are copied into the ticket, and the agent working it gets them.
192-/// `ready` starts an agent on it as soon as a slot is free.
194+/// Writes a ticket: `new_ticket(h, "conveyor", "Title", "What and why", "draft", &[])`. See `Live::new_ticket`.
193195 pub fn new_ticket(h: &mut HostState, project: &str, title: &str, body: &str, state: &str, files: &[PathBuf]) {
194- let files: Vec<String> = files.iter().map(|f| quote(&f.to_string_lossy())).collect();
195- call(h, format!("{{\"op\":\"ticket\",\"project\":{},\"title\":{},\"body\":{},\"state\":{},\"files\":[{}]}}",
196- quote(project), quote(title), quote(body), quote(state), files.join(",")));
196+ Host::live(h).new_ticket(project, title, body, state, files)
197+}
198+
199+/// Rewrites a ticket's title and body. See `Live::edit_ticket`.
200+pub fn edit_ticket(h: &mut HostState, project: &str, id: u32, title: &str, body: &str) {
201+ Host::live(h).edit_ticket(project, id, title, body)
197202 }
198203
199-/// Adds a project: `slug` names it, `path` is its folder, made (with an empty git repo) if missing.
200-/// Pick a folder with `tx.open_folder(...)` (Rune's portal dialog).
204+/// Adds a project. See `Live::add_project`.
201205 pub fn add_project(h: &mut HostState, slug: &str, path: &Path) {
202- call(h, format!("{{\"op\":\"project\",\"slug\":{},\"path\":{}}}", quote(slug), quote(&path.to_string_lossy())));
206+ Host::live(h).add_project(slug, path)
203207 }
204208
205209 /// How many of a project's tickets run at once. 0 pauses it.
206210 pub fn set_slots(h: &mut HostState, project: &str, slots: u32) {
207- if let Some(p) = Host::live(h).data.projects.iter_mut().find(|p| p.slug == project) { p.slots = slots; }
208- call(h, format!("{{\"op\":\"project\",\"slug\":{},\"slots\":{slots}}}", quote(project)));
211+ Host::live(h).set_slots(project, slots)
209212 }
210213
211214 /// A JSON string literal.
@@ -237,6 +240,65 @@ pub struct Live {
237240 outbox: Vec<String>,
238241 spare: TextEdit,
239242 dirty: bool,
243+ /// What widgets asked to do with `cx.act`, run after each update, event and render.
244+ later: RefCell<Vec<Box<dyn FnOnce(&mut Live)>>>,
245+ /// Instances that called `cx.keep_running` in the last update, and the set last saved.
246+ running: RefCell<BTreeSet<String>>,
247+ kept: BTreeSet<String>,
248+}
249+
250+// ── What widgets can do: from handlers with the free functions above, from anywhere with `cx.act`
251+
252+impl Live {
253+ /// Sets a shared value; every widget sees it on its next render. Kept across restarts.
254+ pub fn share(&mut self, key: &str, value: &str) {
255+ self.shared.insert(key.to_owned(), value.to_owned());
256+ self.dirty = true;
257+ }
258+
259+ /// Sends one request to conveyord, as `conveyor call` does. The ops are in conveyor's
260+ /// server.rs. Results show up in `cx.data` within a second.
261+ pub fn call(&mut self, request: String) {
262+ self.outbox.push(request);
263+ }
264+
265+ /// Moves a ticket. Shown at once: `cx.data` changes now, and conveyor's next snapshot
266+ /// confirms it. Conveyor refuses moves into or out of running.
267+ pub fn set_state(&mut self, project: &str, id: u32, state: &str) {
268+ if let Some(t) = self.data.tickets.iter_mut().find(|t| t.project == project && t.id == id && t.state != "running") {
269+ (t.state, t.since) = (state.to_owned(), now() as u64);
270+ }
271+ self.call(format!("{{\"op\":\"set\",\"project\":{},\"id\":{id},\"state\":{}}}", quote(project), quote(state)));
272+ }
273+
274+ /// Writes a ticket. `files` are copied into it, and the agent working it gets them.
275+ /// `ready` starts an agent on it as soon as a slot is free.
276+ pub fn new_ticket(&mut self, project: &str, title: &str, body: &str, state: &str, files: &[PathBuf]) {
277+ let files: Vec<String> = files.iter().map(|f| quote(&f.to_string_lossy())).collect();
278+ self.call(format!("{{\"op\":\"ticket\",\"project\":{},\"title\":{},\"body\":{},\"state\":{},\"files\":[{}]}}",
279+ quote(project), quote(title), quote(body), quote(state), files.join(",")));
280+ }
281+
282+ /// Rewrites a ticket's title and body, in place. Shown at once. Conveyor refuses it while
283+ /// the ticket is running.
284+ pub fn edit_ticket(&mut self, project: &str, id: u32, title: &str, body: &str) {
285+ if let Some(t) = self.data.tickets.iter_mut().find(|t| t.project == project && t.id == id && t.state != "running") {
286+ (t.title, t.body) = (title.to_owned(), body.to_owned());
287+ }
288+ self.call(format!("{{\"op\":\"edit\",\"project\":{},\"id\":{id},\"title\":{},\"body\":{}}}", quote(project), quote(title), quote(body)));
289+ }
290+
291+ /// Adds a project: `slug` names it, `path` is its folder: a git repo, or a new or empty
292+ /// folder that becomes one. Pick a folder with `tx.open_folder(...)`.
293+ pub fn add_project(&mut self, slug: &str, path: &Path) {
294+ self.call(format!("{{\"op\":\"project\",\"slug\":{},\"path\":{}}}", quote(slug), quote(&path.to_string_lossy())));
295+ }
296+
297+ /// How many of a project's tickets run at once. 0 pauses it. Shown at once.
298+ pub fn set_slots(&mut self, project: &str, slots: u32) {
299+ if let Some(p) = self.data.projects.iter_mut().find(|p| p.slug == project) { p.slots = slots; }
300+ self.call(format!("{{\"op\":\"project\",\"slug\":{},\"slots\":{slots}}}", quote(project)));
301+ }
240302 }
241303
242304 impl Live {
@@ -245,8 +307,12 @@ impl Live {
245307 let shared = std::fs::read_to_string(base.join("shared.tsv")).unwrap_or_default().lines()
246308 .filter_map(|l| l.split_once('\t').map(|(k, v)| (k.to_owned(), v.replace("\\n", "\n"))))
247309 .collect();
248- Live { data: Data::default(), base, instances: HashMap::new(), shared, wanted: RefCell::new(vec![]),
249- animate: Cell::new(false), outbox: vec![], spare: TextEdit::new(""), dirty: false }
310+ // Instances that were keeping work going come back now, shown or not.
311+ let wanted: Vec<(String, String)> = std::fs::read_to_string(base.join("running.tsv")).unwrap_or_default().lines()
312+ .filter_map(|l| l.split_once('\t').map(|(id, kind)| (id.to_owned(), kind.to_owned()))).collect();
313+ Live { data: Data::default(), base, instances: HashMap::new(), shared, wanted: RefCell::new(wanted),
314+ animate: Cell::new(false), outbox: vec![], spare: TextEdit::new(""), dirty: false,
315+ later: RefCell::new(vec![]), running: RefCell::new(BTreeSet::new()), kept: BTreeSet::new() }
250316 }
251317
252318 fn cx<'a>(&'a self, id: &'a str, now: f64) -> Cx<'a> {
@@ -257,12 +323,11 @@ impl Live {
257323 pub fn render(&self, kind: &str, id: &str) -> El {
258324 match self.instances.get(id) {
259325 Some((k, w)) if k == kind => w.view(&self.cx(id, now())).key(format!("w:{id}")),
326+ // Made before the next render. A kind the library doesn't have (a discarded build's)
327+ // draws nothing.
260328 _ => {
261329 self.wanted.borrow_mut().push((id.to_owned(), kind.to_owned()));
262- let missing = !super::ALL.iter().any(|(n, _)| *n == kind);
263- let t = tok::theme(true);
264- col().key(format!("w:{id}")).w_full().h_full().center()
265- .child(text(if missing { format!("no widget `{kind}`") } else { String::new() }).color(t.text_secondary))
330+ col().key(format!("w:{id}")).w_full().h_full()
266331 }
267332 }
268333 }
@@ -283,13 +348,9 @@ impl Live {
283348 made
284349 }
285350
286- /// Offers a new widget to each instance in turn, at its own point: the one clicked first,
287- /// then its parents. The id of the one that kept it. A kind with no size of its own (a
288- /// layout, which only fills its parent) is never placed.
289- pub fn mount(&mut self, targets: &[(String, (f32, f32))], kind: &str) -> Option<String> {
290- let (w, h) = super::ALL.iter().find(|(n, _)| *n == kind)?.1.size;
291- if w == 0.0 || h == 0.0 { return None; }
292- targets.iter().find(|(id, at)| self.with(id, |w, cx| w.mount(kind, *at, cx)) == Some(true)).map(|(id, _)| id.clone())
351+ /// Offers new widget `kind` to instance `id`, at `at` in its points. Whether it kept it.
352+ pub fn mount(&mut self, id: &str, at: (f32, f32), kind: &str) -> bool {
353+ super::ALL.iter().any(|(n, _)| *n == kind) && self.with(id, |w, cx| w.mount(kind, at, cx)) == Some(true)
293354 }
294355
295356 /// Instances of `kind`, or any instance if `kind` is empty.
@@ -297,16 +358,34 @@ impl Live {
297358 self.instances.iter().filter(|(_, (k, _))| kind.is_empty() || k == kind).map(|(id, _)| id.clone()).collect()
298359 }
299360
300- /// Runs `update` on every instance.
301- pub fn update(&mut self) {
361+ /// Runs `update` on every instance, then what they asked with `cx.act`. Saves which
362+ /// instances keep work running, so a restart brings them back. True if anything acted.
363+ pub fn update(&mut self) -> bool {
364+ self.running.get_mut().clear();
302365 for id in self.ids("") { self.with(&id, |w, cx| w.update(cx)); }
366+ if *self.running.get_mut() != self.kept {
367+ self.kept = self.running.get_mut().clone();
368+ let lines: String = self.kept.iter().filter_map(|id| Some(format!("{id}\t{}\n", self.kind(id)?))).collect();
369+ let _ = std::fs::write(self.base.join("running.tsv"), lines);
370+ }
371+ self.apply()
303372 }
304373
305374 /// Offers an event to every instance, innermost first. True when one took it.
306375 pub fn event(&mut self, event: &Event) -> bool {
307376 let mut ids = self.ids("");
308377 ids.sort_by_key(|id| std::cmp::Reverse(id.matches('.').count()));
309- ids.iter().any(|id| self.with(id, |w, cx| w.event(event, cx)).unwrap_or(false))
378+ let took = ids.iter().any(|id| self.with(id, |w, cx| w.event(event, cx)).unwrap_or(false));
379+ self.apply();
380+ took
381+ }
382+
383+ /// Runs what widgets asked with `cx.act`, in order. True if there was anything.
384+ pub fn apply(&mut self) -> bool {
385+ let acts = std::mem::take(self.later.get_mut());
386+ let any = !acts.is_empty();
387+ for f in acts { f(self); }
388+ any
310389 }
311390
312391 /// Instance `id`'s state, writable, beside a Cx for it.