Skip to content

Free open-source image editor for the browser

Keep exports through a photo switch, and save the Remove fields a snapshot lacks (#79)

Rodrigo Belfioref941751a8493
diff --git a/API.md b/API.md
index e429c94..238fdf2 100644
--- a/API.md
+++ b/API.md
@@ -66,7 +66,7 @@ Create an empty Heal effect with `addLayer("heal")`.
`addHealStroke(id, patchId, stroke)` appends a painted or erased `BrushStroke` to an existing patch as one undoable edit. It preserves the mode, donor, feather, and opacity. Feather is a patch-wide blend based on the first stroke's diameter, shared by later additions. All patches expose an ordered `strokes` array; each path stays separate, coverage is combined on the GPU, and moving the patch moves paint and erase together. In the editor, Shift adds and Alt/Option subtracts on the selected patch, committing on release. Alt-click chooses a donor for Heal/Clone when no patch is selected. Older saved scenes with a single `stroke` load as one-element arrays.
-`addRemovePatch(id, stroke)` appends a Remove patch and returns its ID. It synthesizes the covered region from unmasked surrounding context using multiscale GPU PatchMatch; no offset or manual source is needed. `setHealSource` rejects Remove patches. The same feather, opacity, destination, duplicate, and delete edits apply. In the editor, the first full-resolution render synthesizes where each pixel copies from, and `getState()` then shows it as the patch's `field`, naming its stored texels: changes to the layers below, undo, export, and scene files keep it, while the copied colors follow those layers. `exportImage` and `exportScene` wait for a field still being read back. A stroke `addHealStroke` adds keeps what the field filled and synthesizes only the rest; moving the patch synthesizes it anew. The solver and compositor run through `createEditorRenderer` without React; [the solver documentation](src/features/heal/inpaint/algorithm.md) describes limits and reproducible benchmarks.
+`addRemovePatch(id, stroke)` appends a Remove patch and returns its ID. It synthesizes the covered region from unmasked surrounding context using multiscale GPU PatchMatch; no offset or manual source is needed. `setHealSource` rejects Remove patches. The same feather, opacity, destination, duplicate, and delete edits apply. In the editor, the first full-resolution render synthesizes where each pixel copies from, and `getState()` then shows it as the patch's `field`, naming its stored texels: changes to the layers below, undo, export, and scene files keep it, while the copied colors follow those layers. `exportImage` and `exportScene` first read back any field the editor holds but the scene lacks, and reject when that readback fails. Adding a stroke with `addHealStroke` keeps what the field already filled and synthesizes only the rest; moving the patch synthesizes it anew. The solver and compositor run through `createEditorRenderer` without React; [the solver documentation](src/features/heal/inpaint/algorithm.md) describes limits and reproducible benchmarks.
Create an empty Paint layer with `addLayer("paint")`. `addPaintStroke(id, stroke)` appends a `BrushStroke` with a `color`, `#rrggbb` sRGB: a painting stroke lays that color over the layer's earlier paint, and an erasing one removes paint whatever its color. `setPaintBlend(id, blend)` blends the layer's paint over the image below with the modes `setFill` takes, on encoded values as Photoshop does. A paint stroke builds up as a mask's does. In the editor, a layer's strokes settle into pixels once it has 100 and no gesture is open: `getState()` then shows a `raster` ID and fewer strokes, undo still reaches every stroke, and scene files keep the pixels. A photo holds up to 4 Paint layers and 10 brush masks; adding more throws.
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index ed8fb48..5fb0536 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -86,7 +86,7 @@ Dependencies point downward. Features do not import each other; `app/` connects
- Strokes are scene content; the renderer caches their rasterized coverage, or a Paint layer's premultiplied 8-bit color, at half the source's resolution each way, a quarter of its pixels, which the passes that read them sample back to full size, and stamps only appended dabs. A Paint layer's or brush mask's raster comes with its first paint and stays, cleared if need be, until the layer goes, so painting and undoing allocate nothing. A photo holds up to 4 Paint layers and 10 brush masks.
- A mask's or Paint layer's latest stroke builds up in a half-float stroke buffer at the same resolution, one stroke at a time; its raster takes it in one pass when the next stroke starts, so it rounds to 8 bits once, however many moves drew it. Until then a Paint layer composes the buffer over its raster, and a mask's readers get its raster with the stroke laid over, in a view redrawn where the stroke grows. A Healing or Clone patch records its mode, reuses the same coverage, and keeps editable feather and opacity. Clone copies donor color directly, skipping the correction passes. A Healing patch records ordered hard paint/erase strokes, stamped through the shared GPU brush engine into one raster over only the 256 px tiles its paint reaches. Appending a gesture stamps only new dabs; undo or moved geometry replays the sequence. Shift adds and Alt/Option subtracts on the selected patch, preserving its donor and blend; separate strokes stay separate. The local SVG preview composes the same ordered operations and shows union boundaries and erased holes. Scene loading migrates earlier single-stroke patches once at the boundary.
- Remove patches store hard paint/erase strokes without a donor offset. `features/heal/inpaint` synthesizes a field of each hole texel's offset to its donor with a local, multiscale PatchMatch graph, entirely on the GPU: exclusion mask, preserved texture descriptors, nearest valid donor initialization, parallel propagation/random search, and overlap voting. Matching is bounded to 512 texels along the long side; the output samples donors at full source resolution. The Heal compositor applies the patch's coverage, feather, and opacity.
-- A Remove field is synthesized once per set of strokes, from the image below the patch at full resolution, and kept: the renderer holds it, and once no gesture is open `features/heal` reads it back and the patch names it as a document resource, as settled paint is, without a history step; a stroke added during the readback takes it as its base. The layers below, a proxy, hiding, undo, export, and a reopened scene all use a saved field and never solve again. The document keeps each readback in flight, so export and scene files wait for it, and a draft saves again once the field changes the scene. Composition samples donor color from the current image below, so the patch follows changes under it, such as exposure. A stroke added to or erased from the patch keeps the texels the earlier field filled, on the same lattice while it fits, as long as they stay in the hole and their donors stay clean, and synthesizes only the rest; moving the patch synthesizes it anew. Synthesis needs no React and no readback. See [the solver](src/features/heal/inpaint/algorithm.md) for its constraints and standalone benchmarks.
+- A Remove field is synthesized once per set of strokes, from the image below the patch at full resolution, and kept: the renderer holds it, and once no gesture is open `features/heal` reads it back and the patch names it as a document resource, as settled paint is, without a history step; a stroke added during the readback takes it as its base. The layers below, a proxy, hiding, undo, export, and a reopened scene all use a saved field and never solve again. Before export and scene files take their snapshot, the document has `features/heal` save any field the scene lacks, so one whose readback failed is read again and a second failure fails the snapshot; a draft saves again once a field changes the scene. Composition samples donor color from the current image below, so the patch follows changes under it, such as exposure. A stroke added to or erased from the patch keeps the texels the earlier field filled, on the same lattice while it fits, as long as they stay in the hole and their donors stay clean, and synthesizes only the rest; moving the patch synthesizes it anew. Synthesis needs no React and no readback. See [the solver](src/features/heal/inpaint/algorithm.md) for its constraints and standalone benchmarks.
- A brush mask paints coverage as a Paint layer paints color: both are a painting, the latest strokes over settled pixels, in one raster module (r8 for coverage, rgba8 for color), which also owns the open stroke coverage view. At 100 strokes, once no gesture is open, the renderer reads a painting's raster band by band through one mapped buffer, and the pixels, deflated, become a document resource the layer names in place of its strokes, without a history step. Rendering waits until both the scene and cached raster accept the settled pixels. History scenes name the pixels they drew over, so undo reaches past a settle: the renderer loads those pixels, inflating them band by band through a staging texture, and draws the strokes again. Resources go once no retained scene names them.
- A mask that only gradients shape needs no texture: the mix pass computes it, children included. A mask with a painted brush or a range combines in the render graph: each child's coverage, a brush's cached raster, a gradient drawn by a node, or a range read from the image below the mask, folds into the group's in stored order through one combine pass, and the mix pass shares its add, subtract, and intersect. The group takes the image's resolution when a range takes part, since a range follows the photo's edges, and the brushes' otherwise. The renderer gives it out, with each range's own coverage, for the overlay and thumbnails. While a color is picked, renders also keep the image below the mask group, which the picker reads through one GPU pass and 16 bytes of readback per pick.
- Open history groups render a reduced proxy. Every render image carries `scale`, its source pixels per texel; shaders that take document coordinates or radii apply it.
diff --git a/src/app/editor/export/export-image.ts b/src/app/editor/export/export-image.ts
index 48c9250..5a36eba 100644
--- a/src/app/editor/export/export-image.ts
+++ b/src/app/editor/export/export-image.ts
@@ -78,18 +78,22 @@ export async function encodeImage(
return blob;
}
-/** Renders a snapshot of the current edits, named after the source file. */
-export async function exportImage(
+/** The scene with its source and the stored pixels and texels its renderer loads, taken together. */
+function snapshotRender(document: EditorDocument) {
+ const scene = document.scene.getState();
+ return {
+ scene,
+ source: document.resources.get(scene.layers[0].source),
+ pixels: settledPixels(document, scene),
+ fields: fieldTexels(document, scene),
+ };
+}
+
+async function renderSnapshot(
gpu: Gpu,
- document: EditorDocument,
- options: ExportOptions = {},
+ { scene, source, pixels, fields }: ReturnType<typeof snapshotRender>,
+ options: ExportOptions,
) {
- await document.replaced();
- const scene = document.scene.getState();
- const source = document.resources.get(scene.layers[0].source);
- // Taken with the scene: another photo may close the document before the renderer loads them.
- const pixels = settledPixels(document, scene);
- const fields = fieldTexels(document, scene);
const renderer = createEditorRenderer(gpu, source, {
paintPixels: (id) => {
const blob = pixels.get(id);
@@ -117,3 +121,22 @@ export async function exportImage(
renderer.dispose();
}
}
+
+/** Renders a snapshot of the current edits, named after the source file. */
+export async function exportImage(
+ gpu: Gpu,
+ document: EditorDocument,
+ options: ExportOptions = {},
+) {
+ // Taken now, since another photo may close the document meanwhile, and again once the Remove fields
+ // the scene lacks are read back, unless it did.
+ const requested = snapshotRender(document);
+ const release = requested.source.retain();
+ try {
+ await document.prepareSnapshot();
+ const snapshot = document.closed ? requested : snapshotRender(document);
+ return await renderSnapshot(gpu, snapshot, options);
+ } finally {
+ release();
+ }
+}
diff --git a/src/app/loaders/scene.ts b/src/app/loaders/scene.ts
index 83442e1..f4f739c 100644
--- a/src/app/loaders/scene.ts
+++ b/src/app/loaders/scene.ts
@@ -20,8 +20,13 @@ function isSceneFile(file: File) {
* already deflated pixels paint settled into at `paint/<id>`, and Remove fields at `fields/<id>`.
*/
export async function writeSceneFile(document: EditorDocument) {
- await document.replaced();
- const { json, sources, paint, fields } = snapshotScene(document);
+ // Taken now, since another photo may close the document meanwhile, and again once the Remove fields
+ // the scene lacks are read back, unless it did.
+ const requested = snapshotScene(document);
+ await document.prepareSnapshot();
+ const { json, sources, paint, fields } = document.closed
+ ? requested
+ : snapshotScene(document);
const { writeZip } = await import("@/lib/zip");
const archive = await writeZip([
{
diff --git a/src/core/document/index.ts b/src/core/document/index.ts
index ca9195f..c63e431 100644
--- a/src/core/document/index.ts
+++ b/src/core/document/index.ts
@@ -168,7 +168,7 @@ export function createDocument(initial: Scene, resources = createResources()) {
selection.setState({ layerId: state.layers[0].id });
}
});
- const inFlight = new Set<Promise<unknown>>();
+ const preparations = new Set<() => Promise<void>>();
let closed = false;
return {
id: crypto.randomUUID(),
@@ -213,17 +213,19 @@ export function createDocument(initial: Scene, resources = createResources()) {
}
replace(next);
},
- /** Keeps `work` that will replace the scene in place, such as a Remove field read back, for `replaced`. */
- replacing(work: Promise<unknown>) {
- inFlight.add(work);
- const done = () => inFlight.delete(work);
- void work.then(done, done);
+ /**
+ * Adds `prepare`, which a snapshot runs first to replace the scene in place with what the editor
+ * shows but the scene lacks, such as Remove fields read back. Returns its removal.
+ */
+ onSnapshot(prepare: () => Promise<void>) {
+ preparations.add(prepare);
+ return () => {
+ preparations.delete(prepare);
+ };
},
- /** Resolves once in-place replacements in flight finish, so a snapshot holds what the editor shows. */
- async replaced() {
- while (inFlight.size) {
- await Promise.allSettled(inFlight);
- }
+ /** Runs every preparation, so a snapshot holds what the editor shows; rejects when one fails. */
+ async prepareSnapshot() {
+ await Promise.all([...preparations].map((prepare) => prepare()));
},
/** Whether the document was disposed, so work that outlived it can drop its result. */
get closed() {
diff --git a/src/features/heal/save-fields.tsx b/src/features/heal/save-fields.tsx
index 012ef8d..ae8c7f3 100644
--- a/src/features/heal/save-fields.tsx
+++ b/src/features/heal/save-fields.tsx
@@ -79,39 +79,43 @@ async function saveRemoveField(
/**
* Saves each Remove field once the renderer synthesizes it and no gesture is open, checking after
* every render and when a gesture ends. A render during a save checks again after it; a patch the
- * renderer holds no field for, such as one on a hidden layer, waits for the next render. The document
- * keeps each save, so a snapshot waits for it. Returns the stop.
+ * renderer holds no field for, such as one on a hidden layer, waits for the next render. A snapshot
+ * first saves what the scene lacks, so a field whose save failed tries again. Returns the stop.
*/
export function watchRemoveFields(
document: EditorDocument,
renderer: Pick<Renderer, "readField" | "subscribe">,
) {
let active = true;
- let running = false;
+ let pass: Promise<void> | undefined;
let rendered = false;
async function save() {
- running = true;
- rendered = false;
- try {
- const patches = [...removePatches(document.scene.getState().layers)];
- for (const { layer, patch } of patches) {
- // A gesture stops the pass, since a readback holds renders; its end checks again.
- if (!active || document.history.status.getState().editing) {
- return;
- }
- if (!saved(patch)) {
- await saveRemoveField(document, renderer, layer.id, patch);
- }
+ const patches = [...removePatches(document.scene.getState().layers)];
+ for (const { layer, patch } of patches) {
+ // A gesture stops the pass, since a readback holds renders; its end checks again.
+ if (!active || document.history.status.getState().editing) {
+ return;
+ }
+ if (!saved(patch)) {
+ await saveRemoveField(document, renderer, layer.id, patch);
}
- } finally {
- running = false;
}
}
+ function start() {
+ rendered = false;
+ pass = save().finally(() => {
+ pass = undefined;
+ if (rendered) {
+ check();
+ }
+ });
+ return pass;
+ }
function check() {
if (!active || document.history.status.getState().editing) {
return;
}
- if (running) {
+ if (pass) {
rendered = true;
return;
}
@@ -119,20 +123,25 @@ export function watchRemoveFields(
if ([...removePatches(scene.layers)].every(({ patch }) => saved(patch))) {
return;
}
- document.replacing(
- save()
- .catch((error) =>
- console.error("A Remove field couldn't be saved.", error),
- )
- .then(() => rendered && check()),
+ void start().catch((error) =>
+ console.error("A Remove field couldn't be saved.", error),
);
}
+ /** Saves what the scene lacks after the passes in flight, and fails with its readback. */
+ async function prepare() {
+ while (pass) {
+ await pass.catch(() => {});
+ }
+ await start();
+ }
const unsubscribe = renderer.subscribe(check);
const detach = document.history.status.subscribe(check);
+ const removePreparation = document.onSnapshot(prepare);
return () => {
active = false;
unsubscribe();
detach();
+ removePreparation();
};
}
diff --git a/tests/heal.test.ts b/tests/heal.test.ts
index 5ac2980..cfca230 100644
--- a/tests/heal.test.ts
+++ b/tests/heal.test.ts
@@ -263,28 +263,31 @@ test("a nested Remove synthesizes once for its strokes, whatever changes below o
}
});
-test("Remove fields save once no gesture is open, a stroke added during a readback takes its field as a base, and snapshots wait for a readback", async () => {
+test("Remove fields save once no gesture is open, a stroke added during a readback takes its field as a base, and a snapshot saves what the scene lacks or fails with its readback", async () => {
const { document, layer } = healFixture();
- // A renderer whose renders the test runs, and whose readbacks finish, oldest first, when it says.
+ // A renderer whose renders the test runs, and whose readbacks finish or fail, oldest first, when it
+ // says.
let render = () => {};
- const reads: (() => void)[] = [];
+ const reads: ((error?: Error) => void)[] = [];
const renderer = {
subscribe(listener: () => void) {
render = listener;
return () => {};
},
readField: () =>
- new Promise<{ texels: Blob; lattice: FieldLattice }>((resolve) =>
- reads.push(() =>
- resolve({
- texels: new Blob(["field"]),
- lattice: { origin: [0, 0], scale: 1, size: [8, 8] },
- }),
+ new Promise<{ texels: Blob; lattice: FieldLattice }>((resolve, reject) =>
+ reads.push((error) =>
+ error
+ ? reject(error)
+ : resolve({
+ texels: new Blob(["field"]),
+ lattice: { origin: [0, 0], scale: 1, size: [8, 8] },
+ }),
),
),
};
- async function finish() {
- reads.shift()?.();
+ async function finish(error?: Error) {
+ reads.shift()?.(error);
await new Promise((resolve) => setTimeout(resolve, 0));
}
const patches = () =>
@@ -316,10 +319,29 @@ test("Remove fields save once no gesture is open, a stroke added during a readba
expect(patches()[0].field?.strokes).toBe(2);
// The field for every stroke is being read back, and a snapshot waits for it.
const snapshot = document
- .replaced()
+ .prepareSnapshot()
.then(() => patches()[0].field?.strokes);
await finish();
expect(await snapshot).toBe(3);
+
+ // A snapshot after a failed readback reads the field again, and fails when that fails too.
+ const errors = spyOn(console, "error").mockImplementation(() => {});
+ addHealStroke(document, layer, first, dab);
+ await finish(Error("Device lost"));
+ expect(errors).toHaveBeenCalledTimes(1);
+ const failed = document.prepareSnapshot().then(
+ () => undefined,
+ (error: Error) => error.message,
+ );
+ expect(reads).toHaveLength(1);
+ await finish(Error("Device lost"));
+ expect(await failed).toBe("Device lost");
+ const retried = document
+ .prepareSnapshot()
+ .then(() => patches()[0].field?.strokes);
+ await finish();
+ expect(await retried).toBe(4);
+ errors.mockRestore();
} finally {
stop();
document.dispose();
diff --git a/tests/scene-file.test.ts b/tests/scene-file.test.ts
index 38c7855..edd13df 100644
--- a/tests/scene-file.test.ts
+++ b/tests/scene-file.test.ts
@@ -2,7 +2,7 @@ import { expect, test } from "bun:test";
import { init, target } from "vgpu/mock";
import { createControls } from "@/app/controls";
import { createImageLayer, createLayer, createMask } from "@/app/editor/layers";
-import { openSceneFile } from "@/app/loaders/scene";
+import { openSceneFile, writeSceneFile } from "@/app/loaders/scene";
import { createWorkspace } from "@/app/workspace";
import {
type BrushStroke,
@@ -230,3 +230,33 @@ test("scene files reopen the photo with every layer for further editing", async
workspace.dispose();
gpu.dispose();
});
+
+test("a scene file waits for its preparations and still saves once another photo closes its document", async () => {
+ const gpu = await init();
+ const resources = createResources();
+ const png = new File([bytes], "photo.png", { type: "image/png" });
+ const source = resources.add(
+ png,
+ createImageSource(target(gpu, { size, format: "rgba16float" })),
+ );
+ const document = createDocument(
+ {
+ frame: imageFrame(size),
+ layers: [createImageLayer(source, "photo.png")],
+ },
+ resources,
+ );
+ let prepared = () => {};
+ document.onSnapshot(
+ () =>
+ new Promise<void>((resolve) => {
+ prepared = resolve;
+ }),
+ );
+ const saving = writeSceneFile(document);
+ document.dispose();
+ prepared();
+ const entries = await readZip(await saving);
+ expect(await entries.get(`sources/${source}`)?.bytes()).toEqual(bytes);
+ gpu.dispose();
+});