mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 12:44:11 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd5efdc0d4 |
No files matched your search
@@ -55,11 +55,6 @@ fn said(l: &Value) -> String {
|
||||
"result" => format!("a result{on}: {text}"),
|
||||
"correction" => format!("a correction{on}: {text}"),
|
||||
"sign" => format!("a sign-off{on} (ask {})", l["ask"]),
|
||||
// a show only to be looked at (raea show --fyi), looked at: Got it, with a word or none
|
||||
"seen" => {
|
||||
let word = text.strip_prefix("Seen").unwrap_or(&text).trim_start_matches(':').trim();
|
||||
if word.is_empty() { format!("seen{on}") } else { format!("seen{on}: {word}") }
|
||||
}
|
||||
k => format!("{}{on}: {text}", if k.is_empty() { "something" } else { k }),
|
||||
};
|
||||
format!("- {what}")
|
||||
@@ -73,17 +68,6 @@ pub fn told(agent: &str, v: &Value) -> Option<String> {
|
||||
return None;
|
||||
}
|
||||
let list = lines.iter().map(said).collect::<Vec<_>>().join("\n");
|
||||
// only Got it on what was shown to look at: nothing to take up
|
||||
if !lines.iter().any(|l| l["kind"] != "seen") {
|
||||
return Some(format!("raea: the person has looked at what you showed them (your inbox, ~/.raea/inbox/{inbox}.jsonl):\n{list}\nNothing to do about it; carry on."));
|
||||
}
|
||||
// a session started again (resumed) after the person wrote to it while it was closed (Shane 11-28: "notes reach
|
||||
// closed sessions"): what waited is handed over before anything else
|
||||
if v["hook_event_name"].as_str() == Some("SessionStart") {
|
||||
return Some(format!(
|
||||
"raea: while this session was closed, the person sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up first, before anything else. Answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
|
||||
));
|
||||
}
|
||||
Some(format!(
|
||||
"raea: the person just sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up now, before going on: it may change what you're doing. What you say next shows under your session in their feed; answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
|
||||
))
|
||||
@@ -94,17 +78,11 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// an empty inbox folder of the test's own
|
||||
fn scratch(tag: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("raea-inbox-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
|
||||
let d = scratch("once");
|
||||
let d = std::env::temp_dir().join(format!("raea-inbox-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let f = d.join("claude-code-abcd1234.jsonl");
|
||||
std::fs::write(&f, "{\"kind\":\"message\",\"text\":\"more epic\"}\n{\"kind\":\"no").unwrap();
|
||||
let first = unread(&d, "claude-code-abcd1234");
|
||||
@@ -119,25 +97,6 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seen_is_said_as_seen_and_asks_nothing() {
|
||||
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen"})), "- seen on item i-2 \"Lobby\"");
|
||||
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen: lovely"})), "- seen on item i-2 \"Lobby\": lovely");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_waited_while_it_was_closed_is_handed_over_as_it_starts_again() {
|
||||
let d = scratch("start");
|
||||
std::fs::write(d.join("claude-code-5e55a0ff.jsonl"), "{\"kind\":\"edits\",\"item\":\"i-9\",\"title\":\"Cut\",\"text\":\"tighter open\"}\n").unwrap();
|
||||
// SAFETY: tests in this crate don't read RAEA_INBOX_DIR concurrently
|
||||
unsafe { std::env::set_var("RAEA_INBOX_DIR", &d) };
|
||||
let start = told("claude", &json!({"hook_event_name": "SessionStart", "source": "resume", "session_id": "5e55a0ff-1"})).unwrap();
|
||||
assert!(start.starts_with("raea: while this session was closed") && start.contains("- edits on item i-9 \"Cut\":\ntighter open"), "{start}");
|
||||
assert_eq!(told("claude", &json!({"hook_event_name": "UserPromptSubmit", "session_id": "5e55a0ff-1"})), None, "handed over once");
|
||||
unsafe { std::env::remove_var("RAEA_INBOX_DIR") };
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_inbox_is_named_as_raea_show_names_it() {
|
||||
assert_eq!(name("claude", &json!({"session_id": "15cd6bb0-8829-466f-a28a-bbca3d35be92"})).as_deref(), Some("claude-code-15cd6bb0"));
|
||||
|
||||
@@ -148,13 +148,7 @@ pub fn hook(args: &[String]) -> R<String> {
|
||||
let event = v["hook_event_name"].as_str().unwrap_or("");
|
||||
// what the person sent from the raea app since the last look (inbox.rs): handed over after any tool, and a turn about
|
||||
// to end goes on to take it up
|
||||
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop" | "SessionStart" | "UserPromptSubmit") { crate::inbox::told(agent, &v) } else { None };
|
||||
// a session starting again, or the person writing to it in its terminal: what they sent from raea while it was
|
||||
// closed or idle goes in as context first (Claude Code's and Codex's SessionStart and UserPromptSubmit read
|
||||
// hookSpecificOutput.additionalContext)
|
||||
if matches!(event, "SessionStart" | "UserPromptSubmit") {
|
||||
return Ok(sent.map(|t| json!({"hookSpecificOutput": {"hookEventName": event, "additionalContext": t}}).to_string()).unwrap_or_default());
|
||||
}
|
||||
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop") { crate::inbox::told(agent, &v) } else { None };
|
||||
if event == "Stop" {
|
||||
// what the person sent, and a `make` job that isn't done (docs/make.feature MK2): either keeps the turn going
|
||||
let reasons: Vec<String> = [sent, raea_app_check_make::stop(&v)].into_iter().flatten().collect();
|
||||
|
||||
@@ -21,10 +21,8 @@ struct Hook {
|
||||
fn hooks(agent: &str) -> R<Vec<Hook>> {
|
||||
let h = |event, matcher, secs| Hook { event, matcher, secs };
|
||||
Ok(match agent {
|
||||
// SessionStart and UserPromptSubmit: notes sent from raea while the session was closed or idle reach it when it
|
||||
// starts again or is next written to (Shane 11-28: "notes reach closed sessions")
|
||||
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
|
||||
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
|
||||
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30)],
|
||||
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
|
||||
"gemini" => vec![h("BeforeTool", "run_shell_command", 30), h("AfterTool", "write_file|replace", 60)],
|
||||
"kimi" => vec![h("PreToolUse", "Bash|Shell", 30), h("PostToolUse", "Write|Edit|WriteFile|StrReplaceFile", 60)],
|
||||
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
|
||||
@@ -126,8 +124,7 @@ mod tests {
|
||||
let c = d.join("claude/settings.json");
|
||||
std::fs::create_dir_all(c.parent().unwrap()).unwrap();
|
||||
std::fs::write(&c, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]},{"matcher":"Write","hooks":[{"type":"command","command":"raea hook claude"}]}]}}"#).unwrap();
|
||||
let [pre, post, stop, start, prompt] = <[Hook; 5]>::try_from(hooks("claude").unwrap()).ok().unwrap();
|
||||
assert!(add_json(&c, "claude", &start).unwrap() && add_json(&c, "claude", &prompt).unwrap() && !add_json(&c, "claude", &start).unwrap());
|
||||
let [pre, post, stop] = <[Hook; 3]>::try_from(hooks("claude").unwrap()).ok().unwrap();
|
||||
assert!(add_json(&c, "claude", &pre).unwrap() && !add_json(&c, "claude", &pre).unwrap());
|
||||
assert!(add_json(&c, "claude", &post).unwrap() && !add_json(&c, "claude", &post).unwrap(), "an older raea's after-save hook is widened to every tool, once");
|
||||
assert!(add_json(&c, "claude", &stop).unwrap() && !add_json(&c, "claude", &stop).unwrap());
|
||||
@@ -136,9 +133,6 @@ mod tests {
|
||||
assert_eq!((v["hooks"]["PostToolUse"][0]["matcher"].as_str(), v["hooks"]["PostToolUse"][1]["matcher"].as_str()), (Some("Bash"), Some("*")));
|
||||
assert_eq!(v["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(v["hooks"]["Stop"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(v["hooks"]["SessionStart"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(v["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"], "raea hook claude");
|
||||
assert_eq!(hooks("codex").unwrap().iter().map(|h| h.event).collect::<Vec<_>>(), ["PreToolUse", "PostToolUse", "Stop", "SessionStart", "UserPromptSubmit"]);
|
||||
let g = d.join("gemini/settings.json");
|
||||
let [before, _] = <[Hook; 2]>::try_from(hooks("gemini").unwrap()).ok().unwrap();
|
||||
assert!(add_json(&g, "gemini", &before).unwrap());
|
||||
|
||||
@@ -110,41 +110,3 @@ describe("labelsIn", () => {
|
||||
expect(() => labelsIn('{"text":"a"}', "l.json")).toThrow(/--labels l.json is a list of labels/);
|
||||
});
|
||||
});
|
||||
|
||||
// Shane 11-28: "some things I'm not approving, I'm just acknowledging"; "the agent can go 'let me add a label here'".
|
||||
// --fyi and --group go to the host (apps/app host/show.ts ShowBody.intent, .groups), which hands them to the review.
|
||||
describe("raea show --fyi and --group", () => {
|
||||
const run = (args: string[]) => {
|
||||
const ops: [string, Record<string, unknown>][] = [];
|
||||
const ask = (op: string, b: Record<string, unknown>) => {
|
||||
ops.push([op, b]);
|
||||
if (op === "harness") return { name: "Claude Code", pid: 7 };
|
||||
return { kind: "item", id: "i-1", type: "look", title: "Lobby", project: "shop", workspace: "Work", inbox: "/inbox.jsonl" };
|
||||
};
|
||||
const out = showVerb(ask, args, "/work/shop", { CLAUDECODE: "1", CLAUDE_CODE_SESSION_ID: "abcdef123" });
|
||||
return { out, body: ops.find(([op]) => op === "show")?.[1] };
|
||||
};
|
||||
|
||||
test("--fyi sends a look-only show, and says nothing waits on it", () => {
|
||||
const { out, body } = run(["lobby.png", "--fyi"]);
|
||||
expect(body).toMatchObject({ intent: "fyi", files: ["/work/shop/lobby.png"] });
|
||||
expect(out).toContain(`{"kind":"seen"}`);
|
||||
expect(run(["lobby.png"]).body?.intent).toBeUndefined();
|
||||
});
|
||||
|
||||
test("each --group holds the files after it, titled before the colon and said after it", () => {
|
||||
const { body } = run(["--group", "Day: sun through the doors", "a.png", "b.png", "--group", "Night", "c.png", "--title", "Lobby"]);
|
||||
expect(body?.files).toEqual(["/work/shop/a.png", "/work/shop/b.png", "/work/shop/c.png"]);
|
||||
expect(body?.groups).toEqual([
|
||||
{ title: "Day", says: "sun through the doors", files: ["/work/shop/a.png", "/work/shop/b.png"] },
|
||||
{ title: "Night", files: ["/work/shop/c.png"] },
|
||||
]);
|
||||
expect(run(["a.png"]).body?.groups).toBeUndefined();
|
||||
});
|
||||
|
||||
test("a group with no files, or --fyi on a question, is refused", () => {
|
||||
expect(() => run(["a.png", "--group", "Empty"])).toThrow(/has no files/);
|
||||
expect(() => run(["--group", ": no title", "a.png"])).toThrow(/is a title/);
|
||||
expect(() => run(["--question", "Which?", "--choice", "A", "--choice", "B", "--fyi"])).toThrow(/--fyi/);
|
||||
});
|
||||
});
|
||||
+6
-29
@@ -27,12 +27,6 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
|
||||
lists them), a folder in the project, or a Copy reference from the app; a title only when it's the only one and
|
||||
this folder isn't in another project. Else the one this folder is in. Who's showing it: --as NAME [--role ROLE]
|
||||
[--inbox NAME], else your harness's.
|
||||
raea show FILE... --fyi
|
||||
Only for the person to look at, nothing to approve: they say Got it (you hear {"kind":"seen"}), and anything they
|
||||
want to say back comes through the chat. Without it a show is a version for them to approve or send notes on.
|
||||
raea show --group "Day: sun through the doors" A.png B.png --group "Night: practicals only" C.png [--title T]
|
||||
Lay the files out in groups the person sees side by side, each titled before the colon and said after it in a plain
|
||||
line (never shorthand); the files after a --group are its own. Keep it short: enough to know what each group is.
|
||||
raea show FILE... --despite CHECK "why"
|
||||
A render that still holds an error (raea findings --open lists them) isn't shown: fix it and render again, or say
|
||||
why it goes anyway, once per check; the person reads the why on the item. One let through at the render (raea render
|
||||
@@ -56,8 +50,8 @@ raea show FILE... --replaces ITEM --done ID...
|
||||
closes when the person retires it, never with --done. raea notes post sends all of these from the notes.
|
||||
`;
|
||||
|
||||
const WITH_VALUE = new Set(["--group", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
|
||||
const FLAGS = new Set(["--open", "--fyi"]);
|
||||
const WITH_VALUE = new Set(["--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
|
||||
const FLAGS = new Set(["--open"]);
|
||||
|
||||
/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
|
||||
* walks up its parents): any harness, not only the ones that mark their shells. */
|
||||
@@ -90,8 +84,6 @@ const hash = (s: string) => {
|
||||
return h.toString(36);
|
||||
};
|
||||
|
||||
const marking = (args: string[]) => args.includes("--working") || args.includes("--done");
|
||||
|
||||
export function parseShow(args: string[], cwd: string) {
|
||||
const one = (name: string) => {
|
||||
const i = args.lastIndexOf(name);
|
||||
@@ -103,19 +95,7 @@ export function parseShow(args: string[], cwd: string) {
|
||||
if (unknown) throw new Error(`no ${unknown} here\n${SHOW_USAGE}`);
|
||||
const abs = (f: string) => fromCwd(cwd, f);
|
||||
// --despite takes two: the check, then why
|
||||
const isFile = (a: string, i: number) => !a.startsWith("--") && !WITH_VALUE.has(args[i - 1] ?? "") && args[i - 2] !== "--despite";
|
||||
const files = args.filter(isFile).map(abs);
|
||||
// the groups in order: each --group "Title: what it is" holds the files after it, up to the next --group
|
||||
const groups: { title: string; says?: string; files: string[] }[] = [];
|
||||
args.forEach((a, i) => {
|
||||
if (a === "--group" && args[i + 1] !== undefined) {
|
||||
const [title, ...rest] = args[i + 1].split(":");
|
||||
if (!title.trim()) throw new Error(`--group "${args[i + 1]}" is a title, then what it is after a colon: --group "Night: practicals only"\n${SHOW_USAGE}`);
|
||||
groups.push({ title: title.trim(), ...(rest.join(":").trim() ? { says: rest.join(":").trim() } : {}), files: [] });
|
||||
} else if (groups.length && isFile(a, i)) groups.at(-1)!.files.push(abs(a));
|
||||
});
|
||||
const empty = groups.find((g) => !g.files.length);
|
||||
if (empty) throw new Error(`the group "${empty.title}" has no files: put its files after its --group\n${SHOW_USAGE}`);
|
||||
const files = args.filter((a, i) => !a.startsWith("--") && !WITH_VALUE.has(args[i - 1] ?? "") && args[i - 2] !== "--despite").map(abs);
|
||||
const despite = args.flatMap((a, i) => {
|
||||
if (a !== "--despite") return [];
|
||||
const [check, why] = [args[i + 1], args[i + 2]];
|
||||
@@ -154,8 +134,7 @@ export function parseShow(args: string[], cwd: string) {
|
||||
if ((labels.length || args.includes("--labels")) && (!files.length || questions || asked.length)) throw new Error(`labels go on the files you show: raea show FILE --label "PLACE TAG"\n${SHOW_USAGE}`);
|
||||
if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`);
|
||||
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
|
||||
if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`);
|
||||
return { groups, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
|
||||
return { labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
|
||||
}
|
||||
|
||||
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
|
||||
@@ -210,7 +189,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
|
||||
if (a.done.length && !a.replaces) throw new Error(`--done with files settles comments on the item they replace: add --replaces ITEM\n${SHOW_USAGE}`);
|
||||
if (a.labelsFile !== undefined && !listed) throw new Error(`--labels ${a.labelsFile}: its labels weren't read (raea's own handler reads the file)`);
|
||||
const labels = a.labels.length ? a.labels : listed;
|
||||
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
|
||||
const r = ask("show", { ...(labels?.length ? { labels } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
|
||||
| { opened: string[] }
|
||||
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean };
|
||||
if ("opened" in r) return `The raea app isn't on this Mac, so ${r.opened.length === 1 ? "it opened" : `${r.opened.length} files opened`} in the Mac's own viewer: nothing was posted and nothing comes back. Install raea (raea.io) to show work as items the person can answer.\n`;
|
||||
@@ -234,9 +213,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
|
||||
? `Shown in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}); the window is on it.`
|
||||
: `Posted in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}), with a notice; the window stayed where the person is.`,
|
||||
...settled,
|
||||
a.fyi
|
||||
? `Only to look at: when they've seen it, {"kind":"seen"} comes to ${inbox}; nothing to wait for.`
|
||||
: `What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
|
||||
`What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
+1
-1
Submodule skills updated: 5b6bd192bd...98de983bca.
@@ -165,8 +165,7 @@ impl Ctx<'_> {
|
||||
if let Some(p) = self.images.get(src) {
|
||||
return Some(p.clone());
|
||||
}
|
||||
// inline (data:), else the picture's file (a page's /media/: the host's roots, as its videos)
|
||||
let (mime, bytes) = raea_io_net::data_url(src).or_else(|| crate::image_file(src))?;
|
||||
let (mime, bytes) = raea_io_net::data_url(src)?;
|
||||
let mime = mime.as_str();
|
||||
let img = if mime == "image/svg+xml" {
|
||||
let size = crate::svg::natural_size(&bytes, self.opt)?;
|
||||
|
||||
@@ -84,8 +84,8 @@ impl Replay {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a canvas's videos' and pictures' files are, for a host that draws canvases (raea-page's Blitz page: the page's
|
||||
/// roots, so a /media/ src is the project's file); until one is given a src is read as a file path.
|
||||
/// Where a canvas's videos' files are, for a host that draws canvases (raea-page's Blitz page: the page's roots); until
|
||||
/// one is given a video's src is read as a file path.
|
||||
pub fn videos(find: fn(&str) -> Option<std::path::PathBuf>) {
|
||||
*VIDEO_PATHS.write().unwrap() = Some(find);
|
||||
}
|
||||
@@ -140,34 +140,9 @@ pub(crate) fn page_options() -> usvg::Options<'static> {
|
||||
db.map_or_else(usvg::Options::default, |db| page_fonts(&db))
|
||||
}
|
||||
|
||||
/// Where a video's or a picture's src is as a file, for drawing it on a canvas (`videos`).
|
||||
/// Where a video's src is as a file, for its frames drawn on a canvas (`videos`).
|
||||
static VIDEO_PATHS: std::sync::RwLock<Option<fn(&str) -> Option<std::path::PathBuf>>> = std::sync::RwLock::new(None);
|
||||
|
||||
/// A src as a file: by the host's roots (`videos`), else as a path (a file:// URL's too).
|
||||
fn media_file(src: &str) -> Option<std::path::PathBuf> {
|
||||
match *VIDEO_PATHS.read().unwrap() {
|
||||
Some(f) => f(src),
|
||||
None => Some(std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture that isn't inline, read from its file, with its type by its name: drawImage of an <img> or new Image()
|
||||
/// whose src is the project's /media/ file (raea #253: the card's screenshot drew nothing, as only data: URLs were
|
||||
/// decoded).
|
||||
pub(crate) fn image_file(src: &str) -> Option<(String, Vec<u8>)> {
|
||||
let path = media_file(src)?;
|
||||
let mime = match path.extension()?.to_str()?.to_ascii_lowercase().as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"webp" => "image/webp",
|
||||
"gif" => "image/gif",
|
||||
"bmp" => "image/bmp",
|
||||
"svg" => "image/svg+xml",
|
||||
_ => return None,
|
||||
};
|
||||
Some((mime.to_string(), std::fs::read(path).ok()?))
|
||||
}
|
||||
|
||||
/// A video's frame at `t`, as a pixmap: opened and decoded on the CPU when it's asked for (a histogram reads one frame
|
||||
/// per seek), the last few kept.
|
||||
fn video_frame(src: &str, t: f64) -> Option<sk::Pixmap> {
|
||||
@@ -175,7 +150,10 @@ fn video_frame(src: &str, t: f64) -> Option<sk::Pixmap> {
|
||||
if let Some((.., pm)) = FRAMES.lock().unwrap().iter().find(|(s, b, _)| s == src && *b == t.to_bits()) {
|
||||
return Some(pm.clone());
|
||||
}
|
||||
let path = media_file(src)?;
|
||||
let path = match *VIDEO_PATHS.read().unwrap() {
|
||||
Some(f) => f(src)?,
|
||||
None => std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src)),
|
||||
};
|
||||
let frame = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(&path).ok()?.frame_at(t).ok())?;
|
||||
let mut pm = sk::Pixmap::new(frame.width, frame.height)?;
|
||||
for (i, px) in pm.pixels_mut().iter_mut().enumerate() {
|
||||
@@ -231,29 +209,6 @@ mod tests {
|
||||
assert_eq!(at(2, 2).alpha(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_from_a_file_is_drawn() {
|
||||
// raea #253: drawImage of a picture whose src is a file (a page's /media/, found by the host's roots) drew nothing
|
||||
let dir = std::env::temp_dir().join(format!("raea-canvas-pic-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut pic = sk::Pixmap::new(3, 2).unwrap();
|
||||
pic.fill(sk::Color::from_rgba8(0, 0, 210, 255));
|
||||
let file = dir.join("shot.png");
|
||||
pic.save_png(&file).unwrap();
|
||||
let opt = usvg::Options::default();
|
||||
let mut pm = sk::Pixmap::new(10, 10).unwrap();
|
||||
let mut cx = Ctx { opt: &opt, images: HashMap::new() };
|
||||
let st = serde_json::json!({"ts": [1, 0, 0, 1, 0, 0], "alpha": 1, "comp": "source-over", "clip": [], "shadow": null, "smooth": false});
|
||||
let src = file.to_string_lossy().to_string();
|
||||
cx.op(&mut pm, &serde_json::json!(["image", src, null, null, null, null, 2, 2, 6, 4, st]));
|
||||
assert_eq!(pm.pixel(4, 4).unwrap().demultiply().blue(), 210, "the picture is drawn");
|
||||
assert_eq!(pm.pixel(1, 1).unwrap().alpha(), 0, "only where it was asked to go");
|
||||
// a file that isn't a picture, or isn't there, draws nothing and doesn't panic
|
||||
cx.op(&mut pm, &serde_json::json!(["image", dir.join("none.png").to_string_lossy(), null, null, null, null, 0, 0, 10, 10, st]));
|
||||
assert_eq!(pm.pixel(1, 1).unwrap().alpha(), 0);
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_under_a_scale() {
|
||||
// Excalidraw's way: a 4x4 picture drawn at 2x size under a 0.5 transform covers 4x4 pixels at (2, 2)
|
||||
|
||||
Reference in new issue
Block a user