@@ -2,11 +2,13 @@
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.
44 use rune::{El, TextEdit, Tx, col};
5+use serde::{Deserialize, Serialize};
6+use serde_json::json;
57 use std::{any::Any, cell::{Cell, OnceCell, RefCell}, rc::Rc, collections::{BTreeMap, BTreeSet, HashMap}, path::{Path, PathBuf}};
68
79 // ── What widgets read: conveyor's state ─────────────────────────────────────────────────────
810
9-#[derive(Clone, Default, Debug)]
11+#[derive(Clone, Default, Debug, Serialize, Deserialize)]
1012 pub struct Project {
1113 pub slug: String,
1214 pub path: String,
@@ -14,7 +16,7 @@ pub struct Project {
1416 pub slots: u32,
1517 }
1618
17-#[derive(Clone, Default, Debug)]
19+#[derive(Clone, Default, Debug, Serialize, Deserialize)]
1820 pub struct Ticket {
1921 pub project: String,
2022 pub id: u32,
@@ -35,7 +37,7 @@ pub struct Ticket {
3537
3638 /// One thing that happened to a ticket: a state change, an agent's note, decision, deviation,
3739 /// block or reply, or conveyor's own step.
38-#[derive(Clone, Default, Debug)]
40+#[derive(Clone, Default, Debug, Serialize, Deserialize)]
3941 pub struct Activity {
4042 /// Unix seconds.
4143 pub at: u64,
@@ -46,7 +48,7 @@ pub struct Activity {
4648 pub text: String,
4749 }
4850
49-#[derive(Default)]
51+#[derive(Default, Serialize, Deserialize)]
5052 pub struct Data {
5153 pub projects: Vec<Project>,
5254 pub tickets: Vec<Ticket>,
@@ -253,22 +255,6 @@ pub fn keep_build(h: &mut HostState, id: u32, keep: bool) {
253255 Host::live(h).keep_build(id, keep)
254256 }
255257
256-/// A JSON string literal.
257-pub fn quote(s: &str) -> String {
258- let mut out = String::from("\"");
259- for c in s.chars() {
260- match c {
261- '"' => out.push_str("\\\""),
262- '\\' => out.push_str("\\\\"),
263- '\n' => out.push_str("\\n"),
264- c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
265- c => out.push(c),
266- }
267- }
268- out.push('"');
269- out
270-}
271-
272258 // ── The host's side: conveyor's app and the preview drive this; widgets never need to ───────
273259
274260 /// Every widget instance, what they share, and what they asked of the host.
@@ -317,15 +303,13 @@ impl Live {
317303 if let Some(t) = self.data.tickets.iter_mut().find(|t| t.project == project && t.id == id && t.state != "running") {
318304 (t.state, t.since) = (state.to_owned(), now() as u64);
319305 }
320- self.call(format!("{{\"op\":\"set\",\"project\":{},\"id\":{id},\"state\":{}}}", quote(project), quote(state)));
306+ self.call(json!({"op": "set", "project": project, "id": id, "state": state}).to_string());
321307 }
322308
323309 /// Writes a ticket. `files` are copied into it, and the agent working it gets them.
324310 /// `ready` starts an agent on it as soon as a slot is free.
325311 pub fn new_ticket(&mut self, project: &str, title: &str, body: &str, state: &str, files: &[PathBuf]) {
326- let files: Vec<String> = files.iter().map(|f| quote(&f.to_string_lossy())).collect();
327- self.call(format!("{{\"op\":\"ticket\",\"project\":{},\"title\":{},\"body\":{},\"state\":{},\"files\":[{}]}}",
328- quote(project), quote(title), quote(body), quote(state), files.join(",")));
312+ self.call(json!({"op": "ticket", "project": project, "title": title, "body": body, "state": state, "files": files}).to_string());
329313 }
330314
331315 /// Rewrites a ticket's title and body, in place. Shown at once. Conveyor refuses it while
@@ -334,13 +318,13 @@ impl Live {
334318 if let Some(t) = self.data.tickets.iter_mut().find(|t| t.project == project && t.id == id && t.state != "running") {
335319 (t.title, t.body) = (title.to_owned(), body.to_owned());
336320 }
337- self.call(format!("{{\"op\":\"edit\",\"project\":{},\"id\":{id},\"title\":{},\"body\":{}}}", quote(project), quote(title), quote(body)));
321+ self.call(json!({"op": "edit", "project": project, "id": id, "title": title, "body": body}).to_string());
338322 }
339323
340324 /// Adds a project: `slug` names it, `path` is its folder: a git repo, or a new or empty
341325 /// folder that becomes one. Pick a folder with `tx.open_folder(...)`.
342326 pub fn add_project(&mut self, slug: &str, path: &Path) {
343- self.call(format!("{{\"op\":\"project\",\"slug\":{},\"path\":{}}}", quote(slug), quote(&path.to_string_lossy())));
327+ self.call(json!({"op": "project", "slug": slug, "path": path}).to_string());
344328 }
345329
346330 /// The user's call on a widget build on trial (a `widgets` ticket in review): keep merges it
@@ -349,13 +333,13 @@ impl Live {
349333 if let Some(t) = self.data.tickets.iter_mut().find(|t| t.project == "widgets" && t.id == id && t.state == "review") {
350334 (t.state, t.since) = ((if keep { "done" } else { "draft" }).to_owned(), now() as u64);
351335 }
352- self.call(format!("{{\"op\":\"{}\",\"id\":{id}}}", if keep { "keep" } else { "discard" }));
336+ self.call(json!({"op": if keep { "keep" } else { "discard" }, "id": id}).to_string());
353337 }
354338
355339 /// How many of a project's tickets run at once. 0 pauses it. Shown at once.
356340 pub fn set_slots(&mut self, project: &str, slots: u32) {
357341 if let Some(p) = self.data.projects.iter_mut().find(|p| p.slug == project) { p.slots = slots; }
358- self.call(format!("{{\"op\":\"project\",\"slug\":{},\"slots\":{slots}}}", quote(project)));
342+ self.call(json!({"op": "project", "slug": project, "slots": slots}).to_string());
359343 }
360344 }
361345
@@ -494,10 +478,10 @@ impl Live {
494478 out.map_err(|msg| self.broken.get_mut().insert(id.to_owned(), msg)).ok()
495479 }
496480
497- /// Writes what the preview needs to show the app as it is now: `data.tsv` beside the
481+ /// Writes what the preview needs to show the app as it is now: `data.json` beside the
498482 /// instance folders and shared values, and `click`, the instance and element to outline.
499483 pub fn save_state(&self, instance: &str, element: &str) {
500- let _ = std::fs::write(self.base.join("data.tsv"), self.data.to_tsv());
484+ let _ = std::fs::write(self.base.join("data.json"), serde_json::to_string(&self.data).unwrap_or_default());
501485 let _ = std::fs::write(self.base.join("click"), format!("{instance}\t{element}\n"));
502486 }
503487
@@ -513,10 +497,6 @@ impl Live {
513497 ids.join("\n")
514498 }
515499
516- pub fn shared_line(&self) -> String {
517- self.shared.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join(", ")
518- }
519-
520500 /// Requests widgets made for conveyord since the last call.
521501 pub fn take_outbox(&mut self) -> Vec<String> {
522502 std::mem::take(&mut self.outbox)
@@ -540,57 +520,6 @@ impl Live {
540520 }
541521 }
542522
543-// ── Data as text: the app saves it with its state, and the preview loads it ─────────────────
544-
545-fn esc(s: &str) -> String {
546- s.replace('\\', "\\\\").replace('\t', "\\t").replace('\n', "\\n")
547-}
548-
549-fn unesc(s: &str) -> String {
550- let (mut out, mut it) = (String::new(), s.chars());
551- while let Some(c) = it.next() {
552- out.push(if c != '\\' { c } else { match it.next() { Some('t') => '\t', Some('n') => '\n', Some(o) => o, None => break } });
553- }
554- out
555-}
556-
557-impl Data {
558- /// One line per project (P), ticket (T), ticket conversation entry (H) and activity (A).
559- pub fn to_tsv(&self) -> String {
560- let line = |f: Vec<String>| f.iter().map(|x| esc(x)).collect::<Vec<_>>().join("\t") + "\n";
561- let act = |tag: &str, a: &Activity| line(vec![tag.into(), a.at.to_string(), a.project.clone(), a.ticket.to_string(), a.kind.clone(), a.text.clone()]);
562- let mut out = String::new();
563- for p in &self.projects { out += &line(vec!["P".into(), p.slug.clone(), p.path.clone(), p.slots.to_string()]); }
564- for t in &self.tickets {
565- let mut f = vec!["T".into(), t.project.clone(), t.id.to_string(), t.state.clone(), t.created.to_string(), t.since.to_string(), t.title.clone(), t.body.clone()];
566- f.extend(t.files.iter().cloned());
567- out += &line(f);
568- for a in &t.thread { out += &act("H", a); }
569- }
570- for a in &self.activity { out += &act("A", a); }
571- out
572- }
573-
574- pub fn from_tsv(text: &str) -> Data {
575- let mut d = Data::default();
576- for l in text.lines() {
577- let f: Vec<String> = l.split('\t').map(unesc).collect();
578- let g = |i: usize| f.get(i).cloned().unwrap_or_default();
579- let n = |i: usize| g(i).parse::<u64>().unwrap_or(0);
580- let act = || Activity { at: n(1), project: g(2), ticket: n(3) as u32, kind: g(4), text: g(5) };
581- match g(0).as_str() {
582- "P" => d.projects.push(Project { slug: g(1), path: g(2), slots: n(3) as u32 }),
583- "T" => d.tickets.push(Ticket { project: g(1), id: n(2) as u32, state: g(3), created: n(4), since: n(5), title: g(6), body: g(7),
584- files: f.iter().skip(8).cloned().collect(), thread: vec![] }),
585- "H" => if let Some(t) = d.tickets.last_mut() { t.thread.push(act()) },
586- "A" => d.activity.push(act()),
587- _ => {}
588- }
589- }
590- d
591- }
592-}
593-
594523 pub fn now() -> f64 {
595524 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64())
596525 }