xonecas.io
8447
Co

conveyor / files

conveyor / templates / library / preview / src / main.rs

6.7 KB
1//! Runs the library as the app does, headless, so it can be checked:
2//!     cargo run --release -p preview -- [--state DIR] <kind> [child kinds…] --snap /tmp/x.png --tree /tmp/x.json --size 1400x900
3//! It's the app's own host: children, shared values, handlers, update, events, animation and
4//! instance folders (/tmp/preview/w/<id>) all work. Child kinds after the first are mounted,
5//! offered to each instance innermost first, as `conveyor place` asks the app to. Requests for conveyord are printed.
6//!
7//! --state DIR replays the user's app: its data, shared values and instance folders, copied so
8//! the run can't change them, with what they Ctrl+clicked outlined in orange.
9mod widgets {
10    include!(concat!(env!("OUT_DIR"), "/widgets.rs"));
11}
12
13use rune::{AppSpec, El, Tx, el};
14use std::{path::{Path, PathBuf}, time::Duration};
15use widgets::api::{Activity, Data, Host, Live, Project, Ticket};
16
17pub type HostState = State;
18
19pub struct State {
20    live: Live,
21    kind: String,
22    mounts: Vec<String>,
23    /// The instance and element the user clicked, from --state.
24    click: Option<(String, String)>,
25}
26
27impl Host for State {
28    fn live(&mut self) -> &mut Live {
29        &mut self.live
30    }
31}
32
33fn sample() -> Data {
34    let p = |slug: &str| Project { slug: slug.into(), path: format!("/home/me/{slug}"), slots: 1 };
35    let now = widgets::api::now() as u64;
36    let a = |ago: u64, project: &str, ticket, kind: &str, text: &str| Activity { at: now - ago, project: project.into(), ticket, kind: kind.into(), text: text.into() };
37    let t = |project: &str, id, state: &str, title: &str, ago: u64| Ticket {
38        project: project.into(), id, state: state.into(), title: title.into(), body: format!("{title}.\n\nWhy: it's the next step."),
39        created: now - ago - 600, since: now - ago, thread: vec![a(ago + 600, project, id, "prompt", title)], ..Default::default()
40    };
41    let mut tickets = vec![
42        t("conveyor", 1, "running", "conveyord: store, dispatcher, VM and agent drivers", 300),
43        t("conveyor", 2, "review", "Guest CLI: the agent's verbs", 900),
44        t("conveyor", 3, "parked", "App shell: canvas and widget prompt", 1800),
45        t("conveyor", 4, "draft", "Window chrome: minimize and edge resize", 3600),
46        t("conveyor", 5, "ready", "Snapshots on decide", 60),
47        t("dotfiles", 7, "ready", "Swap the terminal font", 120),
48        t("dotfiles", 8, "done", "Add a git alias for amend", 7200),
49        t("game", 1, "running", "Player movement", 90),
50        t("game", 2, "failed", "Sound effects", 10),
51        t("widgets", 6, "review", "Show the time in the title bar", 30),
52    ];
53    tickets[0].thread.push(a(240, "conveyor", 1, "decide", "Use a ring buffer for activity — bounded memory"));
54    tickets[2].thread.push(a(60, "conveyor", 3, "block", "Needs the signing key — recommends: add it to the vault"));
55    tickets[9].thread.push(a(30, "widgets", 6, "reply", "The title bar now shows your local time as HH:MM, left of the window buttons."));
56    Data {
57        projects: vec![p("conveyor"), p("dotfiles"), p("game")],
58        activity: vec![
59            a(300, "conveyor", 1, "state", "running"),
60            a(240, "conveyor", 1, "decide", "Use a ring buffer for activity"),
61            a(120, "game", 1, "note", "Movement feels floaty; tuning gravity"),
62            a(60, "conveyor", 3, "block", "Needs the signing key"),
63            a(10, "game", 2, "state", "failed"),
64        ],
65        tickets,
66        connected: true,
67    }
68}
69
70/// A fresh copy of the user's instance folders and shared values in `base`.
71fn replay(state: &Path, base: &Path) -> (Data, Option<(String, String)>) {
72    let _ = std::fs::remove_dir_all(base);
73    let _ = std::fs::create_dir_all(base);
74    for f in ["w", "shared.tsv"].map(|f| state.join(f)).iter().filter(|f| f.exists()) {
75        let _ = std::process::Command::new("cp").arg("-r").arg(f).arg(base).status();
76    }
77    let saved = std::fs::read_to_string(state.join("data.json")).ok().and_then(|s| serde_json::from_str(&s).ok());
78    let data = Data { connected: true, ..saved.unwrap_or_default() };
79    let click = std::fs::read_to_string(state.join("click")).ok()
80        .and_then(|c| c.trim_end_matches('\n').split_once('\t').map(|(i, e)| (i.to_owned(), e.to_owned())));
81    (data, click)
82}
83
84fn init() -> State {
85    let mut args: Vec<String> = rune::extra_args().to_vec();
86    let mut state = None;
87    if let Some(i) = args.iter().position(|a| a == "--state") {
88        state = args.get(i + 1).map(PathBuf::from);
89        args.drain(i..(i + 2).min(args.len()));
90    }
91    let base = std::env::temp_dir().join("preview");
92    let (data, click) = match state {
93        Some(dir) => replay(&dir, &base),
94        None => (sample(), None),
95    };
96    let mut live = Live::new(base, widgets::ALL, widgets::ABOUT);
97    live.data = data;
98    let mut args = args.into_iter();
99    State { live, kind: args.next().unwrap_or_default(), mounts: args.collect(), click }
100}
101
102fn view(s: &State, rcx: &mut rune::Cx<State>) -> El {
103    let mut window = el().w_full().h_full().child(s.live.render(&s.kind, "root"));
104    // As in the app: build status over the window.
105    if s.kind == "root" { window = window.child(el().absolute(0.0, 0.0).w_full().h_full().child(s.live.render("status", "status"))); }
106    if let Some((id, element)) = &s.click {
107        let orange = rune::Color { r: 1.0, g: 0.55, b: 0.1, a: 1.0 };
108        let instance = rcx.layout(&format!("w:{id}"));
109        let leaf = element.rsplit('/').next().unwrap_or("");
110        let part = if leaf.is_empty() { None } else { rcx.layout(&format!("w:{id}/{element}")).or_else(|| rcx.layout(leaf)) };
111        for (r, width) in [(instance, 1.5), (part, 3.0)] {
112            if let Some([x, y, w, h]) = r { window = window.child(el().absolute(x, y).w(w).h(h).border(width, orange).radius(4.0)); }
113        }
114    }
115    window
116}
117
118fn poll(s: &mut State, _: f64, tx: &mut Tx) -> bool {
119    let mut again = s.live.make_wanted();
120    // Once every instance exists, mount the requested children, innermost instance first.
121    if !again && !s.mounts.is_empty() && s.live.kind("root").is_some() {
122        let mut ids = s.live.ids("");
123        ids.sort_by_key(|id| std::cmp::Reverse(id.matches('.').count()));
124        for kind in std::mem::take(&mut s.mounts) {
125            if !ids.iter().any(|id| s.live.mount(id, (40.0, 40.0), &kind)) { eprintln!("preview: no widget kept `{kind}`"); }
126        }
127        again = true;
128    }
129    again |= s.live.update();
130    for r in s.live.take_outbox() { eprintln!("preview: would send to conveyord: {r}"); }
131    s.live.save();
132    if s.live.animating() { tx.wake_after(Duration::from_millis(16)); }
133    again
134}
135
136fn main() {
137    rune::run(AppSpec { poll: Some(poll), setup: Some(|s: &mut State, w| s.live.set_waker(w)), ..AppSpec::new("preview", (1400.0, 900.0), init, view) });
138}