8447
Co
conveyor / files
conveyor / templates / library / api.rs
25.4 KB
1//! The contract between this library and conveyor. Conveyor owns this file and replaces it 2//! when it changes. Everything in widgets/ is the library's, starting with root.rs: the app 3//! draws `root` and nothing else, so the whole UI is widgets. 4use rune::{El, TextEdit, Tx, col}; 5use serde::{Deserialize, Serialize}; 6use serde_json::json; 7use std::{any::Any, cell::{Cell, OnceCell, RefCell}, rc::Rc, collections::{BTreeMap, BTreeSet, HashMap}, path::{Path, PathBuf}}; 8 9// ── What widgets read: conveyor's state ───────────────────────────────────────────────────── 10 11#[derive(Clone, Default, Debug, Serialize, Deserialize)] 12pub struct Project { 13 pub slug: String, 14 pub path: String, 15 /// How many tickets run at once. 16 pub slots: u32, 17} 18 19#[derive(Clone, Default, Debug, Serialize, Deserialize)] 20pub struct Ticket { 21 pub project: String, 22 pub id: u32, 23 pub title: String, 24 /// draft, ready, running, review, parked, failed, done. Ready starts an agent when the 25 /// project has a free slot; conveyor moves it to running and then settles it. 26 pub state: String, 27 /// What was asked, in Markdown. 28 pub body: String, 29 /// Unix seconds: when it was written, and when it last changed state. 30 pub created: u64, 31 pub since: u64, 32 /// Attached files, as paths you can read. 33 pub files: Vec<String>, 34 /// Its conversation, oldest first: kinds prompt, decide, deviate, block, reply, error. 35 pub thread: Vec<Activity>, 36} 37 38/// One thing that happened to a ticket: a state change, an agent's note, decision, deviation, 39/// block or reply, or conveyor's own step. 40#[derive(Clone, Default, Debug, Serialize, Deserialize)] 41pub struct Activity { 42 /// Unix seconds. 43 pub at: u64, 44 pub project: String, 45 pub ticket: u32, 46 /// state, note, decide, deviate, block, done, reply, conveyor, error. 47 pub kind: String, 48 pub text: String, 49} 50 51#[derive(Default, Serialize, Deserialize)] 52pub struct Data { 53 pub projects: Vec<Project>, 54 pub tickets: Vec<Ticket>, 55 /// The latest 200 events, oldest first. 56 pub activity: Vec<Activity>, 57 /// Whether conveyord answers. Without it, everything above is as it last was. 58 pub connected: bool, 59} 60 61// ── Widgets ───────────────────────────────────────────────────────────────────────────────── 62 63/// Every widget kind in the library, as (file name, widget): what a host loads. 64pub type Kinds = &'static [(&'static str, &'static Widget)]; 65/// Each kind's description: the first paragraph of its file's `//!` comment. 66pub type Abouts = &'static [(&'static str, &'static str)]; 67 68/// Each widget file declares `pub const WIDGET: Widget`. 69pub struct Widget { 70 pub title: &'static str, 71 /// The size it would like, in points, where a parent lets children pick (root's canvas). 72 pub size: (f32, f32), 73 /// Makes one instance's state: once per instance, each time the app starts. 74 pub new: fn(&Cx) -> Box<dyn View>, 75} 76 77/// A widget instance's state. It renders itself into the box its parent gives it. 78pub trait View: Any { 79 fn view(&self, cx: &Cx) -> El; 80 /// Runs before every render, with the state writable: note what changed in `cx.data`, step 81 /// a simulation, start a fetch. 82 fn update(&mut self, _cx: &Cx) {} 83 /// Something happened that no single element owns: a paste with no text field focused, or 84 /// files dropped on the window. Every instance is offered it, innermost first, until one 85 /// returns true. 86 fn event(&mut self, _event: &Event, _cx: &Cx) -> bool { 87 false 88 } 89 /// A build asked (`conveyor place <kind> --in <this instance>`) to have the new widget 90 /// `kind` placed here, at `at` in this widget's points: where the user Ctrl+clicked, when 91 /// that was inside it. Keep it as a child and return true. 92 fn mount(&mut self, _kind: &str, _at: (f32, f32), _cx: &Cx) -> bool { 93 false 94 } 95} 96 97/// A window-wide happening, for `View::event`. 98pub enum Event { 99 /// Clipboard content pasted with no text field focused. A pasted image is saved as a PNG 100 /// first, and `image` is its path. 101 Paste { text: String, image: Option<PathBuf> }, 102 /// Files dropped on the window. 103 Drop(Vec<PathBuf>), 104} 105 106/// What a widget gets when it's made and each time it renders. 107pub struct Cx<'a> { 108 /// This instance: "root", or its parent's id, a dot and the key the parent gave it. 109 pub id: &'a str, 110 /// Unix seconds. The app renders at least once a second; `animate` asks for more. 111 pub now: f64, 112 pub data: &'a Data, 113 /// This instance's own folder. What it keeps there survives restarts, and every library 114 /// change, which drops the instance and makes it again from the new code. 115 pub dir: PathBuf, 116 live: &'a Live, 117} 118 119impl Cx<'_> { 120 /// A widget inside this one: `kind` is its file name, `key` names this instance among its 121 /// siblings. Keep the key stable, since the instance's state and folder hang off it. 122 pub fn child(&self, kind: &str, key: &str) -> El { 123 self.live.render(kind, &format!("{}.{key}", self.id)) 124 } 125 126 /// The app's image cache: decodes off the UI thread and redraws when an image is ready. 127 /// Keep the handle (`images: cx.images()`) to load from handlers too. 128 pub fn images(&self) -> Rc<rune::ImageCache> { 129 let live = self.live; 130 live.images.get_or_init(|| Rc::new(rune::ImageCache::new(live.waker.clone()))).clone() 131 } 132 133 /// What widget `kind` is, from the first paragraph of its file's `//!` comment. 134 pub fn about(&self, kind: &str) -> &'static str { 135 self.live.about.iter().find(|(n, _)| *n == kind).map_or("", |(_, a)| a) 136 } 137 138 /// A value any widget can read, set with `share`: the selected project, say. 139 pub fn shared(&self, key: &str) -> Option<&str> { 140 self.live.shared.get(key).map(String::as_str) 141 } 142 143 /// A secret from the keychain, such as an API key, set with `set_secret`. Read it where 144 /// you use it (a handler, or before starting a thread), not in `view`: it's a file read. 145 pub fn secret(&self, name: &str) -> Option<String> { 146 self.live.secret(name) 147 } 148 149 /// The names of every secret the user keeps, sorted: the keychain. A folder read, like `secret`. 150 pub fn secrets(&self) -> Vec<String> { 151 self.live.secrets() 152 } 153 154 /// Ask for frames at the display's rate while this keeps being called: for animation. 155 pub fn animate(&self) { 156 self.live.animate.set(true); 157 } 158 159 /// Every widget kind in the library, as (name, widget). 160 pub fn kinds(&self) -> Kinds { 161 self.live.kinds 162 } 163 164 /// Acts on the app from anywhere a widget runs (view, update, event), not only handlers: 165 /// `cx.act(move |l| l.share("note", &path))`. From update and event it runs right after 166 /// them; from view, at the next update. 167 pub fn act(&self, f: impl FnOnce(&mut Live) + 'static) { 168 self.live.later.borrow_mut().push(Box::new(f)); 169 } 170 171 /// Call it from `update` while this instance has work that must go on when nothing shows 172 /// it, such as music playing: the app brings it back after a library change or a restart, 173 /// even when no parent renders it. Stop calling it when the work stops. 174 pub fn keep_running(&self) { 175 self.live.running.borrow_mut().insert(self.id.to_owned()); 176 } 177} 178 179// ── Handlers: reaching state and conveyor from a press, a key, an edit ────────────────────── 180 181/// The state Rune hands every handler: the app's, or the preview's. 182pub type HostState = crate::HostState; 183 184/// The app, or the preview. 185pub trait Host: 'static { 186 fn live(&mut self) -> &mut Live; 187} 188 189/// Instance `id`'s state, inside any handler. 190pub fn get<'a, W: View>(h: &'a mut HostState, id: &str) -> Option<&'a mut W> { 191 let w: &mut dyn Any = Host::live(h).instances.get_mut(id)?.1.as_mut(); 192 w.downcast_mut() 193} 194 195/// A handler on instance `id`'s state, for on_press_tx, on_submit, on_input_change and the like. 196pub fn on<W: View>(id: &str, f: impl Fn(&mut W, &mut Tx) + 'static) -> impl Fn(&mut HostState, &mut Tx) + 'static { 197 let id = id.to_owned(); 198 move |h: &mut HostState, tx: &mut Tx| { 199 let Some(w) = get::<W>(h, &id) else { return }; 200 if let Err(msg) = catch(|| f(w, tx)) { Host::live(h).broken.get_mut().insert(id.clone(), msg); } 201 } 202} 203 204/// Runs widget code, turning a panic into its message. 205fn catch<T>(f: impl FnOnce() -> T) -> Result<T, String> { 206 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|e| { 207 e.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| e.downcast_ref::<String>().cloned()).unwrap_or_else(|| "it panicked".into()) 208 }) 209} 210 211/// What a broken instance draws instead of itself. 212fn stopped(kind: &str, msg: &str) -> El { 213 let (t, red) = (rune::tok::theme(true), rune::Color { r: 0.9, g: 0.35, b: 0.3, a: 1.0 }); 214 col().w_full().h_full().padding(12.0).gap(4.0).radius(6.0).fill(t.card).border(1.0, red) 215 .child(rune::text(format!("{kind} stopped: {msg}")).color(red).w_full().wrap()) 216 .child(rune::text("Ctrl+click it to have it fixed").font(rune::tok::type_::LABEL).color(t.text_secondary)) 217} 218 219/// Binds a text field to a TextEdit in instance `id`'s state: 220/// `.on_edit(edit(cx.id, |w: &mut Notes| &mut w.text))`. 221pub fn edit<W: View>(id: &str, f: impl Fn(&mut W) -> &mut TextEdit + 'static) -> impl for<'a> Fn(&'a mut HostState) -> &'a mut TextEdit + 'static { 222 let id = id.to_owned(); 223 rune::edit_access(move |h: &mut HostState| { 224 if get::<W>(h, &id).is_none() { return &mut Host::live(h).spare; } 225 f(get::<W>(h, &id).unwrap()) 226 }) 227} 228 229/// Sets a shared value; every widget sees it on its next render. Kept across restarts. 230pub fn share(h: &mut HostState, key: &str, value: &str) { 231 Host::live(h).share(key, value) 232} 233 234/// Keeps a secret, such as an API key, in the user's keychain, outside the app state. Empty forgets it. 235pub fn set_secret(h: &mut HostState, name: &str, value: &str) { 236 Host::live(h).set_secret(name, value) 237} 238 239/// Sends one request to conveyord. The ops are in conveyor's server.rs. 240pub fn call(h: &mut HostState, request: String) { 241 Host::live(h).call(request) 242} 243 244/// Moves a ticket: `set_state(h, "conveyor", 3, "review")`. See `Live::set_state`. 245pub fn set_state(h: &mut HostState, project: &str, id: u32, state: &str) { 246 Host::live(h).set_state(project, id, state) 247} 248 249/// Writes a ticket: `new_ticket(h, "conveyor", "Title", "What and why", "draft", &[])`. See `Live::new_ticket`. 250pub fn new_ticket(h: &mut HostState, project: &str, title: &str, body: &str, state: &str, files: &[PathBuf]) { 251 Host::live(h).new_ticket(project, title, body, state, files) 252} 253 254/// Rewrites a ticket's title and body. See `Live::edit_ticket`. 255pub fn edit_ticket(h: &mut HostState, project: &str, id: u32, title: &str, body: &str) { 256 Host::live(h).edit_ticket(project, id, title, body) 257} 258 259/// Adds a project. See `Live::add_project`. 260pub fn add_project(h: &mut HostState, slug: &str, path: &Path) { 261 Host::live(h).add_project(slug, path) 262} 263 264/// How many of a project's tickets run at once. 0 pauses it. 265pub fn set_slots(h: &mut HostState, project: &str, slots: u32) { 266 Host::live(h).set_slots(project, slots) 267} 268 269/// Keeps a widget build on trial (merges it into the library) or discards it. See `Live::keep_build`. 270pub fn keep_build(h: &mut HostState, id: u32, keep: bool) { 271 Host::live(h).keep_build(id, keep) 272} 273 274// ── The host's side: conveyor's app and the preview drive this; widgets never need to ─────── 275 276/// Every widget instance, what they share, and what they asked of the host. 277pub struct Live { 278 pub data: Data, 279 kinds: Kinds, 280 about: Abouts, 281 /// The host's waker and the image cache made with it, shared by every widget. 282 waker: rune::Waker, 283 images: OnceCell<Rc<rune::ImageCache>>, 284 /// Instances whose code panicked, with the message. They draw `stopped` until the next build. 285 broken: RefCell<BTreeMap<String, String>>, 286 base: PathBuf, 287 /// Beside `base`, never in it: the app's state is copied into every build ticket. 288 secrets: PathBuf, 289 instances: HashMap<String, (String, Box<dyn View>)>, 290 shared: BTreeMap<String, String>, 291 wanted: RefCell<Vec<(String, String)>>, 292 animate: Cell<bool>, 293 outbox: Vec<String>, 294 spare: TextEdit, 295 dirty: bool, 296 /// What widgets asked to do with `cx.act`, run after each update, event and render. 297 later: RefCell<Vec<Box<dyn FnOnce(&mut Live)>>>, 298 /// Instances that called `cx.keep_running` in the last update, and the set last saved. 299 running: RefCell<BTreeSet<String>>, 300 kept: BTreeSet<String>, 301} 302 303// ── What widgets can do: from handlers with the free functions above, from anywhere with `cx.act` 304 305impl Live { 306 /// Sets a shared value; every widget sees it on its next render. Kept across restarts. 307 pub fn share(&mut self, key: &str, value: &str) { 308 self.shared.insert(key.to_owned(), value.to_owned()); 309 self.dirty = true; 310 } 311 312 /// Keeps a secret in the keychain, readable by the user alone. Empty forgets it. 313 pub fn set_secret(&mut self, name: &str, value: &str) { 314 use std::{io::Write, os::unix::fs::{DirBuilderExt, OpenOptionsExt}}; 315 let path = self.secrets.join(name.replace('/', "_")); 316 if value.is_empty() { let _ = std::fs::remove_file(path); return; } 317 let _ = std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&self.secrets); 318 let file = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(path); 319 let _ = file.and_then(|mut f| f.write_all(value.as_bytes())); 320 } 321 322 /// A secret, as `cx.secret` reads it. 323 pub fn secret(&self, name: &str) -> Option<String> { 324 std::fs::read_to_string(self.secrets.join(name.replace('/', "_"))).ok().filter(|s| !s.is_empty()) 325 } 326 327 /// The names of every secret, as `cx.secrets` lists them. 328 pub fn secrets(&self) -> Vec<String> { 329 let mut names: Vec<String> = std::fs::read_dir(&self.secrets).into_iter().flatten().flatten() 330 .filter_map(|e| e.file_name().into_string().ok()).collect(); 331 names.sort(); 332 names 333 } 334 335 /// Sends one request to conveyord, as `conveyor call` does. The ops are in conveyor's 336 /// server.rs. Results show up in `cx.data` within a second. 337 pub fn call(&mut self, request: String) { 338 self.outbox.push(request); 339 } 340 341 /// Moves a ticket. Shown at once: `cx.data` changes now, and conveyor's next snapshot 342 /// confirms it. Conveyor refuses moves into or out of running. 343 pub fn set_state(&mut self, project: &str, id: u32, state: &str) { 344 if let Some(t) = self.data.tickets.iter_mut().find(|t| t.project == project && t.id == id && t.state != "running") { 345 (t.state, t.since) = (state.to_owned(), now() as u64); 346 } 347 self.call(json!({"op": "set", "project": project, "id": id, "state": state}).to_string()); 348 } 349 350 /// Writes a ticket. `files` are copied into it, and the agent working it gets them. 351 /// `ready` starts an agent on it as soon as a slot is free. 352 pub fn new_ticket(&mut self, project: &str, title: &str, body: &str, state: &str, files: &[PathBuf]) { 353 self.call(json!({"op": "ticket", "project": project, "title": title, "body": body, "state": state, "files": files}).to_string()); 354 } 355 356 /// Rewrites a ticket's title and body, in place. Shown at once. Conveyor refuses it while 357 /// the ticket is running. 358 pub fn edit_ticket(&mut self, project: &str, id: u32, title: &str, body: &str) { 359 if let Some(t) = self.data.tickets.iter_mut().find(|t| t.project == project && t.id == id && t.state != "running") { 360 (t.title, t.body) = (title.to_owned(), body.to_owned()); 361 } 362 self.call(json!({"op": "edit", "project": project, "id": id, "title": title, "body": body}).to_string()); 363 } 364 365 /// Adds a project: `slug` names it, `path` is its folder: a git repo, or a new or empty 366 /// folder that becomes one. Pick a folder with `tx.open_folder(...)`. 367 pub fn add_project(&mut self, slug: &str, path: &Path) { 368 self.call(json!({"op": "project", "slug": slug, "path": path}).to_string()); 369 } 370 371 /// The user's call on a widget build on trial (a `widgets` ticket in review): keep merges it 372 /// into the library, discard sends it back to draft and the app drops it. Shown at once. 373 pub fn keep_build(&mut self, id: u32, keep: bool) { 374 if let Some(t) = self.data.tickets.iter_mut().find(|t| t.project == "widgets" && t.id == id && t.state == "review") { 375 (t.state, t.since) = ((if keep { "done" } else { "draft" }).to_owned(), now() as u64); 376 } 377 self.call(json!({"op": if keep { "keep" } else { "discard" }, "id": id}).to_string()); 378 } 379 380 /// How many of a project's tickets run at once. 0 pauses it. Shown at once. 381 pub fn set_slots(&mut self, project: &str, slots: u32) { 382 if let Some(p) = self.data.projects.iter_mut().find(|p| p.slug == project) { p.slots = slots; } 383 self.call(json!({"op": "project", "slug": project, "slots": slots}).to_string()); 384 } 385} 386 387impl Live { 388 /// Instances of `kinds` keep their folders under `base`, shared values in `base/shared.tsv`, 389 /// and secrets in `secrets` beside it. 390 pub fn new(base: PathBuf, kinds: Kinds, about: Abouts) -> Self { 391 let shared = std::fs::read_to_string(base.join("shared.tsv")).unwrap_or_default().lines() 392 .filter_map(|l| l.split_once('\t').map(|(k, v)| (k.to_owned(), v.replace("\\n", "\n")))) 393 .collect(); 394 // Instances that were keeping work going come back now, shown or not. 395 let wanted: Vec<(String, String)> = std::fs::read_to_string(base.join("running.tsv")).unwrap_or_default().lines() 396 .filter_map(|l| l.split_once('\t').map(|(id, kind)| (id.to_owned(), kind.to_owned()))).collect(); 397 Live { data: Data::default(), kinds, about, broken: RefCell::new(BTreeMap::new()), waker: std::sync::Arc::new(|| {}), images: OnceCell::new(), secrets: base.with_file_name("secrets"), base, instances: HashMap::new(), shared, wanted: RefCell::new(wanted), 398 animate: Cell::new(false), outbox: vec![], spare: TextEdit::new(""), dirty: false, 399 later: RefCell::new(vec![]), running: RefCell::new(BTreeSet::new()), kept: BTreeSet::new() } 400 } 401 402 fn cx<'a>(&'a self, id: &'a str, now: f64) -> Cx<'a> { 403 Cx { id, now, data: &self.data, dir: self.base.join("w").join(id), live: self } 404 } 405 406 /// Instance `id` of `kind`, keyed `w:<id>` so the app can find it under the pointer. 407 pub fn render(&self, kind: &str, id: &str) -> El { 408 let broken = self.broken.borrow().get(id).cloned(); 409 if let Some(msg) = broken { return stopped(kind, &msg).key(format!("w:{id}")); } 410 match self.instances.get(id) { 411 Some((k, w)) if k == kind => match catch(|| w.view(&self.cx(id, now()))) { 412 Ok(el) => el.key(format!("w:{id}")), 413 Err(msg) => { self.broken.borrow_mut().insert(id.to_owned(), msg.clone()); stopped(kind, &msg).key(format!("w:{id}")) } 414 }, 415 // Made before the next render. A kind the library doesn't have (a discarded build's) 416 // draws nothing. 417 _ => { 418 self.wanted.borrow_mut().push((id.to_owned(), kind.to_owned())); 419 col().key(format!("w:{id}")).w_full().h_full() 420 } 421 } 422 } 423 424 /// Makes the instances renders asked for. True if any were made: render again. 425 pub fn make_wanted(&mut self) -> bool { 426 let wanted = std::mem::take(self.wanted.get_mut()); 427 let mut made = false; 428 for (id, kind) in wanted { 429 let Some((_, w)) = self.kinds.iter().find(|(n, _)| *n == kind) else { continue }; 430 if self.instances.get(&id).is_some_and(|(k, _)| *k == kind) { continue; } 431 let cx = self.cx(&id, now()); 432 let _ = std::fs::create_dir_all(&cx.dir); 433 match catch(|| (w.new)(&cx)) { 434 Ok(state) => { self.instances.insert(id, (kind, state)); } 435 Err(msg) => { self.broken.get_mut().insert(id, msg); } 436 } 437 made = true; 438 } 439 made 440 } 441 442 /// Offers new widget `kind` to instance `id`, at `at` in its points. Whether it kept it. 443 pub fn mount(&mut self, id: &str, at: (f32, f32), kind: &str) -> bool { 444 self.kinds.iter().any(|(n, _)| *n == kind) && self.with(id, |w, cx| w.mount(kind, at, cx)) == Some(true) 445 } 446 447 /// A new build of the library: every instance is dropped, then made again from its kind's 448 /// new code, before the next render. What they asked with `cx.act` runs first, against 449 /// the old instances. Kinds the new build doesn't have are gone. 450 pub fn reload(&mut self, kinds: Kinds, about: Abouts) { 451 self.apply(); 452 let all: Vec<(String, String)> = self.instances.drain().map(|(id, (kind, _))| (id, kind)).collect(); 453 (self.kinds, self.about) = (kinds, about); 454 self.broken.get_mut().clear(); 455 self.wanted.get_mut().extend(all); 456 self.make_wanted(); 457 } 458 459 /// How widgets wake the host from other threads (images decoded). Set it before rendering. 460 pub fn set_waker(&mut self, waker: rune::Waker) { 461 self.waker = waker; 462 } 463 464 /// A shared value, as `cx.shared` reads it. 465 pub fn shared(&self, key: &str) -> Option<&str> { 466 self.shared.get(key).map(String::as_str) 467 } 468 469 /// Every instance made again, from the same build: a fresh start for broken ones. 470 pub fn remake(&mut self) { 471 self.reload(self.kinds, self.about); 472 } 473 474 /// Why instance `id` stopped, if its code panicked. 475 pub fn broken(&self, id: &str) -> Option<String> { 476 self.broken.borrow().get(id).cloned() 477 } 478 479 /// Instances of `kind`, or any instance if `kind` is empty. 480 pub fn ids(&self, kind: &str) -> Vec<String> { 481 self.instances.iter().filter(|(_, (k, _))| kind.is_empty() || k == kind).map(|(id, _)| id.clone()).collect() 482 } 483 484 /// Runs `update` on every instance, then what they asked with `cx.act`. Saves which 485 /// instances keep work running, so a restart brings them back. True if anything acted. 486 pub fn update(&mut self) -> bool { 487 self.running.get_mut().clear(); 488 for id in self.ids("") { self.with(&id, |w, cx| w.update(cx)); } 489 if *self.running.get_mut() != self.kept { 490 self.kept = self.running.get_mut().clone(); 491 let lines: String = self.kept.iter().filter_map(|id| Some(format!("{id}\t{}\n", self.kind(id)?))).collect(); 492 let _ = std::fs::write(self.base.join("running.tsv"), lines); 493 } 494 self.apply() 495 } 496 497 /// Offers an event to every instance, innermost first. True when one took it. 498 pub fn event(&mut self, event: &Event) -> bool { 499 let mut ids = self.ids(""); 500 ids.sort_by_key(|id| std::cmp::Reverse(id.matches('.').count())); 501 let took = ids.iter().any(|id| self.with(id, |w, cx| w.event(event, cx)).unwrap_or(false)); 502 self.apply(); 503 took 504 } 505 506 /// Runs what widgets asked with `cx.act`, in order. True if there was anything. 507 pub fn apply(&mut self) -> bool { 508 let acts = std::mem::take(self.later.get_mut()); 509 let any = !acts.is_empty(); 510 for f in acts { f(self); } 511 any 512 } 513 514 /// Instance `id`'s state, writable, beside a Cx for it. 515 fn with<T>(&mut self, id: &str, f: impl FnOnce(&mut dyn View, &Cx) -> T) -> Option<T> { 516 if self.broken.get_mut().contains_key(id) { return None; } 517 let (k, mut w) = self.instances.remove(id)?; 518 let out = catch(|| f(w.as_mut(), &self.cx(id, now()))); 519 self.instances.insert(id.to_owned(), (k, w)); 520 out.map_err(|msg| self.broken.get_mut().insert(id.to_owned(), msg)).ok() 521 } 522 523 /// Writes what the preview needs to show the app as it is now: `data.json` beside the 524 /// instance folders and shared values, and `click`, the instance and element to outline. 525 pub fn save_state(&self, instance: &str, element: &str) { 526 let _ = std::fs::write(self.base.join("data.json"), serde_json::to_string(&self.data).unwrap_or_default()); 527 let _ = std::fs::write(self.base.join("click"), format!("{instance}\t{element}\n")); 528 } 529 530 /// Which kind instance `id` is. 531 pub fn kind(&self, id: &str) -> Option<&str> { 532 self.instances.get(id).map(|(k, _)| k.as_str()) 533 } 534 535 /// The instances, as "id (kind)" lines sorted by id: what the agent sees of the screen. 536 pub fn tree(&self) -> String { 537 let mut ids: Vec<_> = self.instances.iter().map(|(id, (k, _))| format!("{id} ({k})")).collect(); 538 ids.sort(); 539 ids.join("\n") 540 } 541 542 /// Requests widgets made for conveyord since the last call. 543 pub fn take_outbox(&mut self) -> Vec<String> { 544 std::mem::take(&mut self.outbox) 545 } 546 547 /// Whether a render asked for animation frames; resets it. 548 pub fn animating(&self) -> bool { 549 self.animate.replace(false) 550 } 551 552 /// Saves shared values if they changed. 553 pub fn save(&mut self) { 554 if !std::mem::take(&mut self.dirty) { return; } 555 let _ = std::fs::create_dir_all(&self.base); 556 let lines: String = self.shared.iter().map(|(k, v)| format!("{k}\t{}\n", v.replace('\n', "\\n"))).collect(); 557 let _ = std::fs::write(self.base.join("shared.tsv"), lines); 558 } 559 560 pub fn base(&self) -> &Path { 561 &self.base 562 } 563} 564 565pub fn now() -> f64 { 566 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()) 567}