Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Keep an open Detect check's preview to its frame, and let a rename take a deleted file's name (#90)

OsintMeThat4feb7f5b22b5
diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md
index 8f0b8c7..51eb9fa 100644
--- a/docs/RELEASE_NOTES.md
+++ b/docs/RELEASE_NOTES.md
@@ -102,6 +102,7 @@ maps made elsewhere on yours.
used to delete a collage or be refused.
- Two names differing only by case no longer block a bundle export on Linux.
- A proof, draft or grid with "#" in its name opens and deletes the right one.
+- Renaming a file to the name of one deleted earlier no longer fails halfway.
- Notes, proofs and drafts are written whole, so an interrupted save keeps the
previous version.
- The Wayback map no longer slows down while you pan, and its picker lists every
diff --git a/docs/UI.md b/docs/UI.md
index 8708402..b66a082 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -2298,7 +2298,9 @@ A view moved off the ground its passes were picked for drops them. A check with
pins counts the candidates of its whole view, which its row says costs more frames
than pins, each read on its own tile. The open check's view is framed on the map
with its name, and its pins drawn: a filled ring where a candidate should come out,
-a struck ring where none should, green or red once read. While the builder has
+a struck ring where none should, green or red once read. While a check is open the
+preview and its candidates stay inside its frame and the ground outside is veiled,
+so what the map paints is what the check judges. While the builder has
passes, a bar on the map switches the imagery under the preview between **A**,
**B** and **Blink**, and back to the basemap. Checks reread themselves
from the tile cache a moment after every change to the rules, with no request, so
diff --git a/frontend/src/lib/map/analyzerRules.js b/frontend/src/lib/map/analyzerRules.js
index 0e7aa55..e81c2ad 100644
--- a/frontend/src/lib/map/analyzerRules.js
+++ b/frontend/src/lib/map/analyzerRules.js
@@ -6,6 +6,7 @@
* decibels. Only the words and the sliders here show reflectance in percent.
*/
import { CHANGE_INDICES, indexThreshold } from './changeAssist.js';
+import { toMercator } from './groundFrame.js';
export const MEASURES = Object.freeze([
{ id: 'index', label: 'Index', hint: 'A published spectral index.' },
@@ -416,6 +417,34 @@ export function paintMask(bits, { shown = [], hover = null, colours = RULE_COLOU
return out;
}
+/**
+ * Keep a painted mask to the ground inside `bounds` ({ west, south, east, north }
+ * in degrees), clearing every pixel outside. The mask covers `box`, its extent in
+ * Web Mercator metres; both are aligned with the ground, so the kept part is a
+ * pixel rectangle however the map is turned. Used while a check is open: it
+ * judges its own frame, so the map paints nothing past it.
+ */
+export function clipToBounds(rgba, width, height, box, bounds) {
+ const [west, north] = toMercator(bounds.west, bounds.north);
+ const [east, south] = toMercator(bounds.east, bounds.south);
+ const column = (x) => ((x - box.west) / (box.east - box.west)) * width;
+ const row = (y) => ((box.north - y) / (box.north - box.south)) * height;
+ const x0 = Math.max(0, Math.floor(column(west)));
+ const x1 = Math.min(width, Math.ceil(column(east)));
+ const y0 = Math.max(0, Math.floor(row(north)));
+ const y1 = Math.min(height, Math.ceil(row(south)));
+ const out = new Uint8ClampedArray(rgba.length);
+ for (let y = y0; y < y1; y++) {
+ out.set(rgba.subarray((y * width + x0) * 4, (y * width + x1) * 4), (y * width + x0) * 4);
+ }
+ return out;
+}
+
+/** Whether a [lon, lat] point is inside `bounds`. */
+export function insideBounds([lon, lat], bounds) {
+ return lon >= bounds.west && lon <= bounds.east && lat >= bounds.south && lat <= bounds.north;
+}
+
/** A share of the measured ground, as the funnel prints it. */
export function formatShare(share) {
if (!Number.isFinite(share)) return '–';
diff --git a/frontend/src/lib/map/analyzerRules.test.js b/frontend/src/lib/map/analyzerRules.test.js
index 2105775..435e11e 100644
--- a/frontend/src/lib/map/analyzerRules.test.js
+++ b/frontend/src/lib/map/analyzerRules.test.js
@@ -4,8 +4,10 @@ import {
formatValue, fromDifference, newRecipe, newRule, opsFor, paintMask, productCount, recipeBands,
recipeCapability, recipeProblem, retarget, scaleOf, signalOf, toEngine,
checkState, checksSummary, describeChecks, describeOutcome, markOutcomes, newCheck, signature, withMark, withoutMark,
+ clipToBounds, insideBounds,
} from './analyzerRules.js';
import { changeSettings } from './changeAssist.js';
+import { toMercator } from './groundFrame.js';
const METHODS = [
{ id: 'rules', single: false, clouds: true, sensor: 'sentinel2', frames: 4, sizes: { medium: { min_area: 2000, cleanup: 1 } }, rules: true },
@@ -241,3 +243,34 @@ describe('checks', () => {
expect(checksSummary({ ...built, checks: [check([true]), check(null)] })).toMatchObject({ total: 2, pass: 1, waiting: 1 });
});
});
+
+
+describe('an open check keeps the preview to its frame', () => {
+ // A 4x4 mask over a box of four degrees a side, every pixel painted.
+ const [west, north] = toMercator(0, 4);
+ const [east, south] = toMercator(4, 0);
+ const box = { west, east, north, south };
+ const painted = () => new Uint8ClampedArray(4 * 4 * 4).fill(255);
+ const alphaAt = (rgba, x, y) => rgba[(y * 4 + x) * 4 + 3];
+
+ it('clears every pixel outside the frame and keeps the ones inside', () => {
+ // the frame covers the west half, full height
+ const kept = clipToBounds(painted(), 4, 4, box, { west: 0, south: 0, east: 2, north: 4 });
+ expect([0, 1].every((x) => [0, 1, 2, 3].every((y) => alphaAt(kept, x, y) === 255))).toBe(true);
+ expect([2, 3].every((x) => [0, 1, 2, 3].every((y) => alphaAt(kept, x, y) === 0))).toBe(true);
+ });
+
+ it('keeps nothing when the frame is off the mask, and everything when it holds it', () => {
+ const off = clipToBounds(painted(), 4, 4, box, { west: 10, south: 10, east: 12, north: 12 });
+ expect(off.every((value) => value === 0)).toBe(true);
+ const all = clipToBounds(painted(), 4, 4, box, { west: -1, south: -1, east: 5, north: 5 });
+ expect(all.every((value) => value === 255)).toBe(true);
+ });
+
+ it('says whether a candidate stands inside the frame', () => {
+ const frame = { west: 0, south: 0, east: 2, north: 4 };
+ expect(insideBounds([1, 2], frame)).toBe(true);
+ expect(insideBounds([3, 2], frame)).toBe(false);
+ expect(insideBounds([1, 5], frame)).toBe(false);
+ });
+});
diff --git a/frontend/src/tools/Detect.svelte b/frontend/src/tools/Detect.svelte
index 84beba8..e0fcbea 100644
--- a/frontend/src/tools/Detect.svelte
+++ b/frontend/src/tools/Detect.svelte
@@ -20,6 +20,7 @@
import { caseState, dismissToast, prefs, prefsReady, toast, uiState } from '../lib/state.svelte.js';
import { marksToZones, sourceLabel, viewZone, zoneMarks, zoneRing } from '../lib/map/analyzers.js';
import { blinkable } from '../lib/map/detectReview.js';
+ import { insideBounds } from '../lib/map/analyzerRules.js';
import { DEFAULT_BLINK_INTERVAL } from '../lib/map/compare.js';
import { createImageryState } from './satellite/state/imagery.svelte.js';
import { createSentinelState } from './satellite/state/sentinel.svelte.js';
@@ -123,10 +124,14 @@
layersAsked = true;
untrack(() => s2.loadLayers(false, true));
});
+ // While a check is open the map shows what the rules keep inside its frame only:
+ // the check judges that ground, and paint past the frame read as it being off.
const previewLayer = $derived(builder?.preview?.ready ? [{
id: 'builder-preview', visible: true,
input: { recipe: { colour: builder.colour, style: builder.style } },
- results: builder.preview.candidates.map((row) => ({ ...row, review: 'new', phenomenon: builder.phenomenon })),
+ results: builder.preview.candidates
+ .filter((row) => !builder.ground || insideBounds(row.coordinates, builder.ground.bounds))
+ .map((row) => ({ ...row, review: 'new', phenomenon: builder.phenomenon })),
}] : []);
$effect(() => { manualTool = manual?.kind === 'polygon' ? 'polygon' : 'select'; });
@@ -635,7 +640,7 @@
/>
{#if builder}
<RuleLayers {engine} {element} preview={builder.preview} shown={builder.shown} hover={builder.hover}
- colours={builder.colours} />
+ colours={builder.colours} within={builder.ground?.bounds ?? null} />
{#if previewLayer.length}
<AnalysisOverlay {engine} layers={previewLayer} onpick={(_, id) => {
const row = builder.preview.candidates.find((candidate) => candidate.id === id);
diff --git a/frontend/src/tools/detect/CheckMarks.render.test.js b/frontend/src/tools/detect/CheckMarks.render.test.js
index 6bd6d58..a05414e 100644
--- a/frontend/src/tools/detect/CheckMarks.render.test.js
+++ b/frontend/src/tools/detect/CheckMarks.render.test.js
@@ -32,6 +32,21 @@ it('draws the open check’s view as a frame with its name', () => {
flushSync();
expect(target.querySelector('polygon').getAttribute('points')).toBe('100,100 200,100 200,200 100,200');
expect(target.querySelector('.ground-name').textContent).toBe('Check 4');
+ // The ground outside the frame is veiled: the frame is cut out of a ring past the screen.
+ const veil = target.querySelector('path.veil');
+ expect(veil.getAttribute('fill-rule')).toBe('evenodd');
+ expect(veil.getAttribute('d')).toBe('M-1e5,-1e5H1e5V1e5H-1e5Z M100,100 L200,100 L200,200 L100,200Z');
+ unmount(live);
+ target.remove();
+});
+
+it('veils nothing while no check is open', () => {
+ const engine = { on: () => () => {}, latLngToContainerPoint: () => ({ x: 0, y: 0 }) };
+ const target = document.createElement('div');
+ document.body.append(target);
+ const live = mount(CheckMarks, { target, props: { engine, marks: [{ point: [1, 48], expect: 'found', ok: null }] } });
+ flushSync();
+ expect(target.querySelector('path.veil')).toBeNull();
unmount(live);
target.remove();
});
diff --git a/frontend/src/tools/detect/CheckMarks.svelte b/frontend/src/tools/detect/CheckMarks.svelte
index 896c65a..fd2fb89 100644
--- a/frontend/src/tools/detect/CheckMarks.svelte
+++ b/frontend/src/tools/detect/CheckMarks.svelte
@@ -4,6 +4,10 @@
* name, and its pins, a filled ring where a candidate should come out and a
* struck ring where none should, green or red once the check has been read
* with the rules as they stand. The map keeps its clicks: this only shows.
+ *
+ * The ground outside the frame is veiled. The rules' preview covers the whole
+ * view, which opens with a margin around the check, so without the veil the
+ * painted ground ran past the frame and read as the frame being off.
*/
let { engine, marks = [], ground = null } = $props();
@@ -27,14 +31,20 @@
const corners = [[west, north], [east, north], [east, south], [west, south]]
.map(([lon, lat]) => engine.latLngToContainerPoint({ lon, lat }));
const top = corners.reduce((best, point) => (point.y < best.y ? point : best), corners[0]);
- return { points: corners.map((point) => `${point.x},${point.y}`).join(' '), label: top };
+ const points = corners.map((point) => `${point.x},${point.y}`).join(' ');
+ // Everything but the frame: a ring far past any screen, the frame cut out of it.
+ const veil = `M-1e5,-1e5H1e5V1e5H-1e5Z M${corners.map((point) => `${point.x},${point.y}`).join(' L')}Z`;
+ return { points, veil, label: top };
});
const words = (mark) => `${mark.expect === 'found' ? 'Should be found' : 'Should stay empty'}${
mark.ok === true ? ', and it is' : mark.ok === false ? ', and it is not' : ''}`;
</script>
{#if frame}
- <svg class="ground" aria-hidden="true"><polygon points={frame.points} /></svg>
+ <svg class="ground" aria-hidden="true">
+ <path class="veil" d={frame.veil} fill-rule="evenodd" />
+ <polygon points={frame.points} />
+ </svg>
<span class="ground-name" style:left={`${frame.label.x}px`} style:top={`${frame.label.y}px`}>{ground.name}</span>
{/if}
{#each placed as mark, i (i)}
@@ -52,7 +62,8 @@
overflow: visible;
pointer-events: none;
}
- .ground polygon { fill: rgb(255 255 255 / 0.04); stroke: #f8fafc; stroke-width: 1.5; stroke-dasharray: 6 4; }
+ .ground polygon { fill: none; stroke: #f8fafc; stroke-width: 1.5; stroke-dasharray: 6 4; }
+ .ground .veil { fill: rgb(0 0 0 / 0.5); }
.ground-name {
position: absolute;
z-index: 551;
diff --git a/frontend/src/tools/detect/RuleLayers.svelte b/frontend/src/tools/detect/RuleLayers.svelte
index 46c5d2c..f2e5d97 100644
--- a/frontend/src/tools/detect/RuleLayers.svelte
+++ b/frontend/src/tools/detect/RuleLayers.svelte
@@ -7,9 +7,10 @@
* zoomed or turned, and repaints only when a rule is shown, hidden or hovered.
*/
import { compose, cssMatrix, imageToMercator, invert, screenToMercator } from '../../lib/map/groundFrame.js';
- import { RULE_COLOURS, paintMask } from '../../lib/map/analyzerRules.js';
+ import { RULE_COLOURS, clipToBounds, paintMask } from '../../lib/map/analyzerRules.js';
- let { engine, element, preview = null, shown = [], hover = null, colours = RULE_COLOURS } = $props();
+ /** `within`: the open check's bounds, past which nothing is painted. */
+ let { engine, element, preview = null, shown = [], hover = null, colours = RULE_COLOURS, within = null } = $props();
let canvas = $state(null);
let bits = $state(null);
@@ -53,7 +54,9 @@
if (bits.length !== width * height) return;
canvas.width = width;
canvas.height = height;
- canvas.getContext('2d').putImageData(new ImageData(paintMask(bits, { shown, hover, colours }), width, height), 0, 0);
+ const painted = paintMask(bits, { shown, hover, colours });
+ const kept = within && preview.box ? clipToBounds(painted, width, height, preview.box, within) : painted;
+ canvas.getContext('2d').putImageData(new ImageData(kept, width, height), 0, 0);
});
const transform = $derived.by(() => {
diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.py
index f1d3634..9601775 100644
--- a/src/azimut/sqlite_backend.py
+++ b/src/azimut/sqlite_backend.py
@@ -3394,13 +3394,30 @@ class SqliteCase:
)
for row in conn.execute(
- "SELECT id, job_key, payload_json FROM jobs"
+ "SELECT id, kind, job_key, payload_json FROM jobs"
).fetchall():
payload = json.loads(row["payload_json"])
replaced = _replace_exact(payload, old, new)
key = new if row["job_key"] == old else row["job_key"]
if key == row["job_key"] and replaced == payload:
continue
+ if key != row["job_key"]:
+ # A rename only lands on a path no file holds, so a job already
+ # keyed there was left by a file deleted from it: enqueue keeps
+ # finished rows to reset them. Re-keying over it would break the
+ # (kind, key) uniqueness halfway through the rename, after the
+ # file had moved, and the recovery would fail the same way.
+ conn.execute(
+ "DELETE FROM jobs WHERE kind = ? AND job_key = ? AND state != 'running'",
+ (row["kind"], key),
+ )
+ if conn.execute(
+ "SELECT 1 FROM jobs WHERE kind = ? AND job_key = ?", (row["kind"], key)
+ ).fetchone():
+ # The worker is still on the stale one. Let it finish; the
+ # renamed file's own row is the one to give up.
+ conn.execute("DELETE FROM jobs WHERE id = ?", (row["id"],))
+ continue
conn.execute(
"UPDATE jobs SET job_key = ?, payload_json = ?, updated_at = ?"
" WHERE id = ?",
diff --git a/tests/test_media_api.py b/tests/test_media_api.py
index e8a0b23..52648e9 100644
--- a/tests/test_media_api.py
+++ b/tests/test_media_api.py
@@ -725,6 +725,25 @@ def test_media_rename_recovers_after_files_moved_before_database_update(client,
assert not journal.exists()
+def test_media_rename_takes_the_name_of_a_deleted_file(client):
+ # Deleting a file keeps its finished jobs (enqueue resets them on reuse), so the
+ # second rename onto "Shared" used to fail on the jobs' (kind, key) uniqueness
+ # after the file had already moved, leaving the entity on the old path.
+ cid = client.post("/api/cases", json={"name": "Rename over deleted"}).json()["id"]
+ first = _upload(client, cid, "one.png", _png_bytes()).json()["item"]
+ renamed = client.patch(f"/api/cases/{cid}/media", json={"path": first["path"], "title": "Shared"})
+ assert renamed.status_code == 200
+ client.delete(f"/api/cases/{cid}/media", params={"path": "media/Shared.png"})
+
+ second = _upload(client, cid, "two.png", _png_bytes(color=(90, 10, 10))).json()["item"]
+ again = client.patch(f"/api/cases/{cid}/media", json={"path": second["path"], "title": "Shared"})
+
+ assert again.status_code == 200
+ from azimut.workspace import Case
+
+ assert Case.open(cid).find_entity(attr="path", value="media/Shared.png")["label"] == "Shared"
+
+
def test_media_rename_uses_portable_case_insensitive_collisions(client):
cid = client.post("/api/cases", json={"name": "Portable names"}).json()["id"]
_upload(client, cid, "Clip.png", _png_bytes()).json()["item"]
diff --git a/tests/test_repository.py b/tests/test_repository.py
index cc60d80..b0f85ea 100644
--- a/tests/test_repository.py
+++ b/tests/test_repository.py
@@ -539,6 +539,34 @@ def test_replace_path_references_updates_exact_structured_values(repo):
assert queued["payload"] == {"path": new, "nested": [new], "notes": sentence}
+def test_replace_path_references_moves_a_job_over_a_deleted_files_leftover(repo):
+ # A file deleted from media/after.png leaves its finished enrich row behind, and
+ # a later rename onto that name must not trip the (kind, key) uniqueness.
+ stale = repo.enqueue_job("enrich", key="media/after.png", payload={"path": "media/after.png"})
+ repo.complete_job(stale["id"])
+ moving = repo.enqueue_job("enrich", key="media/before.png", payload={"path": "media/before.png"})
+ repo.complete_job(moving["id"])
+
+ repo.replace_path_references("media/before.png", "media/after.png")
+
+ assert repo.get_job(stale["id"]) is None
+ moved = repo.get_job(moving["id"])
+ assert moved["key"] == "media/after.png"
+ assert moved["payload"] == {"path": "media/after.png"}
+
+
+def test_replace_path_references_leaves_a_running_leftover_to_its_worker(repo):
+ stale = repo.enqueue_job("enrich", key="media/after.png")
+ claimed = repo.claim_job(kinds=["enrich"])
+ assert claimed["id"] == stale["id"]
+ moving = repo.enqueue_job("enrich", key="media/before.png")
+
+ repo.replace_path_references("media/before.png", "media/after.png")
+
+ assert repo.get_job(stale["id"])["state"] == "running"
+ assert repo.get_job(moving["id"]) is None
+
+
def test_claim_takes_one_queued_job_oldest_first(repo):
a = repo.enqueue_job("thumbnail", key="media/a.jpg")
repo.enqueue_job("thumbnail", key="media/b.jpg")