5d4a2c8fe1
- Explorer: every non-hidden file is listed with its own icon and tab kind (image, video, audio, pdf, code, text, other); settings show_all_types, hidden_extensions and show_annotation_files; kinds without a viewer open a placeholder card, never the text editor - crates/annotate: non-destructive image annotations (strokes, lines, rectangles, ellipses, text) with strict sidecar JSON validation, hit testing, zoom/pan transforms and undo - engine: file.info, file.hash, file.neighbours, image.annotations.load and save (a corrupt sidecar is kept as .bad, the image is never modified), header-only image sizing for PNG, JPEG, GIF, WebP, BMP and SVG - sync server: publish notes or folders as static HTML (raw HTML escaped, strict CSP, publish: false honoured, no attachments) and expiring revocable share links, with per-route rate limits and audit rows - ui-egui: "Last edit - name, time ago" in the status bar from server.file_meta - specs and designs: file viewers spec, 20 PaperCraft exports rated 8.2 of 10 (design/files/RATING.md), annotate and viewer briefs Verified with cargo xtask ci (fmt, clippy -D warnings, workspace tests, layers, tree, i18n). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
389 lines
16 KiB
Rust
389 lines
16 KiB
Rust
//! The "Last edit - Ana, 2 min ago" line of the status bar, driven the way a
|
|
//! user does: real frames over a vault bound to a stub server. One `GET
|
|
//! /v1/vaults/{v}/files-meta/{path}` lookup belongs to one opened note; the
|
|
//! cache answers a re-open within 30 s without a new request, a failure keeps
|
|
//! the old line, and the token of the account never reaches the screen.
|
|
|
|
use egui::{Context, Pos2, RawInput};
|
|
use notescraft_engine::{Session, bind_folder};
|
|
use notescraft_ui_egui::app::NotesApp;
|
|
use std::io::{BufRead, BufReader, Read, Write};
|
|
use std::net::{TcpListener, TcpStream};
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
|
|
|
static NEXT: AtomicU64 = AtomicU64::new(0);
|
|
/// The window of a desktop; the status bar is wide enough up here.
|
|
const DESKTOP: egui::Vec2 = egui::vec2(1280.0, 800.0);
|
|
/// A width below the status bar's own narrow cut (420 pt).
|
|
const NARROW: egui::Vec2 = egui::vec2(400.0, 800.0);
|
|
/// The token of the bound vault; it must never reach the screen.
|
|
const TOKEN: &str = "secret-token";
|
|
/// Longest the tests wait for a stub request.
|
|
const WAIT: Duration = Duration::from_secs(5);
|
|
|
|
/// What the stub answers for the files-meta note look-ups.
|
|
#[derive(Clone)]
|
|
enum Meta {
|
|
/// Ana wrote it about 2 min ago, forever.
|
|
Named,
|
|
/// The server does not know the note: 404.
|
|
Unknown,
|
|
/// The first `first` look-ups answer Ana, the rest fail with 500.
|
|
ThenFail(u32),
|
|
}
|
|
|
|
/// One request the stub received.
|
|
#[derive(Debug, Clone)]
|
|
struct Seen {
|
|
/// The HTTP method.
|
|
method: String,
|
|
/// The path of the request line, without the query.
|
|
path: String,
|
|
}
|
|
|
|
/// A stub server: canned answers per path and method, every request it saw and a plan for the meta look-ups.
|
|
struct Stub {
|
|
base: String,
|
|
seen: Arc<Mutex<Vec<Seen>>>,
|
|
stop: Arc<AtomicBool>,
|
|
}
|
|
|
|
impl Stub {
|
|
/// Starts a stub on an ephemeral port: `/changes` answers an empty log and
|
|
/// `/files/*.md` answers applied, so the worker's cycle lands on "Synced".
|
|
fn spawn(meta: Meta) -> Self {
|
|
let listener = TcpListener::bind("127.0.0.1:0").expect("bind the stub");
|
|
let port = listener.local_addr().expect("addr").port();
|
|
let record = r#"{"path":"a.md","hash":"x","size":2,"mtime_ms":0,"seq":1,"deleted":false}"#;
|
|
let empty = r#"{"head":0,"records":[],"more":false}"#;
|
|
let answer = |status: &str, body: &str| format!("HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", body.len());
|
|
let answers: Vec<(String, String, String)> = vec![
|
|
("GET".to_owned(), "/changes".to_owned(), answer("200 OK", empty)),
|
|
("PUT".to_owned(), "/files/a.md".to_owned(), answer("201 Created", record)),
|
|
("PUT".to_owned(), "/files/b.md".to_owned(), answer("201 Created", record)),
|
|
];
|
|
let meta_json = format!(r#"{{"editor_name":"Ana","editor_user":"u-2","seq":3,"mtime_ms":{}}}"#, now_ms() - 120_000);
|
|
let seen: Arc<Mutex<Vec<Seen>>> = Arc::new(Mutex::new(Vec::new()));
|
|
let stop = Arc::new(AtomicBool::new(false));
|
|
let lookups = Arc::new(AtomicU32::new(0));
|
|
let (thread_seen, thread_stop) = (Arc::clone(&seen), Arc::clone(&stop));
|
|
std::thread::spawn(move || {
|
|
while !thread_stop.load(Ordering::Relaxed) {
|
|
match listener.accept() {
|
|
Ok((stream, _)) => {
|
|
// One thread per connection: the client may keep the
|
|
// connection open, and the listener must go on accepting.
|
|
if stream.set_nonblocking(false).is_ok() {
|
|
let Ok(mut writer) = stream.try_clone() else { continue };
|
|
let mut reader = BufReader::new(stream);
|
|
let answers = Arc::new(answers.clone());
|
|
let seen = Arc::clone(&thread_seen);
|
|
let lookups = Arc::clone(&lookups);
|
|
let meta = meta.clone();
|
|
let meta_json = meta_json.clone();
|
|
std::thread::spawn(move || {
|
|
while let Some(request) = read_request(&mut reader) {
|
|
seen.lock().expect("seen").push(request.clone());
|
|
let canned = if request.method == "GET" && request.path.contains("/files-meta/") {
|
|
let count = lookups.fetch_add(1, Ordering::Relaxed);
|
|
meta_answer(&meta, count, &meta_json)
|
|
} else {
|
|
answers
|
|
.iter()
|
|
.find(|(method, path, _)| *method == request.method && request.path.contains(path.as_str()))
|
|
.map_or("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n", |(_, _, canned)| canned.as_str())
|
|
.to_owned()
|
|
};
|
|
let _ = writer.write_all(canned.as_bytes());
|
|
let _ = writer.flush();
|
|
}
|
|
});
|
|
}
|
|
}
|
|
Err(_) => std::thread::sleep(Duration::from_millis(2)),
|
|
}
|
|
}
|
|
});
|
|
Self { base: format!("http://127.0.0.1:{port}"), seen, stop }
|
|
}
|
|
|
|
/// How many times the stub was asked for the meta of `path`.
|
|
fn meta_requests(&self, path: &str) -> usize {
|
|
self.seen.lock().expect("seen").iter().filter(|seen| seen.method == "GET" && seen.path.ends_with(&format!("/files-meta/{path}"))).count()
|
|
}
|
|
|
|
/// Waits, bounded, until the count passes.
|
|
fn wait_for_meta(&self, path: &str, wanted: usize) {
|
|
let deadline = Instant::now() + WAIT;
|
|
while Instant::now() < deadline && self.meta_requests(path) < wanted {
|
|
std::thread::sleep(Duration::from_millis(5));
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Drop for Stub {
|
|
fn drop(&mut self) {
|
|
self.stop.store(true, Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
/// The canned answer of the `count`-th meta look-up (`count` counts from 0): status and body in one string.
|
|
fn meta_answer(meta: &Meta, count: u32, meta_json: &str) -> String {
|
|
let body_for = |status: &str, body: &str| format!("HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", body.len());
|
|
match meta {
|
|
Meta::Named => body_for("200 OK", meta_json),
|
|
Meta::Unknown => body_for("404 Not Found", ""),
|
|
Meta::ThenFail(first) if count < *first => body_for("200 OK", meta_json),
|
|
Meta::ThenFail(_) => body_for("500 Internal Server Error", ""),
|
|
}
|
|
}
|
|
|
|
/// Reads one request: method, path, and its body skipped; the request ends when
|
|
/// the client closes the connection.
|
|
fn read_request(reader: &mut BufReader<TcpStream>) -> Option<Seen> {
|
|
let mut line = String::new();
|
|
reader.read_line(&mut line).ok()?;
|
|
let mut parts = line.split_whitespace();
|
|
let method = parts.next()?.to_owned();
|
|
let path = parts.next()?.to_owned();
|
|
let mut length = 0_usize;
|
|
loop {
|
|
let mut header = String::new();
|
|
if reader.read_line(&mut header).ok()? == 0 {
|
|
break;
|
|
}
|
|
if header.trim_end().is_empty() {
|
|
break;
|
|
}
|
|
if let Some((name, value)) = header.trim_end().split_once(':')
|
|
&& name.trim().eq_ignore_ascii_case("content-length")
|
|
{
|
|
length = value.trim().parse().unwrap_or(0);
|
|
}
|
|
}
|
|
let mut body = vec![0_u8; length];
|
|
if length > 0 {
|
|
reader.read_exact(&mut body).ok()?;
|
|
}
|
|
Some(Seen { method, path: path.split('?').next().unwrap_or_default().to_owned() })
|
|
}
|
|
|
|
struct Driver {
|
|
app: NotesApp,
|
|
ctx: Context,
|
|
time: f64,
|
|
size: egui::Vec2,
|
|
}
|
|
|
|
/// A painted text: what it says, where it starts and its galley.
|
|
/// A painted text, what it says.
|
|
#[derive(Debug)]
|
|
struct Painted {
|
|
text: String,
|
|
}
|
|
|
|
/// A place the driver made: the vault root and the config beside it.
|
|
struct Driven {
|
|
driver: Driver,
|
|
root: PathBuf,
|
|
config: PathBuf,
|
|
}
|
|
|
|
/// An app over a fresh vault bound to `stub`, with a note open; the settings
|
|
/// dir lives beside the vault, never inside it (the vault is the sync scope).
|
|
fn driven(stub: &Stub, bound: bool, size: egui::Vec2) -> Driven {
|
|
let root = std::env::temp_dir().join(format!("notescraft-last-edit-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
|
let _ = std::fs::remove_dir_all(&root);
|
|
std::fs::create_dir_all(&root).expect("root");
|
|
seed(&root, &[("a.md", "A"), ("b.md", "B")]);
|
|
if bound {
|
|
bind_folder(&root, &stub.base, "v-1", TOKEN, "d-1", Some("u-1")).expect("bind the vault");
|
|
}
|
|
let config = settings_dir(&root);
|
|
Driven { driver: app_for(&root, size), root, config }
|
|
}
|
|
|
|
/// Writes `(path, content)` into `root`, creating the folders.
|
|
fn seed(root: &Path, files: &[(&str, &str)]) {
|
|
for (path, text) in files {
|
|
if let Some((folder, _)) = path.rsplit_once('/') {
|
|
std::fs::create_dir_all(root.join(folder)).expect("folder");
|
|
}
|
|
std::fs::write(root.join(path), text).expect("seed");
|
|
}
|
|
}
|
|
|
|
/// The settings dir beside `root`; the vault never holds the settings (SPEC 4.1).
|
|
fn settings_dir(root: &Path) -> PathBuf {
|
|
root.parent().unwrap_or(root).join("notescraft-last-edit-config")
|
|
}
|
|
|
|
/// An app over an already seeded and bound vault at `root`.
|
|
fn app_for(root: &Path, size: egui::Vec2) -> Driver {
|
|
let mut session = Session::open(root).expect("session");
|
|
session.use_settings_dir(settings_dir(root));
|
|
let mut app = NotesApp::new(session, notescraft_themes::builtin("catppuccin-mocha").expect("theme"));
|
|
app.state.animations = false;
|
|
app.open_note("a.md");
|
|
Driver { app, size, ctx: Context::default(), time: 1.0 }
|
|
}
|
|
|
|
impl Driver {
|
|
/// One frame; the texts it painted.
|
|
fn frame(&mut self) -> Vec<Painted> {
|
|
self.time += 0.05;
|
|
let input = RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, self.size)), time: Some(self.time), ..Default::default() };
|
|
let app = &mut self.app;
|
|
let mut out = self.ctx.run_ui(input, |ui| app.ui(ui.ctx()));
|
|
out.textures_delta.clear();
|
|
out.shapes
|
|
.iter()
|
|
.filter_map(|shape| match &shape.shape {
|
|
egui::Shape::Text(text) => Some(Painted { text: text.galley.text().to_owned() }),
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// A run of frames without input, so the shell ticks and the worker answers land.
|
|
fn settle(&mut self) -> Vec<Painted> {
|
|
let mut last = Vec::new();
|
|
for _ in 0..24 {
|
|
last = self.frame();
|
|
}
|
|
last
|
|
}
|
|
|
|
/// Keeps settling until the painted line mentions `wanted`; also returns the last texts.
|
|
fn wait_for_line(&mut self, wanted: &str) -> Vec<Painted> {
|
|
let mut texts = self.settle();
|
|
for _ in 0..40 {
|
|
if texts.iter().any(|painted| painted.text.contains(wanted)) {
|
|
break;
|
|
}
|
|
texts = self.frame();
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
texts
|
|
}
|
|
}
|
|
|
|
/// The painted texts that mention the note's last edit.
|
|
fn edits(texts: &[Painted]) -> Vec<&str> {
|
|
texts.iter().map(|painted| painted.text.as_str()).filter(|text| text.contains("Last edit")).collect()
|
|
}
|
|
|
|
/// The Unix time now, in milliseconds.
|
|
fn now_ms() -> u64 {
|
|
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| u64::try_from(since.as_millis()).unwrap_or(u64::MAX))
|
|
}
|
|
|
|
fn clean(root: &Path, config: &Path) {
|
|
let _ = std::fs::remove_dir_all(root);
|
|
let _ = std::fs::remove_dir_all(config);
|
|
}
|
|
|
|
#[test]
|
|
fn the_line_shows_the_last_editor_after_the_note_opens() {
|
|
let stub = Stub::spawn(Meta::Named);
|
|
let Driven { mut driver, root, config } = driven(&stub, true, DESKTOP);
|
|
stub.wait_for_meta("a.md", 1);
|
|
let texts = driver.wait_for_line("Last edit - Ana");
|
|
assert_eq!(edits(&texts), ["Last edit - Ana, 2 min ago"], "the line shows: {:?}", edits(&texts));
|
|
assert!(!texts.iter().any(|painted| painted.text.contains(TOKEN)), "the token never reaches the screen");
|
|
drop(driver);
|
|
clean(&root, &config);
|
|
}
|
|
|
|
#[test]
|
|
fn an_unknown_answer_shows_no_line() {
|
|
let stub = Stub::spawn(Meta::Unknown);
|
|
let Driven { mut driver, root, config } = driven(&stub, true, DESKTOP);
|
|
stub.wait_for_meta("a.md", 1);
|
|
let texts = driver.settle();
|
|
assert_eq!(edits(&texts), [] as [&str; 0], "no line without a known author: {:?}", edits(&texts));
|
|
drop(driver);
|
|
clean(&root, &config);
|
|
}
|
|
|
|
#[test]
|
|
fn an_unbound_vault_never_asks_a_server() {
|
|
let stub = Stub::spawn(Meta::Named);
|
|
let Driven { mut driver, root, config } = driven(&stub, false, DESKTOP);
|
|
driver.settle();
|
|
driver.settle();
|
|
let meta_total = stub.seen.lock().expect("seen").iter().filter(|seen| seen.path.contains("/files-meta/")).count();
|
|
assert_eq!(
|
|
meta_total,
|
|
0,
|
|
"no look-up without a bound vault: {}",
|
|
stub.seen.lock().expect("seen").iter().map(|seen| seen.path.as_str()).collect::<Vec<_>>().join(", ")
|
|
);
|
|
assert_eq!(edits(&driver.settle()), [] as [&str; 0]);
|
|
drop(driver);
|
|
clean(&root, &config);
|
|
}
|
|
|
|
#[test]
|
|
fn a_second_note_triggers_its_own_request() {
|
|
let stub = Stub::spawn(Meta::Named);
|
|
let Driven { mut driver, root, config } = driven(&stub, true, DESKTOP);
|
|
driver.settle();
|
|
stub.wait_for_meta("a.md", 1);
|
|
driver.app.open_note("b.md");
|
|
let texts = driver.wait_for_line("Last edit - Ana");
|
|
assert_eq!(stub.meta_requests("a.md"), 1, "a.md: no extra look-up");
|
|
assert!(stub.meta_requests("b.md") >= 1, "b.md was looked up itself");
|
|
assert_eq!(edits(&texts), ["Last edit - Ana, 2 min ago"]);
|
|
drop(driver);
|
|
clean(&root, &config);
|
|
}
|
|
|
|
#[test]
|
|
fn the_cache_serves_a_reopen_without_a_new_request() {
|
|
let stub = Stub::spawn(Meta::Named);
|
|
let Driven { mut driver, root, config } = driven(&stub, true, DESKTOP);
|
|
stub.wait_for_meta("a.md", 1);
|
|
driver.wait_for_line("Last edit - Ana");
|
|
driver.app.open_note("b.md");
|
|
stub.wait_for_meta("b.md", 1);
|
|
driver.settle();
|
|
let before = stub.meta_requests("a.md");
|
|
driver.app.open_note("a.md");
|
|
let texts = driver.wait_for_line("Last edit - Ana");
|
|
assert_eq!(stub.meta_requests("a.md"), before, "the cache answered the re-open");
|
|
assert_eq!(edits(&texts), ["Last edit - Ana, 2 min ago"], "the line came back at once");
|
|
drop(driver);
|
|
clean(&root, &config);
|
|
}
|
|
|
|
#[test]
|
|
fn a_failure_keeps_the_old_line() {
|
|
let stub = Stub::spawn(Meta::ThenFail(1));
|
|
let Driven { mut driver, root, config } = driven(&stub, true, DESKTOP);
|
|
stub.wait_for_meta("a.md", 1);
|
|
driver.settle();
|
|
assert_eq!(edits(&driver.wait_for_line("Last edit - Ana")), ["Last edit - Ana, 2 min ago"]);
|
|
// A sync cycle finishes: the visible note is looked up again, the stub now fails.
|
|
driver.app.run_command("sync.now", &serde_json::Value::Null);
|
|
stub.wait_for_meta("a.md", 2);
|
|
let texts = driver.settle();
|
|
assert_eq!(edits(&texts), ["Last edit - Ana, 2 min ago"], "a failure keeps the old line: {:?}", edits(&texts));
|
|
drop(driver);
|
|
clean(&root, &config);
|
|
}
|
|
|
|
#[test]
|
|
fn the_line_hides_at_a_narrow_width() {
|
|
let stub = Stub::spawn(Meta::Named);
|
|
let Driven { mut driver, root, config } = driven(&stub, true, NARROW);
|
|
stub.wait_for_meta("a.md", 1);
|
|
let texts = driver.settle();
|
|
assert!(!texts.iter().any(|painted| painted.text.contains("Last edit")), "hidden below 420 pt: {:?}", edits(&texts));
|
|
drop(driver);
|
|
clean(&root, &config);
|
|
}
|