The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Add first v2 GEOINT tools: Coordinates, Reverse Search, Grid Search (#22)
OsintMeThat157021c0ea5e
diff --git a/docs/SPEC.md b/docs/SPEC.mdindex e7dfca7..0d8e18e 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -105,6 +105,14 @@ cost controls, the capture browser extension, the settings tabs(Preferences/Imagery/About) + settings backup, scraper self-update, the launcher,server security hardening, and the two-regime dependency setup.+**Shipped since** (first v2 tools landed on `main`):++| Tool | What it does |+|------|--------------|+| ✅ **Coordinates** | Map-workspace tab: paste a point in any notation (decimal, DDM, DMS, UTM, MGRS, plus code, geohash) → read it back in every other with copy; the nine external-map links; opt-in Nominatim place name. |+| ✅ **Reverse Search** | Collect-workspace launcher: pick a case image (or scrub a video to a frame), tweak brightness/contrast/saturation/grayscale → copy to the clipboard for Google Lens or save the PNG to drag into Yandex/Bing/TinEye, each opened key-less. Orchestrates, never queries itself. |+| ✅ **Grid Search** | Satellite mode: overlay a custom metric grid on an area of interest — drag a box or draw a polygon, reshape either after the fact — and sweep it cell by cell. Fly-to-review with keyboard marks, cleared/flagged coverage; every action auto-saves. A case holds several named grids you switch between; promote a hit to a `place`. In-app only, no export. |+**Key constraints** (carried forward):- **Legal-only imagery**: built-in providers are Esri (default, key-less), OSM,@@ -130,11 +138,10 @@ never as new rail entries. Releases ship as GitHub `v0.x` tags.|------|--------------|| **Satellite Compare** | Same coords across providers (Esri / Sentinel-2 date slider / Bing / keyed), synced pan/zoom. Copernicus easy link. || **Image Compare** | Overlay two images with opacity/swipe + pixel diff. Sat-vs-screen alignment aid (assist, never a verdict). |-| **Coordinates** | Paste anything (any format or a map URL) → normalize; convert DMS/decimal/MGRS/plus code/geohash; reverse geocode (Nominatim); quick-open map links. || **EXIF & Metadata** | GPS/timestamps/device/codecs parsed locally + a "what was stripped" hint; suggests place/event. || **Shadow Clock** | Mark a shadow → possible capture times (sun-position math, local); sun times + solar azimuth readout at coords+date. Pairs with weather/METAR history. |-| **Reverse Search Launcher** | Image/frame → reverse-search links (Google/Yandex/Bing/TinEye) + an oldest-date origin hint. First orchestrator tool. || **OCR** | Read signs/plates (tesseract), detect script/language. |+| **Audio Transcript** | Transcribe speech (Whisper) + acoustic context hints (bells/adhan/aircraft/language); auto-translate → English (offline). || **Ground Imagery** | Ground-level photos: Panoramax/Mapillary/KartaView key-less first; Street View easy link, optional keyed in-app view. || **Panorama** | Stitch a video window / frame set. Auto-stitch already in Inspect; still to do: sample a video window directly, seam blending. || **Proof annotation** | Grow the Proof Composer toolbox: shape fill + dashed strokes, freehand, numbered markers, a redaction/blur box; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |@@ -147,7 +154,10 @@ capture (paste an image or a URL anywhere → filed as media with provenance),scale bar + north arrow + optional graticule burned into captures(preference-toggled auto-inclusion, extension/widget capture path included),read EXIF/GPS at media import → suggest place/time, Post Composer targets beyond-X (Mastodon, Bluesky, generic report).+X (Mastodon, Bluesky, generic report). Grow the two shipped GEOINT tools:+Coordinates gains map-URL paste (reuse the extension's `parse_map_url`) and a+Satellite hand-off; Reverse Search gains an optional TinEye-API-keyed+oldest-date origin hint (Settings key, labeled a hint).Engineering (toward v2): split the monolith tool components (Satellite,ProofComposer) by extracting their logic into `lib/` modules like the other@@ -167,9 +177,7 @@ tools; add component/interaction tests (Playwright) for the canvas gestures theAlso toward v3: dependency-aware delete (partly done), downloader cookies,archive-on-download + archive time machine (Wayback CDX snapshot timeline +diff), web-page save extension, case bundle export/import, an editable/filterable-places table (CSV/GeoJSON export), audio analyzer (Whisper) + acoustic context-hints (bells/adhan/aircraft/language), auto-translation → English (offline),-temporal change detection over imagery dates, a pattern-of-life map (a source's+places table (CSV/GeoJSON export), temporal change detection over imagery dates, a pattern-of-life map (a source'sextractable locations on map + timeline), a full chronolocation solver(shadow + sun + weather → dated window), auto-hash + timestamp on every export(proof.png etc.) recorded in the evidence journal, cross-case global search (adiff --git a/docs/UI.md b/docs/UI.mdindex d0fc4f1..f12b745 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -21,9 +21,9 @@ entry**; it registers in `frontend/src/lib/workspaces.js`.| Workspace | Tools today | Future tools land here ||---|---|---|-| **Collect** | Media Library, Files | Reverse Search, Channel Monitor, Evidence Locker |+| **Collect** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker || **Examine** | Inspect (Selection / Frame / Collage / Analyze) | EXIF, OCR, Image Compare, Hints, Shadow Clock, audio |-| **Map** | Satellite | **one map, many modes**: Compare, Ground Imagery, Coordinates, Measures, Viewshed, OSM Query, Map Board |+| **Map** | Satellite, Coordinates | **one map, many modes**: Compare, Ground Imagery, Measures, Viewshed, OSM Query, Map Board || **Compose** | Proof Composer, Post Composer | Report Builder, GIF maker || *(Case)* | — sidebar covers it | v3: Notes, Relations, Timeline, Orchestrator |diff --git a/frontend/src/App.svelte b/frontend/src/App.svelteindex 62f31af..62d28f8 100644--- a/frontend/src/App.svelte+++ b/frontend/src/App.svelte@@ -18,7 +18,9 @@import Toasts from './components/Toasts.svelte';import MediaLibrary from './tools/MediaLibrary.svelte';import Files from './tools/Files.svelte';+ import ReverseSearch from './tools/ReverseSearch.svelte';import Satellite from './tools/Satellite.svelte';+ import Coordinates from './tools/Coordinates.svelte';import ProofComposer from './tools/ProofComposer.svelte';import PostComposer from './tools/PostComposer.svelte';import Inspector from './tools/Inspector.svelte';@@ -31,8 +33,10 @@const TOOLS = [{ id: 'media', label: 'Media', component: MediaLibrary },{ id: 'files', label: 'Files', component: Files },+ { id: 'reverse', label: 'Reverse Search', component: ReverseSearch },{ id: 'inspect', label: 'Inspect', component: Inspector },{ id: 'satellite', label: 'Satellite', component: Satellite },+ { id: 'coordinates', label: 'Coordinates', component: Coordinates },{ id: 'proof', label: 'Proof', component: ProofComposer },{ id: 'post', label: 'Post', component: PostComposer },];diff --git a/frontend/src/lib/gridSearch.js b/frontend/src/lib/gridSearch.jsnew file mode 100644index 0000000..db8397a--- /dev/null+++ b/frontend/src/lib/gridSearch.js@@ -0,0 +1,232 @@+// Pure geometry + coverage bookkeeping for the Satellite Grid Search mode. A+// grid overlays an area of interest with metric cells you sweep one by one,+// marking each cleared or flagged. Kept free of Leaflet so it can be+// unit-tested; the component only handles drawing, flying and persistence.+//+// The grid is a fixed metric lattice: cells are addressed by integer (i, j)+// offsets from a stationary `anchor`, so resizing the area of interest never+// shifts a cell out from under the mark already on it. Cell size is+// approximately metric (equirectangular from the area's reference latitude) —+// exact enough for city-scale search work, which is all this mode is for.++const M_PER_DEG_LAT = 111320; // WGS84 mean, good enough for a display grid+const MIN_COS = 0.01; // clamp near the poles so the lattice stays finite++/** Cell size in degrees (lat, lon) at a reference latitude. */+export function degSteps(refLat, cellM) {+ const latStep = cellM / M_PER_DEG_LAT;+ const cos = Math.max(MIN_COS, Math.cos((refLat * Math.PI) / 180));+ const lonStep = cellM / (M_PER_DEG_LAT * cos);+ return { latStep, lonStep };+}++/** Bounding box of an area of interest (rect bounds or polygon vertices). */+export function aoiBounds(aoi) {+ if (aoi.type === 'rect') return aoi.bounds;+ const lats = aoi.vertices.map((v) => v[0]);+ const lons = aoi.vertices.map((v) => v[1]);+ return {+ south: Math.min(...lats),+ west: Math.min(...lons),+ north: Math.max(...lats),+ east: Math.max(...lons),+ };+}++/** Build a fresh grid over `aoi` with `cellM`-metre cells (no marks yet). */+export function createGrid(aoi, cellM) {+ const b = aoiBounds(aoi);+ const refLat = (b.south + b.north) / 2;+ const { latStep, lonStep } = degSteps(refLat, cellM);+ return {+ azimut_grid: 1,+ cell_m: cellM,+ anchor: { lat: b.south, lon: b.west }, // south-west corner pins the lattice+ lat_step: latStep,+ lon_step: lonStep,+ aoi,+ statuses: {}, // "i:j" -> 'cleared' | 'flagged'; absent = unchecked+ };+}++export const cellKey = (i, j) => `${i}:${j}`;+export function parseKey(k) {+ const [i, j] = k.split(':').map(Number);+ return [i, j];+}++/** Integer cell indices spanning the area's bounding box (inclusive). */+export function cellRange(grid) {+ const b = aoiBounds(grid.aoi);+ return {+ iMin: Math.floor((b.south - grid.anchor.lat) / grid.lat_step),+ iMax: Math.ceil((b.north - grid.anchor.lat) / grid.lat_step) - 1,+ jMin: Math.floor((b.west - grid.anchor.lon) / grid.lon_step),+ jMax: Math.ceil((b.east - grid.anchor.lon) / grid.lon_step) - 1,+ };+}++/** Lat/lon bounds of one cell. */+export function cellBounds(grid, i, j) {+ const south = grid.anchor.lat + i * grid.lat_step;+ const west = grid.anchor.lon + j * grid.lon_step;+ return { south, west, north: south + grid.lat_step, east: west + grid.lon_step };+}++/** Centre of one cell. */+export function cellCenter(grid, i, j) {+ const b = cellBounds(grid, i, j);+ return { lat: (b.south + b.north) / 2, lon: (b.west + b.east) / 2 };+}++/** Ray-casting point-in-polygon on [lat, lon] vertices. */+export function pointInPolygon(pt, vertices) {+ let inside = false;+ const x = pt.lon;+ const y = pt.lat;+ for (let a = 0, b = vertices.length - 1; a < vertices.length; b = a++) {+ const xi = vertices[a][1];+ const yi = vertices[a][0];+ const xj = vertices[b][1];+ const yj = vertices[b][0];+ const hit = yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;+ if (hit) inside = !inside;+ }+ return inside;+}++// Orientation sign of the turn p→q→r (x = lon, y = lat).+function orient(p, q, r) {+ return (q.lon - p.lon) * (r.lat - p.lat) - (q.lat - p.lat) * (r.lon - p.lon);+}++// Do the open segments ab and cd properly cross? (collinear touching → false)+function segsCross(a, b, c, d) {+ const o1 = orient(a, b, c);+ const o2 = orient(a, b, d);+ const o3 = orient(c, d, a);+ const o4 = orient(c, d, b);+ return o1 > 0 !== o2 > 0 && o3 > 0 !== o4 > 0;+}++/** Does a cell rectangle touch the polygon at all? Any overlap counts, so the+ * whole drawn shape gets tiled — no bare strip along a slanted edge. */+export function rectIntersectsPolygon(b, vertices) {+ const corners = [+ { lat: b.south, lon: b.west },+ { lat: b.south, lon: b.east },+ { lat: b.north, lon: b.east },+ { lat: b.north, lon: b.west },+ ];+ // a rect corner inside the polygon+ for (const c of corners) if (pointInPolygon(c, vertices)) return true;+ // a polygon vertex inside the rect+ for (const v of vertices) {+ if (v[0] >= b.south && v[0] <= b.north && v[1] >= b.west && v[1] <= b.east) return true;+ }+ // a polygon edge crossing a rect edge+ for (let i = 0; i < vertices.length; i++) {+ const pa = { lat: vertices[i][0], lon: vertices[i][1] };+ const pb = { lat: vertices[(i + 1) % vertices.length][0], lon: vertices[(i + 1) % vertices.length][1] };+ for (let e = 0; e < 4; e++) {+ if (segsCross(pa, pb, corners[e], corners[(e + 1) % 4])) return true;+ }+ }+ return false;+}++/** Cheap upper bound on cell count (the bounding box), before enumerating. */+export function estimateCells(grid) {+ const { iMin, iMax, jMin, jMax } = cellRange(grid);+ return Math.max(0, iMax - iMin + 1) * Math.max(0, jMax - jMin + 1);+}++/** Refuse a grid that would draw more cells than this (guards huge areas). */+export const MAX_CELLS = 20000;++/** Every cell inside the area, in row-major order. A rectangle keeps its whole+ * bounding box (edge cells that overhang are included so the selection is+ * fully covered); a polygon keeps every cell that overlaps it. */+export function cellsInAoi(grid) {+ const { iMin, iMax, jMin, jMax } = cellRange(grid);+ const poly = grid.aoi.type === 'polygon' ? grid.aoi.vertices : null;+ const out = [];+ for (let i = iMin; i <= iMax; i++) {+ for (let j = jMin; j <= jMax; j++) {+ if (poly && !rectIntersectsPolygon(cellBounds(grid, i, j), poly)) continue;+ out.push([i, j]);+ }+ }+ return out;+}++/** Coverage tally over the cells currently inside the area. */+export function coverage(grid) {+ const cells = cellsInAoi(grid);+ let cleared = 0;+ let flagged = 0;+ for (const [i, j] of cells) {+ const s = grid.statuses[cellKey(i, j)];+ if (s === 'cleared') cleared++;+ else if (s === 'flagged') flagged++;+ }+ const total = cells.length;+ const done = cleared + flagged;+ return {+ total,+ cleared,+ flagged,+ unchecked: total - done,+ percent: total ? Math.round((done / total) * 100) : 0,+ };+}++/** Left-click cycle: unchecked -> cleared -> flagged -> unchecked. */+export function cycleStatus(current) {+ if (!current) return 'cleared';+ if (current === 'cleared') return 'flagged';+ return null; // back to unchecked+}++/** Next unchecked cell after `afterKey` (wraps once), or null if all done. */+export function nextUnchecked(grid, afterKey) {+ const cells = cellsInAoi(grid);+ if (!cells.length) return null;+ let start = 0;+ if (afterKey) {+ const at = cells.findIndex(([i, j]) => cellKey(i, j) === afterKey);+ start = at >= 0 ? at + 1 : 0;+ }+ for (let n = 0; n < cells.length; n++) {+ const [i, j] = cells[(start + n) % cells.length];+ if (!grid.statuses[cellKey(i, j)]) return [i, j];+ }+ return null;+}++/** Drop marks that no longer fall inside the area (after a resize). Returns a+ * new statuses object; the lattice is unchanged, so surviving marks stay put. */+export function pruneStatuses(grid) {+ const valid = new Set(cellsInAoi(grid).map(([i, j]) => cellKey(i, j)));+ const next = {};+ for (const k of Object.keys(grid.statuses)) {+ if (valid.has(k)) next[k] = grid.statuses[k];+ }+ return next;+}++/** Resize a rectangle grid to new bounds, keeping the lattice and every mark+ * still inside it. The whole new box is covered; marks outside are dropped. */+export function resizeRect(grid, bounds) {+ const next = { ...grid, aoi: { type: 'rect', bounds } };+ next.statuses = pruneStatuses(next);+ return next;+}++/** Reshape a polygon grid to new vertices, keeping the lattice and every mark+ * still inside it. Marks on cells the new shape no longer touches are dropped. */+export function resizePolygon(grid, vertices) {+ const next = { ...grid, aoi: { type: 'polygon', vertices } };+ next.statuses = pruneStatuses(next);+ return next;+}diff --git a/frontend/src/lib/gridSearch.test.js b/frontend/src/lib/gridSearch.test.jsnew file mode 100644index 0000000..89563e5--- /dev/null+++ b/frontend/src/lib/gridSearch.test.js@@ -0,0 +1,242 @@+import { describe, it, expect } from 'vitest';+import {+ degSteps,+ aoiBounds,+ createGrid,+ cellKey,+ parseKey,+ cellRange,+ cellBounds,+ cellCenter,+ pointInPolygon,+ rectIntersectsPolygon,+ estimateCells,+ cellsInAoi,+ coverage,+ cycleStatus,+ nextUnchecked,+ pruneStatuses,+ resizeRect,+ resizePolygon,+} from './gridSearch.js';++const rect = (south, west, north, east) => ({ type: 'rect', bounds: { south, west, north, east } });++describe('degSteps', () => {+ it('makes square-ish cells at the equator', () => {+ const { latStep, lonStep } = degSteps(0, 1000);+ expect(latStep).toBeCloseTo(lonStep, 6);+ });++ it('widens the lon step with latitude (cells stay ~metric on the ground)', () => {+ const eq = degSteps(0, 1000);+ const north = degSteps(60, 1000);+ // at 60°N, one metre east spans ~2× the longitude of the equator+ expect(north.lonStep).toBeCloseTo(eq.lonStep * 2, 3);+ expect(north.latStep).toBeCloseTo(eq.latStep, 9);+ });++ it('never blows up at the pole', () => {+ expect(Number.isFinite(degSteps(90, 1000).lonStep)).toBe(true);+ });+});++describe('aoiBounds', () => {+ it('returns rect bounds unchanged', () => {+ expect(aoiBounds(rect(1, 2, 3, 4)).north).toBe(3);+ });++ it('computes the bbox of a polygon', () => {+ const b = aoiBounds({ type: 'polygon', vertices: [[0, 0], [2, 1], [1, 3]] });+ expect(b).toEqual({ south: 0, west: 0, north: 2, east: 3 });+ });+});++describe('cellKey / parseKey', () => {+ it('round-trips, including negative indices', () => {+ expect(parseKey(cellKey(-3, 7))).toEqual([-3, 7]);+ });+});++describe('createGrid', () => {+ it('anchors the lattice at the south-west corner', () => {+ const g = createGrid(rect(48, 2, 48.02, 2.02), 500);+ expect(g.anchor).toEqual({ lat: 48, lon: 2 });+ expect(g.statuses).toEqual({});+ expect(g.cell_m).toBe(500);+ });+});++describe('cellRange / cellBounds', () => {+ it('covers the whole box and tiles it without gaps', () => {+ const g = createGrid(rect(0, 0, 0.03, 0.03), 1000); // ~0.009° cells+ const { iMin, iMax, jMin, jMax } = cellRange(g);+ expect(iMin).toBe(0);+ // cell 0 starts at the anchor; consecutive cells share an edge+ const c0 = cellBounds(g, 0, 0);+ const c1 = cellBounds(g, 1, 0);+ expect(c1.south).toBeCloseTo(c0.north, 9);+ // the top cell reaches past the northern edge (full coverage)+ expect(cellBounds(g, iMax, jMax).north).toBeGreaterThanOrEqual(0.03);+ });+});++describe('cellCenter', () => {+ it('is the midpoint of the cell bounds', () => {+ const g = createGrid(rect(0, 0, 0.01, 0.01), 1000);+ const b = cellBounds(g, 0, 0);+ const c = cellCenter(g, 0, 0);+ expect(c.lat).toBeCloseTo((b.south + b.north) / 2, 12);+ expect(c.lon).toBeCloseTo((b.west + b.east) / 2, 12);+ });+});++describe('pointInPolygon', () => {+ const square = [[0, 0], [0, 2], [2, 2], [2, 0]];+ it('is true inside', () => {+ expect(pointInPolygon({ lat: 1, lon: 1 }, square)).toBe(true);+ });+ it('is false outside', () => {+ expect(pointInPolygon({ lat: 3, lon: 1 }, square)).toBe(false);+ });+});++describe('rectIntersectsPolygon', () => {+ const tri = [[0, 0], [0, 4], [4, 0]]; // region lat>=0, lon>=0, lat+lon<=4+ it('is true when the polygon clips a cell corner (centre outside)', () => {+ // centre (2, 2.5) has lat+lon=4.5 → outside; SW corner (1.5, 2) sums to+ // 3.5 → inside. A strict centre test would wrongly drop this edge cell.+ const cell = { south: 1.5, west: 2, north: 2.5, east: 3 };+ expect(pointInPolygon({ lat: 2, lon: 2.5 }, tri)).toBe(false);+ expect(rectIntersectsPolygon(cell, tri)).toBe(true);+ });+ it('is false for a cell the polygon never touches', () => {+ expect(rectIntersectsPolygon({ south: 5, west: 5, north: 6, east: 6 }, tri)).toBe(false);+ });+});++describe('cellsInAoi', () => {+ it('fills a rectangle completely', () => {+ const g = createGrid(rect(0, 0, 0.02, 0.03), 1000);+ const { iMin, iMax, jMin, jMax } = cellRange(g);+ const expected = (iMax - iMin + 1) * (jMax - jMin + 1);+ expect(cellsInAoi(g).length).toBe(expected);+ });++ it('keeps only centres inside a polygon', () => {+ // a big triangle covering roughly half of its bounding box+ const g = createGrid(+ { type: 'polygon', vertices: [[0, 0], [0, 0.05], [0.05, 0]] },+ 1000+ );+ const inside = cellsInAoi(g).length;+ const box = estimateCells(g);+ expect(inside).toBeGreaterThan(0);+ expect(inside).toBeLessThan(box); // the polygon prunes corner cells+ });+ it('covers the full polygon: cells only clipping an edge are included', () => {+ // a slanted triangle: with a strict centre test, the diagonal edge would+ // leave a bare staircase of half-cells; intersection tiling fills them+ const aoi = { type: 'polygon', vertices: [[0, 0], [0, 0.05], [0.05, 0]] };+ const g = createGrid(aoi, 1000);+ // every cell whose centre is inside is a subset of the cells that overlap+ const overlap = cellsInAoi(g).length;+ let centres = 0;+ const { iMin, iMax, jMin, jMax } = cellRange(g);+ for (let i = iMin; i <= iMax; i++)+ for (let j = jMin; j <= jMax; j++)+ if (pointInPolygon(cellCenter(g, i, j), aoi.vertices)) centres++;+ expect(overlap).toBeGreaterThan(centres);+ });});++describe('coverage', () => {+ it('tallies cleared / flagged / unchecked and a percentage', () => {+ const g = createGrid(rect(0, 0, 0.02, 0.02), 1000);+ const cells = cellsInAoi(g);+ g.statuses[cellKey(...cells[0])] = 'cleared';+ g.statuses[cellKey(...cells[1])] = 'flagged';+ const cov = coverage(g);+ expect(cov.total).toBe(cells.length);+ expect(cov.cleared).toBe(1);+ expect(cov.flagged).toBe(1);+ expect(cov.unchecked).toBe(cells.length - 2);+ expect(cov.percent).toBe(Math.round((2 / cells.length) * 100));+ });++ it('is 0% for an empty grid', () => {+ const g = createGrid(rect(0, 0, 0.01, 0.01), 1000);+ expect(coverage(g).percent).toBe(0);+ });+});++describe('cycleStatus', () => {+ it('goes unchecked -> cleared -> flagged -> unchecked', () => {+ expect(cycleStatus(undefined)).toBe('cleared');+ expect(cycleStatus('cleared')).toBe('flagged');+ expect(cycleStatus('flagged')).toBe(null);+ });+});++describe('nextUnchecked', () => {+ it('walks unchecked cells and wraps', () => {+ const g = createGrid(rect(0, 0, 0.03, 0.03), 1000);+ const first = nextUnchecked(g, null);+ expect(first).not.toBeNull();+ g.statuses[cellKey(...first)] = 'cleared';+ const second = nextUnchecked(g, cellKey(...first));+ expect(cellKey(...second)).not.toBe(cellKey(...first));+ });++ it('returns null once every cell is marked', () => {+ const g = createGrid(rect(0, 0, 0.01, 0.01), 1000);+ for (const [i, j] of cellsInAoi(g)) g.statuses[cellKey(i, j)] = 'cleared';+ expect(nextUnchecked(g, null)).toBeNull();+ });+});++describe('resizeRect', () => {+ it('keeps the lattice fixed and preserves surviving marks', () => {+ const g = createGrid(rect(0, 0, 0.02, 0.02), 1000);+ const anchor = { ...g.anchor };+ const step = g.lat_step;+ const cells = cellsInAoi(g);+ g.statuses[cellKey(...cells[0])] = 'cleared';+ // grow the box: anchor and step must not move, the mark must stay+ const grown = resizeRect(g, { south: -0.02, west: -0.02, north: 0.04, east: 0.04 });+ expect(grown.anchor).toEqual(anchor);+ expect(grown.lat_step).toBe(step);+ expect(grown.statuses[cellKey(...cells[0])]).toBe('cleared');+ });++ it('drops marks that fall outside the shrunken area', () => {+ const g = createGrid(rect(0, 0, 0.04, 0.04), 1000);+ const cells = cellsInAoi(g);+ const far = cells[cells.length - 1]; // a north-east cell+ g.statuses[cellKey(...far)] = 'flagged';+ const shrunk = resizeRect(g, { south: 0, west: 0, north: 0.01, east: 0.01 });+ expect(shrunk.statuses[cellKey(...far)]).toBeUndefined();+ });+});++describe('pruneStatuses', () => {+ it('removes keys with no cell in the area', () => {+ const g = createGrid(rect(0, 0, 0.02, 0.02), 1000);+ g.statuses['999:999'] = 'cleared';+ expect(pruneStatuses(g)['999:999']).toBeUndefined();+ });+});++describe('resizePolygon', () => {+ it('keeps the lattice fixed and preserves surviving marks', () => {+ const aoi = { type: 'polygon', vertices: [[0, 0], [0, 0.03], [0.03, 0.03], [0.03, 0]] };+ const g = createGrid(aoi, 1000);+ const anchor = { ...g.anchor };+ const cells = cellsInAoi(g);+ g.statuses[cellKey(...cells[0])] = 'cleared';+ // nudge one vertex outward: anchor/step stay, the SW-corner mark survives+ const grown = resizePolygon(g, [[0, 0], [0, 0.04], [0.04, 0.04], [0.04, 0]]);+ expect(grown.anchor).toEqual(anchor);+ expect(grown.aoi.type).toBe('polygon');+ expect(grown.statuses[cellKey(...cells[0])]).toBe('cleared');+ });+});diff --git a/frontend/src/lib/reverseSearch.js b/frontend/src/lib/reverseSearch.jsnew file mode 100644index 0000000..a579433--- /dev/null+++ b/frontend/src/lib/reverseSearch.js@@ -0,0 +1,29 @@+// Reverse image search — a launcher, not a search. Azimut never queries these+// engines itself (no scraping, no keys, principle 4 "orchestrate, don't+// replace"): it opens each engine's search page and hands the analyst the+// image, either on the clipboard (paste engines) or as a saved file (drag+// engines). Case work is always a local file or a video frame, never a public+// image URL, so there is no by-URL path. Pure data, kept DOM-free so it tests.+//+// `paste: true` marks the engines whose search page accepts a pasted image+// (Ctrl+V); the rest are drag-and-drop only.+const ENGINES = [+ { id: 'google', label: 'Google Lens', page: 'https://lens.google.com/', paste: true },+ // Yandex's page has no paste target in practice — it wants a file, so it sits+ // with the drag engines.+ { id: 'yandex', label: 'Yandex', page: 'https://yandex.com/images/', paste: false },+ { id: 'bing', label: 'Bing', page: 'https://www.bing.com/visualsearch', paste: false },+ { id: 'tineye', label: 'TinEye', page: 'https://tineye.com/', paste: false },+];++/**+ * Each engine's search page. `paste` flags the ones that take a clipboard image+ * (Ctrl+V), so the tool can split the copy-and-open hand-off from the+ * save-and-drag one.+ */+export const UPLOAD_PAGES = ENGINES.map((e) => ({+ id: e.id,+ label: e.label,+ url: e.page,+ paste: e.paste,+}));diff --git a/frontend/src/lib/reverseSearch.test.js b/frontend/src/lib/reverseSearch.test.jsnew file mode 100644index 0000000..99fc8f5--- /dev/null+++ b/frontend/src/lib/reverseSearch.test.js@@ -0,0 +1,24 @@+import { describe, it, expect } from 'vitest';+import { UPLOAD_PAGES } from './reverseSearch.js';++describe('UPLOAD_PAGES', () => {+ const byId = Object.fromEntries(UPLOAD_PAGES.map((p) => [p.id, p]));++ it('covers the four key-less engines', () => {+ expect(Object.keys(byId).sort()).toEqual(['bing', 'google', 'tineye', 'yandex']);+ });++ it('gives every engine a label and an https search page', () => {+ for (const { label, url } of UPLOAD_PAGES) {+ expect(label).toBeTruthy();+ expect(url.startsWith('https://')).toBe(true);+ }+ });++ it('flags Google Lens as the only paste engine; the rest are drag-only', () => {+ expect(byId.google.paste).toBe(true);+ expect(byId.yandex.paste).toBe(false);+ expect(byId.bing.paste).toBe(false);+ expect(byId.tineye.paste).toBe(false);+ });+});diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.jsindex 70be87c..9821865 100644--- a/frontend/src/lib/workspaces.js+++ b/frontend/src/lib/workspaces.js@@ -10,9 +10,9 @@* layer (today the case sidebar covers it).*/export const WORKSPACES = [- { id: 'collect', label: 'Collect', icon: 'download', tools: ['media', 'files'] },+ { id: 'collect', label: 'Collect', icon: 'download', tools: ['media', 'files', 'reverse'] },{ id: 'examine', label: 'Examine', icon: 'inspect', tools: ['inspect'] },- { id: 'map', label: 'Map', icon: 'satellite', tools: ['satellite'] },+ { id: 'map', label: 'Map', icon: 'satellite', tools: ['satellite', 'coordinates'] },{ id: 'compose', label: 'Compose', icon: 'proof', tools: ['proof', 'post'] },];diff --git a/frontend/src/lib/workspaces.test.js b/frontend/src/lib/workspaces.test.jsindex d8132be..f43f89c 100644--- a/frontend/src/lib/workspaces.test.js+++ b/frontend/src/lib/workspaces.test.js@@ -1,20 +1,28 @@import { describe, it, expect } from 'vitest';import { WORKSPACES, workspaceOf, toolFromHash } from './workspaces.js';-const ALL_TOOLS = ['media', 'files', 'inspect', 'satellite', 'proof', 'post', 'settings'];+const ALL_TOOLS = [+ 'media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post', 'settings',+];describe('workspaceOf', () => {it('maps every rail tool to exactly one workspace', () => {- for (const tool of ['media', 'files', 'inspect', 'satellite', 'proof', 'post']) {+ for (const tool of ['media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post']) {const owners = WORKSPACES.filter((w) => w.tools.includes(tool));expect(owners).toHaveLength(1);expect(workspaceOf(tool)).toBe(owners[0]);}});- it('groups media and files under collect', () => {+ it('groups media, files and reverse search under collect', () => {expect(workspaceOf('media').id).toBe('collect');expect(workspaceOf('files').id).toBe('collect');+ expect(workspaceOf('reverse').id).toBe('collect');+ });++ it('groups satellite and coordinates under map', () => {+ expect(workspaceOf('satellite').id).toBe('map');+ expect(workspaceOf('coordinates').id).toBe('map');});it('groups proof and post under compose', () => {diff --git a/frontend/src/tools/Coordinates.svelte b/frontend/src/tools/Coordinates.sveltenew file mode 100644index 0000000..f29dddc--- /dev/null+++ b/frontend/src/tools/Coordinates.svelte@@ -0,0 +1,277 @@+<script>+ // Coordinates — paste one point in any notation, read it back in every+ // other, and jump to the nine external maps. Conversion runs on the local+ // backend; converting also triggers a Nominatim reverse-geocode for the+ // place name (the app's local-first rule names geocoding as one of the+ // actions that inherently needs the network), reported as "Not available"+ // if that call fails.+ import { api } from '../lib/api.js';+ import { toast, uiState } from '../lib/state.svelte.js';+ import { mapLinks } from '../lib/maplinks.js';+ import { bidiSafe } from '../lib/bidi.js';+ import Icon from '../components/Icon.svelte';++ // Mirrors the label order of engine/geo.py's all_formats(), so the empty+ // state can preview the field list before any coordinate is parsed.+ const EMPTY_FORMATS = [+ { id: 'dd', label: 'Decimal' },+ { id: 'ddm', label: 'Deg. decimal min.' },+ { id: 'dms', label: 'Deg. min. sec.' },+ { id: 'utm', label: 'UTM' },+ { id: 'mgrs', label: 'MGRS' },+ { id: 'plus_code', label: 'Plus code' },+ { id: 'geohash', label: 'Geohash' },+ ];++ let text = $state('');+ let point = $state(null); // { lat, lon, formats: [{id,label,value}] }+ let parsing = $state(false);+ let place = $state(null); // reverse-geocode result+ let placeLoading = $state(false);++ // Link labels don't depend on lat/lon, so this also drives the empty-state preview.+ const links = $derived(mapLinks(point?.lat ?? 0, point?.lon ?? 0));++ async function parse() {+ const value = text.trim();+ if (!value || parsing) return;+ parsing = true;+ place = null;+ try {+ point = await api.post('/api/geo/parse', { text: value });+ lookupPlace();+ } catch {+ point = null;+ toast('Could not read a coordinate from that', 'danger');+ } finally {+ parsing = false;+ }+ }++ async function copy(value) {+ await navigator.clipboard.writeText(bidiSafe(value));+ toast('Copied', 'ok', 1400);+ }++ async function lookupPlace() {+ if (!point) return;+ placeLoading = true;+ try {+ const res = await api.get(`/api/geo/reverse?lat=${point.lat}&lon=${point.lon}`);+ place = res.display_name || 'Not available';+ } catch {+ place = 'Not available';+ } finally {+ placeLoading = false;+ }+ }++ // Hand the point to the Satellite map and switch tabs; it consumes+ // uiState.gotoCoords on the next tick and flies there (lib/navigate.js).+ function openInSatellite() {+ if (!point) return;+ uiState.gotoCoords = { lat: point.lat, lon: point.lon };+ uiState.tool = 'satellite';+ }+</script>++<div class="tool">+ <div class="tool-header">+ <h2>Coordinates</h2>+ </div>++ <div class="tool-body">+ <form+ class="go-form"+ onsubmit={(e) => {+ e.preventDefault();+ parse();+ }}+ >+ <input+ class="input"+ placeholder={'Paste any coordinate: 48.8584, 2.2945 · DMS · UTM · MGRS · plus code · geohash'}+ bind:value={text}+ title="Decimal, degrees-minutes-seconds, degrees-decimal-minutes, UTM, MGRS, plus code or geohash"+ />+ <button type="submit" class="btn" disabled={!text.trim() || parsing}>+ <Icon name="search" size={15} /> {parsing ? '…' : 'Convert'}+ </button>+ </form>++ <div class="sheet">+ <div class="head-row">+ <span class="place" class:muted={!point || placeLoading}>+ {#if !point}+ Paste a coordinate to read it back in every notation.+ {:else if placeLoading}+ Resolving place…+ {:else}+ {place}+ {/if}+ </span>+ <button+ class="btn btn-sm"+ disabled={!point}+ onclick={openInSatellite}+ title="Open this point on the Satellite map"+ >+ <Icon name="crosshair" size={14} /> View in Satellite+ </button>+ </div>++ <div class="formats">+ {#if point}+ {#each point.formats as f (f.id)}+ <button class="row" onclick={() => copy(f.value)} title="Copy">+ <span class="k">{f.label}</span>+ <span class="v mono">{f.value}</span>+ <Icon name="copy" size={13} />+ </button>+ {/each}+ {:else}+ {#each EMPTY_FORMATS as f (f.id)}+ <div class="row row-empty">+ <span class="k">{f.label}</span>+ <span class="v mono">–</span>+ </div>+ {/each}+ {/if}+ </div>++ <div class="open-on">+ <span class="open-label">Open on</span>+ <div class="links">+ {#each links as l (l.id)}+ {#if point}+ <a class="ext-link" href={l.url} target="_blank" rel="noreferrer">+ {l.label}<Icon name="external" size={11} />+ </a>+ {:else}+ <span class="ext-link disabled">{l.label}</span>+ {/if}+ {/each}+ </div>+ </div>+ </div>+ </div>+</div>++<style>+ .go-form {+ display: flex;+ gap: 8px;+ align-items: center;+ padding: 16px 16px 0;+ max-width: 720px;+ }+ .go-form .input {+ flex: 1;+ }+ .sheet {+ display: flex;+ flex-direction: column;+ padding: 16px;+ max-width: 720px;+ }+ .head-row {+ display: flex;+ align-items: center;+ gap: 12px;+ padding-bottom: 12px;+ border-bottom: 1px solid var(--border);+ }+ .head-row .place {+ flex: 1;+ min-width: 0;+ font-size: var(--fs-md);+ color: var(--text-1);+ overflow-wrap: anywhere;+ }+ .head-row .place.muted {+ color: var(--text-3);+ }+ .head-row .btn {+ flex-shrink: 0;+ white-space: nowrap;+ }+ .formats {+ display: flex;+ flex-direction: column;+ padding: 4px 0;+ border-bottom: 1px solid var(--border);+ }+ .row {+ display: grid;+ grid-template-columns: 150px 1fr auto;+ align-items: center;+ gap: 12px;+ padding: 7px 8px;+ text-align: left;+ background: none;+ border: 0;+ border-radius: 4px;+ color: inherit;+ cursor: pointer;+ }+ .row:hover {+ background: var(--bg-2);+ }+ .row .k {+ color: var(--text-3);+ font-size: var(--fs-sm);+ }+ .row .v {+ overflow-wrap: anywhere;+ }+ .row :global(svg) {+ color: var(--text-3);+ opacity: 0;+ }+ .row:hover :global(svg) {+ opacity: 1;+ }+ .row-empty {+ cursor: default;+ }+ .row-empty .v {+ color: var(--text-3);+ }+ .open-on {+ display: flex;+ align-items: baseline;+ gap: 14px;+ padding-top: 14px;+ }+ .open-label {+ flex-shrink: 0;+ font-size: var(--fs-xs);+ color: var(--text-3);+ }+ .links {+ display: flex;+ flex-wrap: wrap;+ gap: 6px 14px;+ }+ .ext-link {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ font-size: var(--fs-sm);+ color: var(--text-2);+ text-decoration: none;+ }+ .ext-link :global(svg) {+ color: var(--text-3);+ }+ .ext-link:hover {+ color: var(--accent);+ }+ .ext-link:hover :global(svg) {+ color: var(--accent);+ }+ .ext-link.disabled {+ color: var(--text-3);+ opacity: 0.6;+ }+</style>diff --git a/frontend/src/tools/ReverseSearch.svelte b/frontend/src/tools/ReverseSearch.sveltenew file mode 100644index 0000000..d271a98--- /dev/null+++ b/frontend/src/tools/ReverseSearch.svelte@@ -0,0 +1,550 @@+<script>+ // Reverse Search Launcher — builds the reverse-image hand-off for the four+ // key-less engines. Azimut never runs the search itself (principle 4): it+ // preps the image (clipboard for paste engines, a saved file for drag ones)+ // and each button is a plain link to the engine's page.+ //+ // Pick a case photo, or scrub a case video to a frame. Adjustments+ // (brightness, contrast, …) preview live and are baked into the exported+ // image via a same-origin canvas — nothing leaves the machine until an+ // engine tab is opened by the analyst.+ import { api } from '../lib/api.js';+ import { caseState, uiState, toast } from '../lib/state.svelte.js';+ import { UPLOAD_PAGES } from '../lib/reverseSearch.js';+ import Modal from '../components/Modal.svelte';+ import Icon from '../components/Icon.svelte';++ const PASTE = UPLOAD_PAGES.filter((e) => e.paste);+ const DRAG = UPLOAD_PAGES.filter((e) => !e.paste);++ let pickerOpen = $state(false);+ let mediaLibrary = $state([]);+ let selected = $state(null); // the chosen media item, or null+ let videoEl = $state(null); // the <video> element, when a video is selected++ // -- adjustments (client-side CSS filters, baked into the export) -----------+ const NEUTRAL = { brightness: 100, contrast: 100, saturate: 100, grayscale: 0 };+ let adjust = $state({ ...NEUTRAL });+ let adjustOpen = $state(false);+ const filterCss = $derived(+ `brightness(${adjust.brightness}%) contrast(${adjust.contrast}%) ` ++ `saturate(${adjust.saturate}%) grayscale(${adjust.grayscale}%)`+ );+ const adjusted = $derived(+ adjust.brightness !== 100 ||+ adjust.contrast !== 100 ||+ adjust.saturate !== 100 ||+ adjust.grayscale !== 0+ );+ const resetAdjust = () => (adjust = { ...NEUTRAL });++ const srcOf = (item) => `/files/${caseState.current.id}/${item.path}`;+ const nameOf = (item) => (item.label || item.path).replace(/^media\//, '');+ const frameLabel = $derived(selected?.kind === 'video' ? 'frame' : 'image');++ // -- picker -----------------------------------------------------------------+ async function openPicker() {+ if (!caseState.current) {+ toast('Open a case to search its media', 'warn');+ return;+ }+ try {+ mediaLibrary = await api.get(`/api/cases/${caseState.current.id}/media`);+ pickerOpen = true;+ } catch (e) {+ toast(e.message, 'danger');+ }+ }++ function pickMedia(item) {+ selected = item;+ resetAdjust();+ pickerOpen = false;+ }++ function discard() {+ selected = null;+ resetAdjust();+ adjustOpen = false;+ }++ // -- selection → PNG blob ---------------------------------------------------+ // Always drawn through a canvas so the adjustments bake in; an image gets+ // loaded, a video is sampled at its current playhead.+ function loadImage(src) {+ return new Promise((resolve, reject) => {+ const img = new Image();+ img.onload = () => resolve(img);+ img.onerror = () => reject(new Error('Could not read the image'));+ img.src = src;+ });+ }++ async function pngBlob() {+ let source, w, h;+ if (selected.kind === 'video') {+ if (!videoEl || !videoEl.videoWidth) {+ throw new Error('Let the video load, then scrub to the frame you want');+ }+ source = videoEl;+ w = videoEl.videoWidth;+ h = videoEl.videoHeight;+ } else {+ source = await loadImage(srcOf(selected));+ w = source.naturalWidth;+ h = source.naturalHeight;+ }+ const canvas = document.createElement('canvas');+ canvas.width = w;+ canvas.height = h;+ const ctx = canvas.getContext('2d');+ ctx.filter = filterCss;+ ctx.drawImage(source, 0, 0, w, h);+ return new Promise((resolve, reject) =>+ canvas.toBlob(+ (b) => (b ? resolve(b) : reject(new Error('Could not encode the image'))),+ 'image/png'+ )+ );+ }++ // -- hand-off (buttons are real links, so nothing is popup-blocked) ---------+ async function copySelection() {+ try {+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': pngBlob() })]);+ toast(`Copied the ${frameLabel} — paste it (Ctrl+V) in the tab`, 'ok', 4500);+ } catch (e) {+ toast(e.message || 'Could not copy the image', 'warn');+ }+ }++ async function saveSelection() {+ try {+ const blob = await pngBlob();+ const base = nameOf(selected).replace(/^.*\//, '').replace(/\.[^.]+$/, '');+ const a = document.createElement('a');+ a.href = URL.createObjectURL(blob);+ a.download = `reverse-${base}.png`;+ a.click();+ URL.revokeObjectURL(a.href);+ toast(`Saved the ${frameLabel} — drag it into the tab`, 'ok', 4500);+ } catch (e) {+ toast(e.message || 'Could not save the image', 'warn');+ }+ }++ function openInInspect() {+ uiState.inspectPath = selected.path;+ uiState.tool = 'inspect';+ }++ const SLIDERS = [+ { id: 'brightness', label: 'Brightness', min: 0, max: 200 },+ { id: 'contrast', label: 'Contrast', min: 0, max: 200 },+ { id: 'saturate', label: 'Saturation', min: 0, max: 200 },+ { id: 'grayscale', label: 'Grayscale', min: 0, max: 100 },+ ];+</script>++<div class="tool">+ <div class="tool-header">+ <h2>Reverse Search</h2>+ {#if selected}<span class="sub">Copy or save the {frameLabel}, then hand it to an engine</span>{/if}+ </div>++ <div class="tool-body">+ {#if !selected}+ <div class="empty" style="height: 100%">+ <div class="empty-icon"><Icon name="search" size={42} /></div>+ <h3>Reverse image search</h3>+ <p>Pick a case photo, or a video to grab a frame from, then send it to the engines.</p>+ <button class="btn btn-primary" onclick={openPicker}>+ <Icon name="image" size={15} /> Pick from case+ </button>+ <div class="fallback">+ <span class="eg-head">Or open an engine and drag any file in</span>+ <div class="engine-links">+ {#each UPLOAD_PAGES as e (e.id)}+ <a href={e.url} target="_blank" rel="noreferrer" class="engine-link">+ {e.label} <Icon name="external" size={12} />+ </a>+ {/each}+ </div>+ </div>+ </div>+ {:else}+ <div class="work">+ <div class="preview-col">+ <div class="preview-panel card">+ <div class="preview-bar">+ <span class="file">+ <Icon name={selected.kind === 'video' ? 'video' : 'image'} size={13} />+ <span class="name" title={selected.path}>{nameOf(selected)}</span>+ </span>+ <span class="bar-actions">+ <button class="btn btn-ghost btn-sm" onclick={openPicker}>Change</button>+ <button class="btn btn-ghost btn-sm" onclick={discard}>+ <Icon name="x" size={13} /> Discard+ </button>+ </span>+ </div>+ <div class="preview">+ {#if selected.kind === 'video'}+ <!-- svelte-ignore a11y_media_has_caption -->+ <video+ bind:this={videoEl}+ src={srcOf(selected)}+ controls+ preload="metadata"+ style="filter: {filterCss}"+ ></video>+ {:else}+ <img src={srcOf(selected)} alt={nameOf(selected)} style="filter: {filterCss}" />+ {/if}+ </div>+ </div>+ {#if selected.kind === 'video'}+ <p class="hint">Scrub to the moment, then copy or save the frame.</p>+ {/if}+ </div>++ <div class="controls-col">+ <div class="adjust">+ <button+ class="adjust-toggle"+ class:on={adjustOpen}+ onclick={() => (adjustOpen = !adjustOpen)}+ >+ <Icon name="sliders" size={14} /> Adjust+ {#if adjusted && !adjustOpen}<span class="dot" title="Edited"></span>{/if}+ </button>+ {#if adjustOpen}+ <div class="sliders">+ {#each SLIDERS as s (s.id)}+ <label class="slider">+ <span class="lbl">{s.label}</span>+ <input type="range" min={s.min} max={s.max} bind:value={adjust[s.id]} />+ <span class="val mono">{adjust[s.id]}</span>+ </label>+ {/each}+ <button class="btn btn-ghost btn-sm reset" onclick={resetAdjust} disabled={!adjusted}>+ Reset+ </button>+ </div>+ {/if}+ </div>++ <div class="engines">+ <div class="eg-group">+ <span class="eg-head">Copy, then paste (Ctrl+V) in the tab</span>+ <div class="eg-list">+ {#each PASTE as e (e.id)}+ <a href={e.url} target="_blank" rel="noreferrer" class="btn engine-btn" onclick={copySelection}>+ <Icon name="copy" size={14} /> {e.label}+ </a>+ {/each}+ </div>+ </div>+ <div class="eg-group">+ <span class="eg-head">Save, then drag the file into the tab</span>+ <div class="eg-list">+ {#each DRAG as e (e.id)}+ <a href={e.url} target="_blank" rel="noreferrer" class="btn engine-btn" onclick={saveSelection}>+ <Icon name="download" size={14} /> {e.label}+ </a>+ {/each}+ </div>+ </div>+ </div>++ {#if selected.kind === 'video'}+ <button class="btn btn-ghost btn-sm inspect-link" onclick={openInInspect}>+ <Icon name="crop" size={13} /> Finer control in Inspect+ </button>+ {/if}+ </div>+ </div>+ {/if}+ </div>+</div>++{#if pickerOpen}+ <Modal title="Pick a case image or video" width="640px" onclose={() => (pickerOpen = false)}>+ {#if mediaLibrary.length === 0}+ <p class="picker-empty">No media in this case yet. Import or download some in the Media tab.</p>+ {:else}+ <div class="picker-grid">+ {#each mediaLibrary as item (item.path)}+ <button class="picker-item" onclick={() => pickMedia(item)} title={item.path}>+ <div class="picker-thumb">+ {#if item.thumbnail}+ <img src={`/files/${caseState.current.id}/${item.thumbnail}`} alt={item.path} />+ {:else}+ <Icon name={item.kind === 'video' ? 'video' : 'image'} size={24} />+ {/if}+ {#if item.kind === 'video'}<span class="kind-badge"><Icon name="video" size={11} /></span>{/if}+ </div>+ <span class="picker-name">{nameOf(item)}</span>+ </button>+ {/each}+ </div>+ {/if}+ </Modal>+{/if}++<style>+ .tool-body {+ padding: 20px;+ }+ .hint {+ font-size: var(--fs-sm);+ color: var(--text-3);+ }++ /* empty state — shared .empty primitive, with the engine fallback below */+ .fallback {+ margin-top: 22px;+ padding-top: 20px;+ border-top: 1px solid var(--border);+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 10px;+ width: 100%;+ max-width: 360px;+ }+ .engine-links {+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ gap: 6px 18px;+ }+ .engine-link {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ color: var(--text-2);+ font-size: var(--fs-sm);+ }+ .engine-link:hover {+ color: var(--text-1);+ text-decoration: none;+ }+ .engine-link :global(svg) {+ color: var(--text-3);+ }++ /* working layout */+ .work {+ display: flex;+ gap: 24px;+ flex-wrap: wrap;+ align-items: flex-start;+ }+ .preview-col {+ flex: 1 1 460px;+ min-width: 320px;+ max-width: 660px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ }+ .preview-panel {+ overflow: hidden;+ }+ .preview-bar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 6px 8px 6px 12px;+ border-bottom: 1px solid var(--border);+ background: var(--bg-2);+ }+ .file {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ min-width: 0;+ color: var(--text-2);+ }+ .file :global(svg) {+ color: var(--text-3);+ flex-shrink: 0;+ }+ .name {+ font-size: var(--fs-sm);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .bar-actions {+ display: inline-flex;+ gap: 2px;+ flex-shrink: 0;+ }+ .preview {+ background: var(--bg-0);+ display: flex;+ justify-content: center;+ }+ .preview img,+ .preview video {+ display: block;+ max-width: 100%;+ max-height: 64vh;+ object-fit: contain;+ }++ .controls-col {+ flex: 1 1 300px;+ min-width: 260px;+ display: flex;+ flex-direction: column;+ gap: 20px;+ }+ .eg-head {+ display: block;+ text-transform: uppercase;+ font-size: var(--fs-xs);+ letter-spacing: 0.06em;+ color: var(--text-3);+ margin-bottom: 8px;+ }+ .engines {+ display: flex;+ flex-direction: column;+ gap: 18px;+ }+ .eg-list {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ }+ .engine-btn {+ flex: 1 1 auto;+ justify-content: center;+ min-width: 120px;+ }+ .reset {+ align-self: flex-end;+ }+ .inspect-link {+ align-self: flex-start;+ }++ /* adjust panel */+ .adjust-toggle {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ padding: 6px 10px;+ background: var(--bg-2);+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ color: var(--text-2);+ font-size: var(--fs-sm);+ cursor: pointer;+ }+ .adjust-toggle:hover,+ .adjust-toggle.on {+ border-color: var(--border-strong);+ color: var(--text-1);+ }+ .dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--accent);+ }+ .sliders {+ display: flex;+ flex-direction: column;+ gap: 9px;+ margin-top: 10px;+ padding: 12px;+ background: var(--bg-1);+ border: 1px solid var(--border);+ border-radius: 4px;+ }+ .slider {+ display: grid;+ grid-template-columns: 84px 1fr 34px;+ align-items: center;+ gap: 10px;+ font-size: var(--fs-sm);+ }+ .slider .lbl {+ color: var(--text-2);+ }+ .slider input[type='range'] {+ width: 100%;+ accent-color: var(--accent);+ }+ .slider .val {+ text-align: right;+ color: var(--text-3);+ font-size: var(--fs-xs);+ }+ .reset {+ align-self: flex-end;+ margin-top: 2px;+ }++ /* picker modal */+ .picker-empty {+ color: var(--text-3);+ font-size: var(--fs-sm);+ padding: 8px;+ }+ .picker-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));+ gap: 8px;+ }+ .picker-item {+ display: flex;+ flex-direction: column;+ gap: 5px;+ padding: 6px;+ background: var(--bg-2);+ border: 1px solid var(--border);+ border-radius: 4px;+ cursor: pointer;+ text-align: left;+ }+ .picker-item:hover {+ border-color: var(--border-strong);+ }+ .picker-thumb {+ position: relative;+ aspect-ratio: 4 / 3;+ display: flex;+ align-items: center;+ justify-content: center;+ background: var(--bg-0);+ border-radius: 3px;+ overflow: hidden;+ color: var(--text-3);+ }+ .picker-thumb img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .kind-badge {+ position: absolute;+ bottom: 3px;+ right: 3px;+ display: inline-flex;+ padding: 2px;+ background: rgba(0, 0, 0, 0.6);+ border-radius: 3px;+ }+ .picker-name {+ font-size: var(--fs-xs);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+</style>diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex 86da1ca..c9bf1a9 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -8,6 +8,7 @@} from '../lib/state.svelte.js';import { mapLinks } from '../lib/maplinks.js';import * as measure from '../lib/measure.js';+ import * as gridSearch from '../lib/gridSearch.js';import { dragBearing, pivotPanOffset } from '../lib/satRotate.js';import { SIZE_MIN, SIZE_MAX, clampSize, scaledCapture } from '../lib/captureSize.js';import { isRegistered, sourceRect, frameFitsView } from '../lib/screenCrop.js';@@ -216,6 +217,50 @@// External-maps quick links, in the SAVED panel (item 6).let linksOpen = $state(false);+ // --- Grid Search (spec §5): overlay a metric grid on an area of interest and+ // sweep it cell by cell, marking each cleared or flagged. A case can hold+ // several saved grids (files under search/, working aids, not entities); each+ // action auto-saves. Persists across basemap changes — its own layer group is+ // untouched by setLayer().+ let gridMode = $state(false); // mode armed from the tools bar+ let grid = $state(null); // the open grid spec (lib/gridSearch.js), or null+ let gridName = $state(null); // slug of the open grid's file (drives the picker)+ let gridList = $state([]); // summaries of this case's saved grids (the picker)+ let gridFor = null; // case id the list was loaded for (plain: load-dedup only)+ let gridCollapsed = $state(false); // fold the panel down to its header+ let gridCellM = $state(500); // metric cell size the next area is drawn with+ let gridDraw = $state(null); // null | 'rect' | 'polygon' — drawing an area+ let polyDraft = $state([]); // polygon vertices being placed, [{ lat, lon }]+ let editArea = $state(false); // showing the area box to resize/reshape it+ let gridHidden = $state(false); // eye toggle: keep the grid but hide it on the map+ let renamingGrid = $state(false); // editing the open grid's title inline+ let renameText = $state(''); // the title being typed while renaming+ let reviewKey = $state(null); // 'i:j' of the cell under review, or null+ let gridSaveTimer; // debounce the persist call+ let gridLayer = null; // Leaflet layerGroup of the cells+ let gridAoiLayer = null; // Leaflet layerGroup of the area outline + handles+ let gridDraftLayer = null; // Leaflet layerGroup of the in-progress polygon+ let gridRenderer = null; // one shared canvas renderer for all the cells+ let cellRects = new Map(); // 'i:j' -> Leaflet rectangle (for cheap restyles)+ let aoiOutline = null; // Leaflet path: the area's dashed outline+ let dragBounds = null; // live rect bounds while a corner handle is dragged+ let liveVerts = null; // live polygon vertices while a vertex handle is dragged+ let draftLine = null; // Leaflet polyline of the in-progress polygon+ const gridCov = $derived(grid ? gridSearch.coverage(grid) : null);+ const savedOthers = $derived(gridList.filter((g) => g.name !== gridName));+ const GRID_MAX_CELLS = gridSearch.MAX_CELLS;+ // status → cell paint. Unchecked is a bright thin outline so the lattice reads+ // clearly over dark imagery; cleared greys the cell out; flagged fills yellow+ // (chosen over red so it reads for colour-blind analysts too).+ const CELL_STYLE = {+ unchecked: { color: '#ffffff', weight: 1, opacity: 0.7, fill: true, fillColor: '#fff', fillOpacity: 0 },+ cleared: { color: '#ffffff', weight: 1, opacity: 0.55, fill: true, fillColor: '#2b3040', fillOpacity: 0.62 },+ flagged: { color: '#ffcf33', weight: 1.5, opacity: 1, fill: true, fillColor: '#ffdb4d', fillOpacity: 0.6 },+ };+ const AOI_STYLE = { color: '#f5a623', weight: 1.5, opacity: 0.9, fill: false, dashArray: '5 4', interactive: false };+ const CORNERS = ['sw', 'se', 'nw', 'ne']; // rect resize handles++// --- reference viewers: floating scratch windows over the map that hold a// media image (the shot to geolocate) so you can eyeball it against the// imagery while panning. Session-only (uiState.refViewers) — never captured,@@ -310,6 +355,8 @@// left-drag draws the capture marquee when that mode is armed (capture-phase// so Leaflet's pan handler never sees the gesture)mapEl.addEventListener('mousedown', onSelectStart, true);+ // left-drag draws a Grid Search area when the rectangle tool is armed+ mapEl.addEventListener('mousedown', onGridRectStart, true);window.addEventListener('keydown', onKeydown);document.addEventListener('fullscreenchange', onFullscreenChange);// the user clicked the extension after a refused capture — close the loop@@ -326,9 +373,28 @@});function onKeydown(e) {- if (uiState.tool !== 'satellite' || e.key !== 'Escape') return;- // a dialog on top owns Escape — it closes itself, the map keeps its state+ if (uiState.tool !== 'satellite') return;+ // a dialog on top owns the keyboard — it closes itself, the map keeps stateif (notesItem || placeModal || refPicker || deleteTarget) return;+ const tag = e.target?.tagName;+ const typing = tag === 'INPUT' || tag === 'TEXTAREA' || e.target?.isContentEditable;+ // Enter confirms a polygon area, same as the Confirm button+ if (gridMode && gridDraw === 'polygon' && !typing && e.key === 'Enter' && polyDraft.length >= 3) {+ e.preventDefault();+ confirmPolygon();+ return;+ }+ // Grid Search sweep: single-key marks while a cell is under review+ if (gridMode && reviewKey && !typing) {+ const k = e.key.toLowerCase();+ if (k === ' ' || k === 'c') return void (e.preventDefault(), markReview('cleared'));+ if (k === 'f') return void (e.preventDefault(), markReview('flagged'));+ if (k === 's') return void (e.preventDefault(), reviewAdvance());+ if (k === 'p') return void (e.preventDefault(), reviewToPlace());+ }+ if (e.key !== 'Escape') return;+ if (gridDraw) return cancelGridDraw();+ if (reviewKey) return stopReview();if (selectArmed) toggleSelect();else if (sizeMenuOpen) sizeMenuOpen = false;else if (measureMode) setMeasureMode(null);@@ -638,6 +704,12 @@// --- measure tools (item 5) ---function onMapClick(e) {+ // Grid Search polygon: each click drops a vertex+ if (gridDraw === 'polygon') {+ polyDraft = [...polyDraft, { lat: e.latlng.lat, lon: e.latlng.lng }];+ renderDraft();+ return;+ }if (!measureMode) return;const pt = { lat: e.latlng.lat, lon: e.latlng.lng };// an angle is exactly three points; a fourth click starts a fresh angle@@ -1450,6 +1522,578 @@});}+ // --- Grid Search: layers, drawing, sweeping, persistence -------------------++ function toggleGridMode() {+ gridMode = !gridMode;+ if (gridMode) {+ if (selectArmed) toggleSelect(); // exclusive with the capture marquee…+ if (measureMode) setMeasureMode(null); // …and the measure tools+ gridHidden = false;+ ensureGridLayers();+ refreshGridList();+ if (grid) {+ renderGrid();+ renderAoi();+ }+ } else {+ cancelGridDraw();+ stopReview();+ editArea = false;+ clearGridLayers();+ }+ }++ function ensureGridLayers() {+ if (!map) return;+ if (!gridRenderer) gridRenderer = L.canvas({ padding: 0.5 });+ if (!gridLayer) gridLayer = L.layerGroup();+ if (!gridAoiLayer) gridAoiLayer = L.layerGroup();+ if (!gridDraftLayer) gridDraftLayer = L.layerGroup();+ syncGridVisibility();+ }++ // the eye toggle keeps the grid but drops its layers off the map so you can+ // read the bare imagery underneath, then puts them back+ function syncGridVisibility() {+ if (!map) return;+ for (const lyr of [gridLayer, gridAoiLayer, gridDraftLayer]) {+ if (!lyr) continue;+ const on = map.hasLayer(lyr);+ if (gridHidden && on) map.removeLayer(lyr);+ else if (!gridHidden && !on) map.addLayer(lyr);+ }+ }++ function toggleGridHidden() {+ gridHidden = !gridHidden;+ syncGridVisibility();+ }++ function startRename() {+ if (!grid) return;+ renameText = grid.title || '';+ renamingGrid = true;+ }++ function commitRename() {+ renamingGrid = false;+ if (!grid) return;+ const t = renameText.trim();+ if (t && t !== grid.title) {+ grid.title = t;+ scheduleGridSave();+ }+ }++ function clearGridLayers() {+ cellRects.clear();+ aoiOutline = null;+ draftLine = null;+ gridLayer?.clearLayers();+ gridAoiLayer?.clearLayers();+ gridDraftLayer?.clearLayers();+ }++ function gridHandleIcon() {+ return L.divIcon({ className: 'grid-handle', iconSize: [16, 16], iconAnchor: [8, 8] });+ }++ function cellLatLngBounds(i, j) {+ const b = gridSearch.cellBounds(grid, i, j);+ return [[b.south, b.west], [b.north, b.east]];+ }++ function cellStyle(key) {+ const base = CELL_STYLE[grid?.statuses[key] || 'unchecked'];+ // the cell under review gets a bright cyan outline — distinct from the+ // yellow flag and the grey cleared fill for colour-blind readability+ return key === reviewKey ? { ...base, color: '#33c9ff', weight: 2.5, opacity: 1 } : base;+ }++ function renderGrid() {+ ensureGridLayers();+ gridLayer.clearLayers();+ cellRects.clear();+ if (!grid) return;+ for (const [i, j] of gridSearch.cellsInAoi(grid)) {+ const key = gridSearch.cellKey(i, j);+ const rect = L.rectangle(cellLatLngBounds(i, j), {+ renderer: gridRenderer,+ bubblingMouseEvents: false,+ ...cellStyle(key),+ });+ rect.on('click', (e) => {+ L.DomEvent.stop(e);+ cycleCell(i, j);+ });+ rect.on('contextmenu', (e) => {+ L.DomEvent.stop(e);+ flagCell(i, j);+ });+ rect.addTo(gridLayer);+ cellRects.set(key, rect);+ }+ }++ function restyleCell(key) {+ cellRects.get(key)?.setStyle(cellStyle(key));+ }++ function setReview(key) {+ const prev = reviewKey;+ reviewKey = key;+ if (prev) restyleCell(prev);+ if (key) restyleCell(key);+ }++ function cycleCell(i, j) {+ const key = gridSearch.cellKey(i, j);+ // during a sweep, clicking the cell you're reviewing clears it and moves on+ // (same as the Clear button) — you're looking right at it+ if (reviewKey && key === reviewKey) {+ markReview('cleared');+ return;+ }+ const next = gridSearch.cycleStatus(grid.statuses[key]);+ if (next) grid.statuses[key] = next;+ else delete grid.statuses[key];+ restyleCell(key);+ scheduleGridSave();+ }++ function flagCell(i, j) {+ const key = gridSearch.cellKey(i, j);+ if (grid.statuses[key] === 'flagged') delete grid.statuses[key];+ else grid.statuses[key] = 'flagged';+ restyleCell(key);+ scheduleGridSave();+ }++ // --- editing the area of interest (rect corners / polygon vertices) ---+ function cornerLatLng(b, c) {+ return [c[0] === 'n' ? b.north : b.south, c[1] === 'e' ? b.east : b.west];+ }++ function normBounds(b) {+ return {+ south: Math.min(b.south, b.north),+ north: Math.max(b.south, b.north),+ west: Math.min(b.west, b.east),+ east: Math.max(b.west, b.east),+ };+ }++ // The area box + handles show only while editing the area; once a grid is+ // drawn the box is hidden and just the cells remain.+ function renderAoi() {+ ensureGridLayers();+ gridAoiLayer.clearLayers();+ aoiOutline = null;+ if (!grid || !editArea) return;+ const b = gridSearch.aoiBounds(grid.aoi);+ if (grid.aoi.type === 'rect') {+ aoiOutline = L.rectangle([[b.south, b.west], [b.north, b.east]], AOI_STYLE).addTo(gridAoiLayer);+ for (const corner of CORNERS) {+ const m = L.marker(cornerLatLng(b, corner), {+ draggable: true,+ keyboard: false,+ icon: gridHandleIcon(),+ zIndexOffset: 1200,+ });+ m.on('dragstart', () => (dragBounds = { ...gridSearch.aoiBounds(grid.aoi) }));+ m.on('drag', (e) => onCornerDrag(corner, e.target.getLatLng()));+ m.on('dragend', commitResize);+ m.addTo(gridAoiLayer);+ }+ } else {+ aoiOutline = L.polygon(grid.aoi.vertices, AOI_STYLE).addTo(gridAoiLayer);+ addVertHandles();+ }+ }++ function onCornerDrag(corner, latlng) {+ if (!dragBounds) return;+ if (corner[0] === 'n') dragBounds.north = latlng.lat;+ else dragBounds.south = latlng.lat;+ if (corner[1] === 'e') dragBounds.east = latlng.lng;+ else dragBounds.west = latlng.lng;+ const b = normBounds(dragBounds);+ aoiOutline?.setBounds([[b.south, b.west], [b.north, b.east]]);+ }++ function commitResize() {+ if (!dragBounds || !grid) return;+ const b = normBounds(dragBounds);+ dragBounds = null;+ const resized = gridSearch.resizeRect(grid, b);+ if (gridSearch.estimateCells(resized) > GRID_MAX_CELLS) {+ toast(`That area is too fine for ${grid.cell_m} m cells — keeping the previous size`, 'warn', 5000);+ renderAoi(); // snap the handles back+ return;+ }+ grid = resized;+ renderGrid();+ renderAoi();+ scheduleGridSave();+ }++ // reshape a confirmed polygon: draggable handles on every vertex+ function addVertHandles() {+ grid.aoi.vertices.forEach((v, k) => {+ const m = L.marker([v[0], v[1]], {+ draggable: true,+ keyboard: false,+ icon: gridHandleIcon(),+ zIndexOffset: 1200,+ });+ m.on('dragstart', () => (liveVerts = grid.aoi.vertices.map((x) => [...x])));+ m.on('drag', (e) => {+ if (!liveVerts) return;+ const ll = e.target.getLatLng();+ liveVerts[k] = [ll.lat, ll.lng];+ aoiOutline?.setLatLngs(liveVerts);+ });+ m.on('dragend', commitVertEdit);+ m.addTo(gridAoiLayer);+ });+ }++ function commitVertEdit() {+ if (!liveVerts || !grid) return;+ const verts = liveVerts;+ liveVerts = null;+ const resized = gridSearch.resizePolygon(grid, verts);+ if (gridSearch.estimateCells(resized) > GRID_MAX_CELLS) {+ toast(`That shape is too fine for ${grid.cell_m} m cells — keeping the previous one`, 'warn', 5000);+ renderAoi();+ return;+ }+ grid = resized;+ renderGrid();+ renderAoi();+ scheduleGridSave();+ }++ // show the area box to resize (rect corners) or reshape (polygon vertices)+ function toggleEditArea() {+ if (!grid) return;+ stopReview();+ cancelGridDraw();+ editArea = !editArea;+ renderAoi();+ }++ function startDraw(type) {+ cancelGridDraw();+ stopReview();+ editArea = false;+ gridHidden = false;+ gridDraw = type;+ // hide the current cells while drawing so map clicks reach the canvas+ // (polygon vertices) instead of being swallowed by a cell underneath+ gridLayer?.clearLayers();+ cellRects.clear();+ if (type === 'polygon') {+ polyDraft = [];+ renderDraft();+ }+ }++ function cancelGridDraw() {+ const wasDrawing = gridDraw;+ gridDraw = null;+ polyDraft = [];+ selRect = null;+ draftLine = null;+ gridDraftLayer?.clearLayers();+ if (wasDrawing && grid) renderGrid(); // restore the cells hidden while drawing+ }++ // rectangle area: drag a box (mirrors the capture marquee, reusing selRect for+ // the live outline). Armed while gridDraw === 'rect'.+ function onGridRectStart(e) {+ if (gridDraw !== 'rect' || e.button !== 0 || !map) return;+ e.stopPropagation();+ e.preventDefault();+ const rect = mapEl.getBoundingClientRect();+ const start = { x: e.clientX - rect.left, y: e.clientY - rect.top };+ selRect = { x0: start.x, y0: start.y, x1: start.x, y1: start.y };+ const move = (ev) => {+ selRect = { x0: start.x, y0: start.y, x1: ev.clientX - rect.left, y1: ev.clientY - rect.top };+ };+ const up = () => {+ window.removeEventListener('mousemove', move);+ window.removeEventListener('mouseup', up);+ finishGridRect();+ };+ window.addEventListener('mousemove', move);+ window.addEventListener('mouseup', up);+ }++ function finishGridRect() {+ const r = selRect;+ selRect = null;+ gridDraw = null;+ if (!r || Math.abs(r.x1 - r.x0) < 12 || Math.abs(r.y1 - r.y0) < 12) {+ if (grid) renderGrid(); // stray click: restore the cells hidden to draw+ return;+ }+ const p1 = map.containerPointToLatLng(L.point(r.x0, r.y0));+ const p2 = map.containerPointToLatLng(L.point(r.x1, r.y1));+ doApplyArea({+ type: 'rect',+ bounds: normBounds({ south: p1.lat, north: p2.lat, west: p1.lng, east: p2.lng }),+ });+ }++ // polygon area: click to drop vertices (handled in onMapClick), drag the+ // handles to adjust, Confirm to build.+ function draftLatLngs() {+ const pts = polyDraft.map((p) => [p.lat, p.lon]);+ return pts.length >= 3 ? pts.concat([pts[0]]) : pts;+ }++ function renderDraft() {+ ensureGridLayers();+ gridDraftLayer.clearLayers();+ draftLine = null;+ if (gridDraw !== 'polygon') return;+ draftLine = L.polyline(draftLatLngs(), {+ color: '#f5a623',+ weight: 1.5,+ opacity: 0.95,+ dashArray: '5 4',+ }).addTo(gridDraftLayer);+ polyDraft.forEach((p, k) => {+ const m = L.marker([p.lat, p.lon], {+ draggable: true,+ keyboard: false,+ icon: gridHandleIcon(),+ zIndexOffset: 1200,+ });+ m.on('drag', (e) => {+ const ll = e.target.getLatLng();+ polyDraft[k] = { lat: ll.lat, lon: ll.lng };+ draftLine?.setLatLngs(draftLatLngs());+ });+ m.on('dragend', renderDraft);+ m.addTo(gridDraftLayer);+ });+ }++ function confirmPolygon() {+ if (polyDraft.length < 3) return;+ const vertices = polyDraft.map((p) => [p.lat, p.lon]);+ gridDraw = null;+ polyDraft = [];+ gridDraftLayer?.clearLayers();+ doApplyArea({ type: 'polygon', vertices });+ }++ // Drawing an area always makes a *new* grid (the case can hold several); the+ // one you were on stays saved. Resizing the current grid is the handles.+ async function doApplyArea(aoi) {+ const cellM = Math.max(10, Number(gridCellM) || 500); // never a NaN lattice+ const g = gridSearch.createGrid(aoi, cellM);+ if (gridSearch.estimateCells(g) > GRID_MAX_CELLS) {+ toast(`That area is too fine — over the ${GRID_MAX_CELLS}-cell limit. Use a larger cell size.`, 'warn', 6000);+ renderGrid(); // restore the previous grid we hid to draw+ return;+ }+ await ensureCase(); // a grid is case state; make sure there is one to hold it+ await flushGridSave(); // persist the grid we're leaving before switching+ g.title = gridTitleFor(aoi);+ grid = g;+ gridName = `grid-${Date.now().toString(36)}`;+ gridFor = caseState.current?.id;+ reviewKey = null;+ editArea = false;+ gridHidden = false;+ renderGrid();+ renderAoi();+ await saveGrid(); // create it on disk now, then refresh the picker+ refreshGridList();+ }++ function gridTitleFor(aoi) {+ const b = gridSearch.aoiBounds(aoi);+ return fmtCoords((b.south + b.north) / 2, (b.west + b.east) / 2);+ }++ // --- sweep loop: fly to a cell, mark it, advance ---+ function flyToCell([i, j]) {+ setReview(gridSearch.cellKey(i, j));+ const b = gridSearch.cellBounds(grid, i, j);+ map.fitBounds([[b.south, b.west], [b.north, b.east]], {+ padding: [80, 80],+ maxZoom: 20,+ animate: true,+ });+ }++ function startReview() {+ if (!grid) return;+ editArea = false;+ const cell = gridSearch.nextUnchecked(grid, null);+ if (!cell) {+ toast('Every cell is marked — sweep complete', 'ok');+ return;+ }+ flyToCell(cell);+ }++ function reviewAdvance() {+ const next = gridSearch.nextUnchecked(grid, reviewKey);+ if (!next) {+ setReview(null);+ toast('Sweep complete', 'ok');+ return;+ }+ flyToCell(next);+ }++ function markReview(status) {+ if (!reviewKey) return;+ if (status) grid.statuses[reviewKey] = status;+ else delete grid.statuses[reviewKey];+ restyleCell(reviewKey);+ scheduleGridSave();+ reviewAdvance();+ }++ function stopReview() {+ if (reviewKey) setReview(null);+ }++ // flag the cell under review and file its centre as a place (spec §5 — a hit+ // the analyst promotes into the case graph)+ async function reviewToPlace() {+ if (!reviewKey || !grid) return;+ const [i, j] = gridSearch.parseKey(reviewKey);+ const c = gridSearch.cellCenter(grid, i, j);+ grid.statuses[reviewKey] = 'flagged';+ restyleCell(reviewKey);+ scheduleGridSave();+ try {+ const cs = await ensureCase();+ await api.post(`/api/cases/${cs.id}/satellite/place`, {+ lat: c.lat,+ lon: c.lon,+ zoom: Math.max(center.zoom, 16),+ bearing: 0,+ });+ await reloadCase();+ toast('Cell flagged and saved as a place', 'ok');+ } catch (e) {+ toast(`Could not save place: ${e.message}`, 'danger', 6000);+ }+ }++ // --- the case's saved grids: list, load, new, delete, persist ---+ function scheduleGridSave() {+ clearTimeout(gridSaveTimer);+ gridSaveTimer = setTimeout(saveGrid, 600);+ }++ // persist any pending change to the *current* grid before we switch away+ async function flushGridSave() {+ clearTimeout(gridSaveTimer);+ await saveGrid();+ }++ async function saveGrid() {+ const id = caseState.current?.id;+ if (!id || !grid || !gridName) return;+ try {+ const spec = JSON.parse(JSON.stringify(grid)); // strip the $state proxy+ await api.put(`/api/cases/${id}/search-grids/${gridName}`, { spec, title: grid.title });+ } catch (e) {+ toast(`Could not save the grid: ${e.message}`, 'danger', 5000);+ }+ }++ async function refreshGridList() {+ const id = caseState.current?.id;+ if (!id) {+ gridList = [];+ return;+ }+ try {+ gridList = await api.get(`/api/cases/${id}/search-grids`);+ } catch {+ gridList = [];+ }+ }++ async function loadGrid(name) {+ const id = caseState.current?.id;+ if (!id) return;+ cancelGridDraw();+ stopReview();+ editArea = false;+ gridHidden = false;+ await flushGridSave(); // persist the grid we're leaving+ try {+ const spec = await api.get(`/api/cases/${id}/search-grids/${name}`);+ grid = spec;+ gridName = name;+ reviewKey = null;+ ensureGridLayers();+ renderGrid();+ renderAoi();+ refreshGridList(); // the grid we left becomes a picker entry+ } catch (e) {+ toast(`Could not load grid: ${e.message}`, 'danger', 6000);+ }+ }++ // close the open grid (it stays saved) — the draw buttons then start a fresh one+ function closeGrid() {+ grid = null;+ gridName = null;+ reviewKey = null;+ editArea = false;+ cancelGridDraw();+ clearGridLayers();+ }++ // the Discard button: persist any pending rename/marks first, then close, then+ // refresh the picker so the just-closed grid shows its latest title+ async function discardOpenGrid() {+ await flushGridSave();+ closeGrid();+ refreshGridList();+ }++ async function deleteGrid(name) {+ const id = caseState.current?.id;+ if (id) {+ try {+ await api.del(`/api/cases/${id}/search-grids/${name}`);+ } catch {+ /* the file may already be gone — nothing left to do */+ }+ }+ if (gridName === name) closeGrid();+ refreshGridList();+ }++ // on case change: refresh the picker and close whatever grid was open+ $effect(() => {+ const id = caseState.current?.id;+ caseState.rev; // re-read after a reload elsewhere+ if (!mapReady) return;+ if (gridFor === id) return;+ gridFor = id;+ grid = null;+ gridName = null;+ reviewKey = null;+ editArea = false;+ clearGridLayers();+ refreshGridList();+ });+// save just the point (pin if moved, else center) as a navigable place — no imagelet savingPlace = $state(false);async function savePlace() {@@ -1675,6 +2319,7 @@class="map-wrap"class:measuring={measureMode}class:selecting={selectArmed}+ class:grid-drawing={!!gridDraw}class:grabbing={hideOverlays}><div class="map" bind:this={mapEl}></div>@@ -1712,6 +2357,15 @@><Icon name="ruler" size={16} /></button>+ <button+ class="mtbtn"+ class:on={gridMode}+ onclick={toggleGridMode}+ title="Grid Search — sweep an area cell by cell"+ aria-label="Grid Search"+ >+ <Icon name="grid" size={16} />+ </button><buttonclass="mtbtn"class:on={uiState.refViewers.length}@@ -1762,6 +2416,166 @@{/if}</div>{/if}++ {#if gridMode}+ <div class="grid-panel card" class:collapsed={gridCollapsed}>+ <div class="grid-head">+ <button+ class="grid-collapse"+ onclick={() => (gridCollapsed = !gridCollapsed)}+ title={gridCollapsed ? 'Expand' : 'Collapse'}+ aria-label={gridCollapsed ? 'Expand panel' : 'Collapse panel'}+ >+ <Icon name={gridCollapsed ? 'chevronDown' : 'chevronUp'} size={14} />+ </button>+ {#if renamingGrid}+ <!-- svelte-ignore a11y_autofocus -->+ <input+ class="input grid-rename"+ bind:value={renameText}+ autofocus+ onblur={commitRename}+ onkeydown={(e) => {+ if (e.key === 'Enter') commitRename();+ else if (e.key === 'Escape') {+ renameText = grid.title || '';+ renamingGrid = false;+ }+ }}+ />+ {:else}+ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <span+ class="grid-head-title"+ class:renamable={grid}+ ondblclick={startRename}+ title={grid ? 'Double-click to rename' : ''}+ >+ {grid ? grid.title || 'Grid' : 'Grid Search'}+ </span>+ {/if}+ {#if grid}+ <button+ class="grid-eye"+ onclick={toggleGridHidden}+ title={gridHidden ? 'Show grid' : 'Hide grid'}+ aria-label={gridHidden ? 'Show grid' : 'Hide grid'}+ >+ <Icon name={gridHidden ? 'eyeOff' : 'eye'} size={14} />+ </button>+ {#if gridCov}+ <span class="grid-head-pct mono">{gridCov.percent}%</span>+ {/if}+ {/if}+ </div>++ {#if !gridCollapsed}+ <div class="grid-body">+ {#if grid}+ <div class="grid-cov">+ <div class="grid-bar">+ <span class="grid-bar-fill" style="width:{gridCov.percent}%"></span>+ </div>+ <span class="grid-cov-text mono">+ {gridCov.cleared + gridCov.flagged}/{gridCov.total} · {gridCov.percent}%{#if gridCov.flagged} · {gridCov.flagged} flagged{/if}+ </span>+ </div>++ {#if reviewKey}+ <div class="grid-hint">+ <b>C</b> clear · <b>F</b> flag · <b>S</b> skip · <b>P</b> place · <b>Esc</b> stop+ </div>+ <div class="grid-btns">+ <button class="btn btn-sm" onclick={() => markReview('cleared')}>+ <Icon name="check" size={13} /> Clear+ </button>+ <button class="btn btn-sm" onclick={() => markReview('flagged')}>+ <Icon name="pin" size={13} /> Flag+ </button>+ <button class="btn btn-sm" onclick={reviewToPlace} title="Flag and save as a place">+ <Icon name="plus" size={13} /> Place+ </button>+ <button class="btn btn-ghost btn-sm" onclick={stopReview}>Stop</button>+ </div>+ {:else}+ <div class="grid-btns">+ <button class="btn btn-sm" onclick={startReview} title="Fly through the unchecked cells">+ <Icon name="eye" size={13} /> Review+ </button>+ <button class="btn btn-sm" class:on={editArea} onclick={toggleEditArea} title="Show the area box to resize or reshape it">+ <Icon name="edit" size={13} /> Edit area+ </button>+ <button class="btn btn-sm grid-discard" onclick={discardOpenGrid} title="Close this grid (it stays saved) to draw or open another">+ Discard+ </button>+ <button class="btn btn-ghost btn-sm" onclick={() => deleteGrid(gridName)} title="Delete this grid for good">+ <Icon name="trash" size={13} />+ </button>+ </div>+ {#if editArea}+ <div class="grid-hint">Drag the {grid.aoi.type === 'rect' ? 'corners' : 'points'} to reshape.</div>+ {/if}+ {/if}+ {/if}++ {#if !grid}+ <div class="grid-new">+ <div class="grid-size">+ <span>Cell</span>+ <input+ class="input"+ type="number"+ min="10"+ step="10"+ bind:value={gridCellM}+ title="Cell size in metres for the next grid"+ />+ <span>m</span>+ </div>+ <div class="grid-btns">+ <button class="btn btn-sm" class:on={gridDraw === 'rect'} onclick={() => startDraw('rect')}>+ <Icon name="square" size={13} /> Box+ </button>+ <button class="btn btn-sm" class:on={gridDraw === 'polygon'} onclick={() => startDraw('polygon')}>+ <Icon name="polygon" size={13} /> Polygon+ </button>+ </div>+ {#if gridDraw === 'polygon'}+ <div class="grid-hint">Click to add points{#if polyDraft.length} · {polyDraft.length}{/if}. Drag to adjust.</div>+ <div class="grid-btns">+ <button class="btn btn-sm" disabled={polyDraft.length < 3} onclick={confirmPolygon}>Confirm</button>+ <button class="btn btn-ghost btn-sm" onclick={cancelGridDraw}>Cancel</button>+ </div>+ {:else if gridDraw === 'rect'}+ <div class="grid-hint">Drag a box on the map. Esc to cancel.</div>+ {/if}+ </div>+ {/if}++ {#if !grid && savedOthers.length}+ <div class="grid-saved">+ <div class="grid-saved-label">Saved grids ({savedOthers.length})</div>+ <div class="grid-saved-list">+ {#each savedOthers as g (g.name)}+ <div class="grid-saved-row">+ <button class="grid-load" onclick={() => loadGrid(g.name)} title="Open this grid">+ {g.title || g.name}+ </button>+ <span class="grid-saved-cov mono" title="cleared · flagged">+ {g.cleared}{#if g.flagged}<span class="flagged"> ⚑{g.flagged}</span>{/if}+ </span>+ <button class="btn btn-ghost btn-sm" onclick={() => deleteGrid(g.name)} title="Delete">+ <Icon name="trash" size={12} />+ </button>+ </div>+ {/each}+ </div>+ </div>+ {/if}+ </div>+ {/if}+ </div>+ {/if}</div><!-- capture-frame outline: what the centred Capture will cover — only when@@ -2943,6 +3757,213 @@.map-wrap.selecting :global(.leaflet-container) {cursor: crosshair;}+ .map-wrap.grid-drawing :global(.leaflet-container) {+ cursor: crosshair;+ }++ /* Grid Search panel — same shelf as the measure panel, to the cluster's right */+ .grid-panel {+ position: absolute;+ top: 0;+ left: calc(100% + 8px);+ width: 218px;+ display: flex;+ flex-direction: column;+ background: rgba(24, 24, 24, 0.92);+ backdrop-filter: blur(6px);+ box-shadow: var(--shadow-2);+ }+ .grid-head {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 6px 8px;+ }+ .grid-collapse {+ display: grid;+ place-items: center;+ width: 22px;+ height: 22px;+ border-radius: var(--radius-1);+ color: var(--text-2);+ cursor: pointer;+ flex-shrink: 0;+ }+ .grid-collapse:hover {+ color: var(--text-1);+ background: var(--bg-3);+ }+ .grid-head-title {+ flex: 1;+ min-width: 0;+ font-size: var(--fs-sm);+ font-weight: 600;+ color: var(--text-1);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .grid-head-title.renamable {+ cursor: text;+ }+ .grid-rename {+ flex: 1;+ min-width: 0;+ height: 24px;+ padding: 2px 6px;+ font-size: var(--fs-sm);+ }+ .grid-eye {+ display: grid;+ place-items: center;+ width: 22px;+ height: 22px;+ border-radius: var(--radius-1);+ color: var(--text-2);+ cursor: pointer;+ flex-shrink: 0;+ }+ .grid-eye:hover {+ color: var(--text-1);+ background: var(--bg-3);+ }+ .grid-head-pct {+ font-size: var(--fs-xs);+ color: var(--accent);+ flex-shrink: 0;+ }+ .grid-body {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 0 10px 10px;+ }+ .grid-size {+ display: flex;+ align-items: center;+ gap: 6px;+ font-size: var(--fs-xs);+ color: var(--text-2);+ }+ .grid-size .input {+ width: 64px;+ }+ .grid-btns {+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+ }+ .grid-btns .btn.on {+ background: var(--accent);+ color: var(--accent-text);+ border-color: var(--accent);+ }+ .grid-discard {+ background: rgba(255, 255, 255, 0.1);+ border-color: rgba(255, 255, 255, 0.18);+ color: var(--text-1);+ }+ .grid-discard:hover {+ background: rgba(255, 255, 255, 0.16);+ color: var(--text-1);+ }+ .grid-hint {+ font-size: var(--fs-xs);+ color: var(--text-3);+ }+ .grid-hint b {+ color: var(--text-2);+ }+ .grid-cov {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }+ .grid-bar {+ height: 6px;+ border-radius: 3px;+ background: rgba(124, 138, 165, 0.25);+ overflow: hidden;+ }+ .grid-bar-fill {+ display: block;+ height: 100%;+ background: var(--accent);+ transition: width 0.15s ease;+ }+ .grid-cov-text {+ font-size: var(--fs-xs);+ color: var(--text-2);+ }+ .grid-new {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding-top: 8px;+ border-top: 1px solid var(--border);+ }+ .grid-saved {+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding-top: 8px;+ border-top: 1px solid var(--border);+ }+ .grid-saved-label {+ font-size: var(--fs-xs);+ color: var(--text-3);+ margin-bottom: 2px;+ }+ .grid-saved-list {+ display: flex;+ flex-direction: column;+ gap: 3px;+ /* hundreds of grids scroll inside the panel instead of stretching it down+ the whole page */+ max-height: 240px;+ overflow-y: auto;+ }+ .grid-saved-row {+ display: flex;+ align-items: center;+ gap: 4px;+ }+ .grid-load {+ flex: 1;+ min-width: 0;+ text-align: left;+ padding: 3px 6px;+ border-radius: var(--radius-1);+ font-size: var(--fs-xs);+ color: var(--text-2);+ cursor: pointer;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .grid-load:hover {+ color: var(--text-1);+ background: var(--bg-3);+ }+ .grid-saved-cov {+ font-size: var(--fs-xs);+ color: var(--text-3);+ flex-shrink: 0;+ }+ .grid-saved-cov .flagged {+ color: #ffcf33;+ }+ /* draggable square handle for the area corners / polygon vertices */+ :global(.grid-handle) {+ background: var(--accent, #f5a623);+ border: 2px solid #14161d;+ border-radius: 3px;+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.55);+ cursor: grab;+ }+ :global(.grid-handle:active) {+ cursor: grabbing;+ }/* live capture marquee: a dashed box with a dark scrim over the rest of themap, mirroring the centred frame-overlay look */diff --git a/frontend/src/tools/inspect/SelectionMenu.svelte b/frontend/src/tools/inspect/SelectionMenu.svelteindex c414664..c681585 100644--- a/frontend/src/tools/inspect/SelectionMenu.svelte+++ b/frontend/src/tools/inspect/SelectionMenu.svelte@@ -1,7 +1,7 @@<script>import { api } from '../../lib/api.js';import { caseState, toast } from '../../lib/state.svelte.js';- import { isNeutral } from '../../lib/inspect.js';+ import { adjustDefaults, isNeutral } from '../../lib/inspect.js';import Icon from '../../components/Icon.svelte';import AdjustSliders from './AdjustSliders.svelte';@@ -67,6 +67,10 @@const maxScore = $derived(Math.max(1, ...suggestions.map((s) => s.score)));const gearActive = $derived(!isNeutral(videoFilters, session.videoAdjust));++ function resetVideoAdjust() {+ session.videoAdjust = adjustDefaults(videoFilters);+ }</script><div class="module">@@ -100,6 +104,9 @@{#if showGear}<p class="hint">Preview the whole clip brighter/clearer; save an enhanced copy in Save.</p><AdjustSliders filters={videoFilters} values={session.videoAdjust} />+ <button class="btn btn-ghost btn-sm reset" disabled={!gearActive} onclick={resetVideoAdjust}>+ <Icon name="reset" size={14} /> Reset adjustments+ </button>{/if}</div>@@ -198,6 +205,9 @@font-size: var(--fs-xs);margin: 0;}+ .reset {+ align-self: flex-start;+ }.sugg {display: flex;align-items: center;diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex 26d1157..eea5a79 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -2,6 +2,8 @@from __future__ import annotations+import json+import refrom datetime import datetime, timezonefrom typing import Any@@ -85,6 +87,29 @@ class SatelliteUpdateIn(BaseModel):title: str | None = None+class GridSaveIn(BaseModel):+ # The whole grid spec, built and owned by the client (lib/gridSearch.js).+ # Stored under search/, one file per grid; the server only stamps ++ # sanity-checks it. A human title rides alongside for the picker.+ spec: dict[str, Any]+ title: str | None = None+++# Search grids are saved sweeps a case can hold several of (spec §5 "Grid+# Search"): JSON specs under search/, each a working aid, not a filed entity.+GRID_STATUSES = {"cleared", "flagged"}+GRID_MAX_STATUSES = 50000+++def _slug(text: str) -> str:+ slug = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-")+ return slug[:80] or "grid"+++def _now() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")++@router.get("/satellite/providers")def providers() -> list[dict[str, Any]]:# the user's per-provider eco threshold (Settings) beats the provider's@@ -373,8 +398,11 @@ def parse_coordinates(body: ParseIn) -> dict[str, Any]:return {"lat": lat,"lon": lon,+ # flat keys the Post Composer reads by name"dms": geo.to_dms(lat, lon),"plus_code": geo.plus_code(lat, lon),+ # the Coordinates tool renders this ordered list wholesale+ "formats": geo.all_formats(lat, lon),"links": geo.map_links(lat, lon),}@@ -604,3 +632,82 @@ def update_capture(case_id: str, body: SatelliteUpdateIn) -> dict[str, Any]:# flatten the capture provenance up, like the listing does, so the client# gets the same shape back as GET /satellitereturn {**(updated.get("source") or {}), **updated}++[email protected]("/cases/{case_id}/search-grids")+def list_search_grids(case_id: str) -> list[dict[str, Any]]:+ """Summaries of every saved grid, newest first, for the picker."""+ case = get_case(case_id)+ out = []+ for spec_path in case.subdir("search").glob("*.json"):+ try:+ spec = json.loads(spec_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ if spec.get("azimut_grid") != 1:+ continue+ statuses = spec.get("statuses") or {}+ out.append({+ "name": spec_path.stem,+ "title": spec.get("title", spec_path.stem),+ "updated_at": spec.get("updated_at"),+ "aoi_type": (spec.get("aoi") or {}).get("type"),+ "cleared": sum(1 for v in statuses.values() if v == "cleared"),+ "flagged": sum(1 for v in statuses.values() if v == "flagged"),+ })+ out.sort(key=lambda g: g.get("updated_at") or "", reverse=True)+ return out++[email protected]("/cases/{case_id}/search-grids/{name}")+def get_search_grid(case_id: str, name: str) -> dict[str, Any]:+ """One saved grid's full spec."""+ case = get_case(case_id)+ try:+ spec_path = case.resolve_inside(f"search/{name}.json")+ except CaseError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from exc+ if not spec_path.exists():+ raise HTTPException(status_code=404, detail="grid not found")+ return json.loads(spec_path.read_text(encoding="utf-8"))++[email protected]("/cases/{case_id}/search-grids/{name}")+def save_search_grid(case_id: str, name: str, body: GridSaveIn) -> dict[str, Any]:+ """Create or replace one grid. The client owns the name (a stable slug)."""+ case = get_case(case_id)+ slug = _slug(name)+ spec = dict(body.spec)+ aoi = spec.get("aoi")+ if not isinstance(aoi, dict) or aoi.get("type") not in {"rect", "polygon"}:+ raise HTTPException(status_code=400, detail="grid needs a rect or polygon aoi")+ # keep only the two real marks; a corrupt value never reaches disk+ raw = spec.get("statuses")+ statuses = {} if not isinstance(raw, dict) else {+ str(k): v for k, v in raw.items() if v in GRID_STATUSES+ }+ if len(statuses) > GRID_MAX_STATUSES:+ raise HTTPException(status_code=400, detail="grid has too many cells")+ spec["statuses"] = statuses+ spec["azimut_grid"] = 1+ if body.title is not None:+ spec["title"] = body.title+ spec.setdefault("title", slug)+ spec.setdefault("created_at", _now())+ spec["updated_at"] = _now()+ spec_path = case.subdir("search") / f"{slug}.json"+ spec_path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ return {"name": slug, "title": spec["title"], "updated_at": spec["updated_at"]}++[email protected]("/cases/{case_id}/search-grids/{name}")+def delete_search_grid(case_id: str, name: str) -> dict[str, Any]:+ """Discard one saved grid."""+ case = get_case(case_id)+ try:+ spec_path = case.resolve_inside(f"search/{name}.json")+ except CaseError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from exc+ existed = spec_path.exists()+ spec_path.unlink(missing_ok=True)+ return {"deleted": existed}diff --git a/src/azimut/engine/geo.py b/src/azimut/engine/geo.pyindex 1e5647d..e767859 100644--- a/src/azimut/engine/geo.py+++ b/src/azimut/engine/geo.py@@ -13,10 +13,17 @@ from .tiles import USER_AGENT# -- parsing -------------------------------------------------------------------_DEC = r"[-+]?\d{1,3}(?:\.\d+)?"+# Degrees, then minutes (decimal allowed, so degrees-decimal-minutes reads back),+# then optional seconds, then a hemisphere letter._DMS = (- r"(?P<deg>\d{1,3})\s*[°d]\s*(?:(?P<min>\d{1,2})\s*[’'m]\s*)?"+ r"(?P<deg>\d{1,3})\s*[°d]\s*(?:(?P<min>\d{1,2}(?:\.\d+)?)\s*[’'m]\s*)?"r"(?:(?P<sec>\d{1,2}(?:\.\d+)?)\s*[”\"s]\s*)?(?P<hemi>[NSEW])")+# UTM: "31U 448251 5411932" (zone, band, easting, northing; spacing loose).+_UTM = (+ r"(?P<zone>\d{1,2})\s*(?P<band>[C-HJ-NP-X])\s+"+ r"(?P<easting>\d{1,7}(?:\.\d+)?)\s+(?P<northing>\d{1,8}(?:\.\d+)?)"+)def parse_coords(text: str) -> tuple[float, float] | None:@@ -57,8 +64,25 @@ def parse_coords(text: str) -> tuple[float, float] | None:if mgrs:return mgrs+ # UTM: "31U 448251 5411932" — bands C-M are the southern hemisphere.+ m = re.fullmatch(_UTM, text, flags=re.IGNORECASE)+ if m:+ zone = int(m.group("zone"))+ southern = m.group("band").upper() < "N"+ lat, lon = coords.from_utm(+ zone, float(m.group("easting")), float(m.group("northing")), southern+ )+ if -90 <= lat <= 90 and -180 <= lon <= 180:+ return lat, lon+ return None+# full plus code: "8FW4V75V+8Q"- return parse_plus_code(text)+ plus = parse_plus_code(text)+ if plus:+ return plus++ # geohash: "u09tvw0f" — tried last, it is the most permissive shape+ return parse_geohash(text)def parse_plus_code(text: str) -> tuple[float, float] | None:@@ -97,6 +121,97 @@ def to_dms(lat: float, lon: float) -> str:return f"{fmt(lat, 'N', 'S')} {fmt(lon, 'E', 'W')}"+def to_ddm(lat: float, lon: float) -> str:+ """Degrees decimal minutes, e.g. "48°51.502'N 2°17.669'E" (~0.06 m on lat)."""++ def fmt(value: float, pos: str, neg: str) -> str:+ hemi = pos if value >= 0 else neg+ value = abs(value)+ deg = int(value)+ minutes = (value - deg) * 60+ return f"{deg}°{minutes:06.3f}'{hemi}"++ return f"{fmt(lat, 'N', 'S')} {fmt(lon, 'E', 'W')}"+++def to_utm(lat: float, lon: float) -> str | None:+ """UTM grid reference, e.g. "31U 448251 5411932". None outside its domain."""+ band = coords.lat_band(lat)+ if band is None:+ return None+ zone, easting, northing = coords.to_utm(lat, lon)+ return f"{zone}{band} {round(easting)} {round(northing)}"+++# -- geohash ------------------------------------------------------------------------+# Standard base32 geohash (public-domain algorithm), used by many OSINT sites.++_GEOHASH_BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"+++def geohash(lat: float, lon: float, precision: int = 9) -> str:+ lat_lo, lat_hi = -90.0, 90.0+ lon_lo, lon_hi = -180.0, 180.0+ out: list[str] = []+ bit = 0+ ch = 0+ even = True # even bits refine longitude+ while len(out) < precision:+ if even:+ mid = (lon_lo + lon_hi) / 2+ if lon >= mid:+ ch = (ch << 1) | 1+ lon_lo = mid+ else:+ ch <<= 1+ lon_hi = mid+ else:+ mid = (lat_lo + lat_hi) / 2+ if lat >= mid:+ ch = (ch << 1) | 1+ lat_lo = mid+ else:+ ch <<= 1+ lat_hi = mid+ even = not even+ if bit < 4:+ bit += 1+ else:+ out.append(_GEOHASH_BASE32[ch])+ bit = 0+ ch = 0+ return "".join(out)+++def parse_geohash(text: str) -> tuple[float, float] | None:+ """Decode a geohash to its cell centre. None if it holds a non-base32 char."""+ code = text.strip().lower()+ if not code or len(code) < 4: # too short to be an unambiguous paste+ return None+ lat_lo, lat_hi = -90.0, 90.0+ lon_lo, lon_hi = -180.0, 180.0+ even = True+ for c in code:+ idx = _GEOHASH_BASE32.find(c)+ if idx < 0:+ return None+ for mask in (16, 8, 4, 2, 1):+ if even:+ mid = (lon_lo + lon_hi) / 2+ if idx & mask:+ lon_lo = mid+ else:+ lon_hi = mid+ else:+ mid = (lat_lo + lat_hi) / 2+ if idx & mask:+ lat_lo = mid+ else:+ lat_hi = mid+ even = not even+ return (lat_lo + lat_hi) / 2, (lon_lo + lon_hi) / 2++# -- Open Location Code (plus codes) ----------------------------------------------# Standard encoding, full 10-character code + '+'. Public-domain algorithm.@@ -120,6 +235,24 @@ def plus_code(lat: float, lon: float) -> str:return "".join(code[:8]) + "+" + "".join(code[8:])+def all_formats(lat: float, lon: float) -> list[dict[str, str]]:+ """Every coordinate notation the app can render, ordered for display.++ Notations that don't cover the poles (UTM, MGRS) are simply left out when a+ point falls outside their domain, so the list is always well-formed.+ """+ rows = [+ ("dd", "Decimal", coords.format_dd(lat, lon)),+ ("ddm", "Deg. decimal min.", to_ddm(lat, lon)),+ ("dms", "Deg. min. sec.", to_dms(lat, lon)),+ ("utm", "UTM", to_utm(lat, lon)),+ ("mgrs", "MGRS", coords.format_mgrs(lat, lon)),+ ("plus_code", "Plus code", plus_code(lat, lon)),+ ("geohash", "Geohash", geohash(lat, lon)),+ ]+ return [{"id": i, "label": lb, "value": v} for i, lb, v in rows if v]++# -- map links (quick-open, spec Coordinates tool preview) --------------------------diff --git a/src/azimut/workspace.py b/src/azimut/workspace.pyindex ae952f3..b264d58 100644--- a/src/azimut/workspace.py+++ b/src/azimut/workspace.py@@ -27,7 +27,7 @@ from typing import Any, Callable, Literalfrom . import config-CASE_SUBDIRS = ("media", "proofs", "exports", "inspect")+CASE_SUBDIRS = ("media", "proofs", "exports", "inspect", "search")# On-disk schema for case.json. A newer Azimut opens an older case by running# the migrations below up to this number on first open; a case written by adiff --git a/tests/test_geo_api.py b/tests/test_geo_api.pyindex b8c1f99..8c5aa5b 100644--- a/tests/test_geo_api.py+++ b/tests/test_geo_api.py@@ -1,5 +1,7 @@"""Forward geocoding (/api/geo/geocode): Nominatim behind a mock, never the network."""+import pytest+from azimut.engine import geo@@ -63,3 +65,34 @@ def test_geocode_network_failure_is_404(client, monkeypatch):# engine swallows the error (best-effort) → API reports no matchresponse = client.get("/api/geo/geocode", params={"q": "paris"})assert response.status_code == 404+++# -- /api/geo/parse: pure offline conversion, no network -------------------------------+++def test_parse_returns_every_format_and_the_map_links(client):+ result = client.post("/api/geo/parse", json={"text": "48.8583701, 2.2944813"}).json()+ assert result["lat"] == pytest.approx(48.8583701)+ assert result["lon"] == pytest.approx(2.2944813)+ # flat keys the Post Composer reads by name stay in place+ assert result["dms"].endswith('E')+ assert "+" in result["plus_code"]+ # the ordered list the Coordinates tool renders+ assert [f["id"] for f in result["formats"]] == [+ "dd", "ddm", "dms", "utm", "mgrs", "plus_code", "geohash",+ ]+ # all nine external maps, keyed by site+ assert set(result["links"]) >= {"google", "yandex", "bing", "sentinel"}+++def test_parse_accepts_the_formats_it_emits(client):+ for text in ("31U 448251 5411952", "u09tunqu9", "48°51.502'N 2°17.669'E"):+ response = client.post("/api/geo/parse", json={"text": text})+ assert response.status_code == 200, text+ body = response.json()+ assert body["lat"] == pytest.approx(48.858, abs=1e-2)+ assert body["lon"] == pytest.approx(2.294, abs=1e-2)+++def test_parse_rejects_gibberish_with_422(client):+ assert client.post("/api/geo/parse", json={"text": "hello world"}).status_code == 422diff --git a/tests/test_geo_formats.py b/tests/test_geo_formats.pynew file mode 100644index 0000000..bcaedb7--- /dev/null+++ b/tests/test_geo_formats.py@@ -0,0 +1,81 @@+"""Coordinate notations for the Coordinates tool: DDM, UTM, geohash + round-trips.++Every notation the app can *display* must parse back in (the geo.py contract),+so these vectors check the formatter and the parser against each other.+"""++import pytest++from azimut.engine import geo++# A spread of points, including a southern/western one and Null Island.+POINTS = [+ (48.8583701, 2.2944813), # Eiffel Tower+ (-33.8568, 151.2153), # Sydney Opera House+ (-54.8019, -68.303), # Ushuaia (southern + western)+ (0.0, 0.0), # Null Island+ (64.1466, -21.9426), # Reykjavík+]+++def test_ddm_format_and_hemispheres():+ assert geo.to_ddm(48.8583701, 2.2944813) == "48°51.502'N 2°17.669'E"+ assert geo.to_ddm(-33.8568, -70.6693) == "33°51.408'S 70°40.158'W"+++def test_utm_format_and_domain():+ assert geo.to_utm(48.8583701, 2.2944813) == "31U 448251 5411952"+ # UTM/MGRS don't cover the poles → no string rather than a wrong one+ assert geo.to_utm(89.5, 10.0) is None+++def test_geohash_known_vector():+ # Eiffel Tower, precision 9 (matches the geohash.org reference)+ assert geo.geohash(48.8583701, 2.2944813) == "u09tunqu9"++[email protected]("lat,lon", POINTS)+def test_ddm_round_trips(lat, lon):+ parsed = geo.parse_coords(geo.to_ddm(lat, lon))+ assert parsed is not None+ assert parsed[0] == pytest.approx(lat, abs=1e-3)+ assert parsed[1] == pytest.approx(lon, abs=1e-3)++[email protected]("lat,lon", POINTS)+def test_utm_round_trips(lat, lon):+ utm = geo.to_utm(lat, lon)+ assert utm is not None+ parsed = geo.parse_coords(utm)+ assert parsed is not None+ assert parsed[0] == pytest.approx(lat, abs=1e-4)+ assert parsed[1] == pytest.approx(lon, abs=1e-4)++[email protected]("lat,lon", POINTS)+def test_geohash_round_trips(lat, lon):+ parsed = geo.parse_coords(geo.geohash(lat, lon))+ assert parsed is not None+ assert parsed[0] == pytest.approx(lat, abs=1e-4)+ assert parsed[1] == pytest.approx(lon, abs=1e-4)+++def test_geohash_rejects_non_base32_and_short_strings():+ # a, i, l, o are absent from the geohash alphabet+ assert geo.parse_geohash("aiou") is None+ # too short to be an unambiguous paste+ assert geo.parse_geohash("u0") is None+++def test_all_formats_is_ordered_and_labelled():+ rows = geo.all_formats(48.8583701, 2.2944813)+ assert [r["id"] for r in rows] == ["dd", "ddm", "dms", "utm", "mgrs", "plus_code", "geohash"]+ assert all(r["label"] and r["value"] for r in rows)+++def test_all_formats_drops_utm_mgrs_at_the_poles():+ rows = geo.all_formats(89.9, 10.0)+ ids = [r["id"] for r in rows]+ assert "utm" not in ids and "mgrs" not in ids+ # the global notations still render+ assert {"dd", "ddm", "dms", "plus_code", "geohash"} <= set(ids)diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.pyindex f397468..97eb511 100644--- a/tests/test_satellite_api.py+++ b/tests/test_satellite_api.py@@ -568,3 +568,107 @@ def test_tile_proxy_benches_google_on_a_persistent_403(client, monkeypatch):assert "not available for your account and region" in status["detail"]ids = {p["id"] for p in client.get("/api/satellite/providers").json()}assert "google-satellite" not in ids+++# --- Grid Search: several saved grids per case (spec §5) -------------------+++def _rect_grid(south=48.0, west=2.0, north=48.02, east=2.02, statuses=None, title=None):+ return {+ "title": title,+ "spec": {+ "azimut_grid": 1,+ "cell_m": 500,+ "anchor": {"lat": south, "lon": west},+ "lat_step": 0.0045,+ "lon_step": 0.0067,+ "aoi": {"type": "rect", "bounds": {+ "south": south, "west": west, "north": north, "east": east}},+ "statuses": statuses or {},+ },+ }+++def test_search_grids_empty_list(client):+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]+ assert client.get(f"/api/cases/{cid}/search-grids").json() == []+++def test_search_grid_save_and_reload(client):+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]+ body = _rect_grid(statuses={"0:0": "cleared", "1:2": "flagged"}, title="North sweep")+ saved = client.put(f"/api/cases/{cid}/search-grids/north-sweep", json=body).json()+ assert saved["name"] == "north-sweep"+ assert saved["title"] == "North sweep"+ assert saved["updated_at"]++ loaded = client.get(f"/api/cases/{cid}/search-grids/north-sweep").json()+ assert loaded["cell_m"] == 500+ assert loaded["aoi"]["type"] == "rect"+ assert loaded["statuses"] == {"0:0": "cleared", "1:2": "flagged"}+ assert loaded["azimut_grid"] == 1+ assert loaded["title"] == "North sweep"+ assert loaded["created_at"]+++def test_search_grids_list_summaries(client):+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]+ client.put(f"/api/cases/{cid}/search-grids/a",+ json=_rect_grid(statuses={"0:0": "cleared"}, title="A"))+ client.put(f"/api/cases/{cid}/search-grids/b",+ json=_rect_grid(statuses={"0:0": "flagged", "0:1": "flagged"}, title="B"))+ listed = {g["name"]: g for g in client.get(f"/api/cases/{cid}/search-grids").json()}+ assert set(listed) == {"a", "b"}+ assert listed["a"]["cleared"] == 1+ assert listed["b"]["flagged"] == 2+ assert listed["a"]["aoi_type"] == "rect"+++def test_search_grid_replace_keeps_created_at(client):+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]+ client.put(f"/api/cases/{cid}/search-grids/g", json=_rect_grid())+ first = client.get(f"/api/cases/{cid}/search-grids/g").json()["created_at"]++ body = _rect_grid(north=48.05, east=48.05, statuses={"3:3": "cleared"})+ body["spec"]["created_at"] = first # the client round-trips it back+ client.put(f"/api/cases/{cid}/search-grids/g", json=body)+ again = client.get(f"/api/cases/{cid}/search-grids/g").json()+ assert again["created_at"] == first+ assert again["statuses"] == {"3:3": "cleared"}+++def test_search_grid_sanitizes_bad_statuses(client):+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]+ body = _rect_grid(statuses={"0:0": "cleared", "0:1": "bogus", "0:2": "flagged"})+ client.put(f"/api/cases/{cid}/search-grids/g", json=body)+ loaded = client.get(f"/api/cases/{cid}/search-grids/g").json()+ assert loaded["statuses"] == {"0:0": "cleared", "0:2": "flagged"}+++def test_search_grid_rejects_missing_aoi(client):+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]+ r = client.put(f"/api/cases/{cid}/search-grids/g", json={"spec": {"cell_m": 500}})+ assert r.status_code == 400+++def test_search_grid_missing_is_404(client):+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]+ assert client.get(f"/api/cases/{cid}/search-grids/nope").status_code == 404+++def test_search_grid_delete_one(client):+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]+ client.put(f"/api/cases/{cid}/search-grids/a", json=_rect_grid(title="A"))+ client.put(f"/api/cases/{cid}/search-grids/b", json=_rect_grid(title="B"))+ assert client.delete(f"/api/cases/{cid}/search-grids/a").json()["deleted"] is True+ names = {g["name"] for g in client.get(f"/api/cases/{cid}/search-grids").json()}+ assert names == {"b"}+ # deleting again is a no-op, not an error+ assert client.delete(f"/api/cases/{cid}/search-grids/a").json()["deleted"] is False+++def test_search_grids_are_not_entities(client):+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]+ client.put(f"/api/cases/{cid}/search-grids/g", json=_rect_grid())+ # grids are working aids, filed under search/, never in the case graph+ assert client.get(f"/api/cases/{cid}").json()["entities"] == []