8447
Co
conveyor / files
conveyor / crates / conveyor-app / src / app.rs
8.9 KB
1//! The app's state and loop. It draws the library's `root` widget and three things of its own 2//! above it: the Ctrl inspector, the prompt form and safe mode. Over `root` it draws the library's `status` 3//! widget, build status, so the user can replace that too. Everything else is widgets. 4use crate::{client, form::{self, Form}, inspect, reload::Loader, safe}; 5use crate::api::{Event, Host, Live}; 6use rune::{El, Tx, Waker, el}; 7use serde_json::Value; 8use std::{cell::RefCell, collections::BTreeSet, path::{Path, PathBuf}, sync::{Arc, Mutex}, time::{Duration, Instant, SystemTime}}; 9 10pub struct State { 11 pub live: Live, 12 /// The widget builds, with their tickets' state and conversation. 13 pub builds: Vec<Value>, 14 pub connected: bool, 15 /// The latest snapshot, and when its request started. 16 inbox: Arc<Mutex<Option<(Instant, Option<Value>)>>>, 17 /// When widgets last sent conveyord a request: a snapshot asked for before it is stale, 18 /// and would undo what `set_state` already shows. 19 sent: Instant, 20 /// When this process started rendering: new widgets are placed once their parents exist. 21 started: Instant, 22 /// The binary at launch and its mtime. Read once: after cargo replaces it, 23 /// current_exe() names the deleted file. 24 exe: Option<PathBuf>, 25 built: Option<SystemTime>, 26 /// Ctrl is held: the inspector is up. 27 pub ctrl: bool, 28 /// The pointer, in window points. 29 pub pointer: (f32, f32), 30 /// The widget instances under the pointer, innermost first, and the element's key. 31 pub picked: Vec<String>, 32 pub element: String, 33 /// Each picked instance's rect, as of the last render. 34 pub rects: RefCell<Vec<(String, [f32; 4])>>, 35 pub form: Option<Form>, 36 /// The window's size in points, as of the last render. 37 pub window: std::cell::Cell<(f32, f32)>, 38 /// What the form's field binds to in the frame it closes. 39 pub spare: rune::TextEdit, 40 /// Safe mode is up, and why: every widget is paused. 41 pub safe: Option<String>, 42 /// Builds whose new widgets were placed. 43 placed: BTreeSet<u64>, 44 widgets: Loader, 45} 46 47impl Host for State { 48 fn live(&mut self) -> &mut Live { 49 &mut self.live 50 } 51} 52 53fn mtime(p: &Path) -> Option<SystemTime> { 54 std::fs::metadata(p).ok()?.modified().ok() 55} 56 57fn ids(base: &Path, name: &str) -> Option<BTreeSet<u64>> { 58 Some(std::fs::read_to_string(base.join(name)).ok()?.split_whitespace().filter_map(|w| w.parse().ok()).collect()) 59} 60 61pub fn save_ids(base: &Path, name: &str, set: &BTreeSet<u64>) { 62 let _ = std::fs::write(base.join(name), set.iter().map(|i| format!("{i}\n")).collect::<String>()); 63} 64 65pub fn init() -> State { 66 let base = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/conveyor/app"); 67 let _ = std::fs::create_dir_all(&base); 68 let mut widgets = Loader::new(); 69 let (kinds, about) = widgets.poll().unwrap_or((&[], &[])); 70 let live = Live::new(base.clone(), kinds, about); 71 State { placed: ids(&base, "placed").unwrap_or_default(), live, widgets, 72 safe: std::env::args().any(|a| a == "--safe").then(|| "You started the app with --safe.".into()), 73 builds: vec![], connected: false, sent: Instant::now(), started: Instant::now(), inbox: Default::default(), exe: None, built: None, ctrl: false, pointer: (0.0, 0.0), 74 picked: vec![], element: String::new(), rects: RefCell::new(vec![]), form: None, window: Default::default(), spare: rune::TextEdit::new("") } 75} 76 77/// Polls conveyord once a second on a thread. Every poll also re-renders, for clocks. 78pub fn setup(s: &mut State, waker: Waker) { 79 s.live.set_waker(waker.clone()); 80 s.exe = std::env::current_exe().ok(); 81 s.built = s.exe.as_deref().and_then(mtime); 82 let inbox = s.inbox.clone(); 83 std::thread::spawn(move || loop { 84 let asked = Instant::now(); 85 *inbox.lock().unwrap() = Some((asked, client::state())); 86 waker(); 87 std::thread::sleep(Duration::from_secs(1)); 88 }); 89} 90 91pub fn poll(s: &mut State, _t: f64, tx: &mut Tx) -> bool { 92 if s.safe.is_some() { return safe_poll(s, tx); } 93 let reloaded = s.widgets.poll().map(|(kinds, about)| s.live.reload(kinds, about)).is_some(); 94 let made = s.live.make_wanted(); 95 let mut again = made || reloaded; 96 if let Some((asked, snap)) = s.inbox.lock().unwrap().take() { 97 s.connected = snap.is_some(); 98 if let Some(snap) = snap.filter(|_| asked > s.sent) { 99 s.live.data = client::data(&snap); 100 s.builds = client::builds(&snap); 101 } 102 s.live.data.connected = s.connected; 103 again = true; 104 } 105 if !made && s.started.elapsed() > Duration::from_secs(2) { place(s); } else { tx.wake_after(Duration::from_millis(500)); } 106 again |= s.live.update(); 107 for r in s.live.take_outbox() { 108 s.sent = Instant::now(); 109 client::send(r); 110 } 111 s.live.save(); 112 if s.live.animating() { tx.wake_after(Duration::from_millis(16)); } 113 restart(s); 114 safe::check(s); 115 let ctrl = s.ctrl; 116 on_modifiers(s, tx.mods(), tx); 117 again || ctrl != s.ctrl 118} 119 120/// In safe mode only conveyord's news comes in: no widget code runs, and no new build loads. 121fn safe_poll(s: &mut State, tx: &mut Tx) -> bool { 122 if let Some((_, snap)) = s.inbox.lock().unwrap().take() { 123 s.connected = snap.is_some(); 124 if let Some(snap) = snap { s.builds = client::builds(&snap); } 125 } 126 for r in s.live.take_outbox() { client::send(r); } 127 s.live.save(); 128 restart(s); 129 tx.wake_after(Duration::from_millis(500)); 130 true 131} 132 133/// Places the new widgets each build on trial asked for (`conveyor place <kind> --in <id>`), 134/// once: at the click, when that instance was clicked or is one of its parents. 135fn place(s: &mut State) { 136 if s.builds.is_empty() || s.live.kind("root").is_none() { return; } 137 let first_run = !s.live.base().join("placed").exists(); 138 for b in s.builds.clone().iter().filter(|b| b["state"] == "review" || b["state"] == "done") { 139 if !s.placed.insert(b["id"].as_u64().unwrap_or(0)) || first_run { continue; } 140 let at = |id: &str| b["targets"].as_array().into_iter().flatten().find(|t| t[0] == id) 141 .map_or((40.0, 40.0), |t| (t[1].as_f64().unwrap_or(40.0) as f32, t[2].as_f64().unwrap_or(40.0) as f32)); 142 for p in b["place"].as_array().into_iter().flatten() { 143 let (kind, id) = (p[0].as_str().unwrap_or(""), p[1].as_str().unwrap_or("")); 144 if !s.live.mount(id, at(id), kind) { eprintln!("`{id}` didn't keep the new `{kind}`"); } 145 } 146 } 147 save_ids(s.live.base(), "placed", &s.placed); 148} 149 150/// conveyord rebuilt the app itself (a change to conveyor, not to the widgets): become the 151/// new binary, in place. 152fn restart(s: &mut State) { 153 let Some(exe) = &s.exe else { return }; 154 let Some(t) = mtime(exe) else { return }; 155 if Some(t) == s.built { return; } 156 use std::os::unix::process::CommandExt; 157 let err = std::process::Command::new(exe).args(std::env::args().skip(1)).exec(); 158 eprintln!("restart failed: {err}"); 159 s.built = Some(t); 160} 161 162/// Ctrl went down or up. Rune's desktop host doesn't call `App::on_modifiers` yet (window.rs 163/// never hands it to the runtime), so pointer moves and polls also report Ctrl here. 164pub fn on_modifiers(s: &mut State, mods: rune::Mods, tx: &mut Tx) { 165 if mods.ctrl == s.ctrl { return; } 166 s.ctrl = mods.ctrl; 167 if s.ctrl { inspect::pick(s, tx); } 168} 169 170/// A paste with no text field focused goes to the widgets; an image is saved as a PNG first. 171fn paste(s: &mut State, c: &rune::ClipboardContent, _: &mut Tx) { 172 let image = c.image().and_then(|img| { 173 let dir = s.live.base().join("clips"); 174 let path = dir.join(format!("{}.png", (crate::api::now() * 1000.0) as u64)); 175 std::fs::create_dir_all(&dir).ok()?; 176 std::fs::write(&path, img.png()).ok()?; 177 Some(path) 178 }); 179 if !s.live.event(&Event::Paste { text: c.text().to_owned(), image }) { eprintln!("no widget took the paste"); } 180} 181 182pub fn view(s: &State, rcx: &mut rune::Cx<State>) -> El { 183 if let Some(why) = &s.safe { return safe::view(s, why); } 184 if let Some(r) = rcx.layout("app") { s.window.set((r[2], r[3])); } 185 let mut app = el().key("app").w_full().h_full() 186 .on_paste_content(paste) 187 .on_drop_files(|s: &mut State, files: &[PathBuf], _: &mut Tx| { s.live.event(&Event::Drop(files.to_vec())); }) 188 .child(el().key("content").w_full().h_full().child(s.live.render("root", "root")) 189 .on_pointer_move_local(|s: &mut State, e: rune::PointerEvent, tx: &mut Tx| { 190 s.pointer = (e.window_x, e.window_y); 191 if tx.mods().ctrl { on_modifiers(s, tx.mods(), tx) } else { tx.live_only() } 192 })); 193 app = app.child(el().key("status-layer").absolute(0.0, 0.0).w_full().h_full().child(s.live.render("status", "status"))); 194 if s.ctrl && s.form.is_none() { app = app.child(inspect::view(s, rcx)); } 195 if let Some(f) = &s.form { app = app.child(form::view(s, f, rcx)); } 196 app 197}