From adb0adbd94f85abd54e241a15e029edc8738f5c5 Mon Sep 17 00:00:00 2001 From: lrnselfreliance <33263708+lrnselfreliance@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:11:01 -0700 Subject: [PATCH] The map draws any PMTiles file as an overlay, in any sub-directory (#962) Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically. Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config. PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths. --- app/src/api.js | 22 +- app/src/components/Map.js | 71 +++-- app/src/components/MapPreview.test.js | 37 ++- app/src/components/MapTables.test.js | 78 +++++ app/src/components/MapViewer.js | 271 +++++++++++++----- app/src/components/MapViewerOverlays.test.js | 279 ++++++++++++++++++ app/src/components/mapOverlays.js | 247 ++++++++++++++++ app/src/components/mapOverlays.test.js | 285 +++++++++++++++++++ app/src/components/mapPoiPopup.js | 2 +- conftest.py | 1 + modules/map/api.py | 19 +- modules/map/config.py | 60 ++++ modules/map/conftest.py | 51 ++++ modules/map/lib.py | 102 +++++-- modules/map/pmtiles.py | 195 +++++++++++++ modules/map/schema.py | 6 + modules/map/search.py | 37 ++- modules/map/static/embed.html | 16 +- modules/map/static/index.html | 29 +- modules/map/test/test_api.py | 107 +++++++ modules/map/test/test_lib.py | 91 ++++++ modules/map/test/test_pmtiles.py | 137 +++++++++ modules/map/test/test_search.py | 97 ++++++- wrolpi/common.py | 15 + wrolpi/contexts.py | 7 + wrolpi/scripts/build_map_search.py | 22 +- wrolpi/sync/lib.py | 1 + 27 files changed, 2115 insertions(+), 170 deletions(-) create mode 100644 app/src/components/MapViewerOverlays.test.js create mode 100644 app/src/components/mapOverlays.js create mode 100644 app/src/components/mapOverlays.test.js create mode 100644 modules/map/config.py create mode 100644 modules/map/conftest.py create mode 100644 modules/map/pmtiles.py create mode 100644 modules/map/test/test_pmtiles.py diff --git a/app/src/api.js b/app/src/api.js index f6e69e75..6130bfbb 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -1679,14 +1679,28 @@ export async function getMapFiles() { } } -export async function deleteMapFile(filename) { - const response = await apiDelete(`${API_URI}/map/files/${encodeURIComponent(filename)}`); +// A map file is named by its path within the map directory; it may be in a sub-directory. +function encodeMapPath(mapPath) { + return String(mapPath).split('/').map(encodeURIComponent).join('/'); +} + +export async function deleteMapFile(mapPath) { + const response = await apiDelete(`${API_URI}/map/files/${encodeMapPath(mapPath)}`); if (!response.ok) { const message = await getErrorMessage(response, 'Could not delete map file'); toast({type: 'error', title: 'Map Error', description: message, time: 5000}); } } +// Show a map file on the map, or ignore it. +export async function setMapFileVisible(mapPath, visible) { + const response = await apiPost(`${API_URI}/map/files/visible`, {map_path: mapPath, visible}); + if (!response.ok) { + const message = await getErrorMessage(response, 'Could not change the map file'); + toast({type: 'error', title: 'Map Error', description: message, time: 5000}); + } +} + export async function fetchMapSubscriptions() { const response = await apiGet(`${API_URI}/map/subscribe`); if (response.ok) { @@ -1793,8 +1807,8 @@ export async function searchEstimateMap(search_str) { return {mapPlaces: data.map_places || 0}; } -export async function rebuildMapSearchIndex(filename) { - const response = await apiPost(`${API_URI}/map/search/rebuild/${encodeURIComponent(filename)}`); +export async function rebuildMapSearchIndex(mapPath) { + const response = await apiPost(`${API_URI}/map/search/rebuild/${encodeMapPath(mapPath)}`); if (!response.ok) { const message = await getErrorMessage(response, 'Could not rebuild search index'); toast({type: 'error', title: 'Map Error', description: message, time: 5000}); diff --git a/app/src/components/Map.js b/app/src/components/Map.js index 46b2554d..6a730d5f 100644 --- a/app/src/components/Map.js +++ b/app/src/components/Map.js @@ -12,9 +12,9 @@ import { import {Route, Routes, useNavigate} from "react-router"; import { deleteMapFile, deleteMapPin, fetchMapSubscriptions, getMapFiles, getMapPins, - mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, updateMapPin + mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, setMapFileVisible, updateMapPin } from "../api"; -import {Button, Divider, Group, Header, Icon, Modal, Table, TextInput} from "./ui"; +import {Button, Divider, Group, Header, Icon, Modal, Table, TextInput, Toggle} from "./ui"; import {SortableTable} from "./SortableTable"; import {Media, StatusContext} from "../contexts/contexts"; import {MAP_VIEWER_URI} from "./Vars"; @@ -24,29 +24,29 @@ import {solarCalculatorPath} from "./calculators/solar"; import maplibregl from "maplibre-gl"; import {Protocol} from "pmtiles"; import layers from "protomaps-themes-base"; +import {planMapFiles, pmtilesUrl} from "./mapOverlays"; // Ensure PMTiles protocol is registered (may already be registered by MapViewer). try { maplibregl.addProtocol("pmtiles", new Protocol().tile); } catch (e) { /* already registered */ } const MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles"; -// Detect full planet files: "planet-20260329.pmtiles" or bare date like "20260329.pmtiles". -function isPlanetFile(name) { - if (name.startsWith("planet-")) return true; - return /^\d{8}\.pmtiles$/.test(name); -} +// How the map draws a file (the API's `kind`). +const MAP_FILE_KINDS = { + basemap: 'Basemap', + overlay: 'Overlay', + terrain: 'Terrain', + unknown: 'Unreadable', +}; // Resolve the best available base map source for preview maps. // Checks for a user's planet file first, falls back to the overview blob. async function getPreviewMapSource() { try { const data = await getMapFiles(); - if (data?.files) { - for (const f of data.files) { - if (isPlanetFile(f.name)) { - return {type: 'vector', url: `pmtiles:///media/map/${f.name}`}; - } - } + const {planet} = planMapFiles(data?.files); + if (planet) { + return {type: 'vector', url: pmtilesUrl(planet.path)}; } } catch (e) { /* ignore */ } return {type: 'vector', url: `pmtiles://${MAP_OVERVIEW_URL}`}; @@ -343,30 +343,47 @@ function ManageMap() { // --- Files table --- const fileHeaders = [ - {key: 'name', text: 'File', sortBy: i => i.name.toLowerCase()}, + {key: 'name', text: 'File', sortBy: i => i.map_path.toLowerCase()}, + {key: 'kind', text: 'Type', sortBy: i => i.kind || ''}, {key: 'size', text: 'Size', sortBy: i => i.size || 0}, {key: 'search', text: 'Search', sortBy: null}, {key: 'actions', text: '', sortBy: null}, + {key: 'visible', text: 'Visible', sortBy: i => (i.visible === false ? 0 : 1)}, ]; - const handleBuildSearch = async (filename) => { - await rebuildMapSearchIndex(filename); + const handleBuildSearch = async (mapPath) => { + await rebuildMapSearchIndex(mapPath); await fetchFiles(); }; + const handleVisible = async (file, visible) => { + try { + await setMapFileVisible(file.map_path, visible); + } finally { + await fetchFiles(); + } + }; + const fileRowFunc = (file) => { - return - {file.name} + return + + {/* A file in a sub-directory is shown with its directory. */} + {file.map_path} + {file.title && file.title !== file.name.replace(/\.pmtiles$/, '') &&
{file.title}
} +
+ {MAP_FILE_KINDS[file.kind] || ''} {humanFileSize(file.size)} - {file.name.startsWith('terrain') + {/* A search index is built from a basemap's places; other files have none. */} + {file.kind !== 'basemap' ? null : file.has_search_index ? : handleBuildSearch(file.name)}> + onClick={() => handleBuildSearch(file.map_path)}> {searchBuilding ? 'Building...' : 'Build'} } @@ -377,16 +394,24 @@ function ManageMap() { size='xs' confirmContent='Delete this map file?' confirmButton='Delete' - onClick={() => handleDelete(file.name)} + onClick={() => handleDelete(file.map_path)} > Delete + + handleVisible(file, e.currentTarget.checked)} + /> +
; }; const emptyRow = - No PMTiles map files were found in map/ + No PMTiles map files were found in map/ ; // --- Catalog table --- @@ -427,7 +452,7 @@ function ManageMap() { tableHeaders={fileHeaders} data={files} rowFunc={fileRowFunc} - rowKey='name' + rowKey='map_path' defaultSortColumn='name' emptyRow={emptyRow} /> diff --git a/app/src/components/MapPreview.test.js b/app/src/components/MapPreview.test.js index a3a6b70c..91573bcd 100644 --- a/app/src/components/MapPreview.test.js +++ b/app/src/components/MapPreview.test.js @@ -213,16 +213,47 @@ describe('a single region preview', () => { describe('the basemap source', () => { it("uses the user's planet file when they have one", async () => { - await renderManage({files: [{name: '20260329.pmtiles', size: 134e9}]}); + await renderManage({ + files: [ + { + name: '20260329.pmtiles', path: 'map/planet/20260329.pmtiles', + map_path: 'planet/20260329.pmtiles', kind: 'basemap', visible: true, size: 134e9, + }, + ], + }); await userEvent.click(screen.getByRole('button', {name: 'View All Regions'})); await waitFor(() => expect(constructed).toHaveLength(1)); const {sources} = constructed[0].options.style; - expect(sources.basemap.url).toBe('pmtiles:///media/map/20260329.pmtiles'); + // The file is used where it is, here in a sub-directory of the map directory. + expect(sources.basemap.url).toBe('pmtiles:///media/map/planet/20260329.pmtiles'); }); it('falls back to the overview blob when there is no planet file', async () => { - await renderManage({files: [{name: 'us-west-20260329.pmtiles', size: 5e9}]}); + await renderManage({ + files: [ + { + name: 'us-west-20260329.pmtiles', path: 'map/us-west-20260329.pmtiles', + map_path: 'us-west-20260329.pmtiles', kind: 'basemap', visible: true, size: 5e9, + }, + ], + }); + await userEvent.click(screen.getByRole('button', {name: 'View All Regions'})); + await waitFor(() => expect(constructed).toHaveLength(1)); + + const {sources} = constructed[0].options.style; + expect(sources.basemap.url).toBe('pmtiles:///blobs/map-overview.pmtiles'); + }); + + it('falls back to the overview blob when the planet file is ignored', async () => { + await renderManage({ + files: [ + { + name: '20260329.pmtiles', path: 'map/20260329.pmtiles', + map_path: '20260329.pmtiles', kind: 'basemap', visible: false, size: 134e9, + }, + ], + }); await userEvent.click(screen.getByRole('button', {name: 'View All Regions'})); await waitFor(() => expect(constructed).toHaveLength(1)); diff --git a/app/src/components/MapTables.test.js b/app/src/components/MapTables.test.js index 5755b228..70382c8f 100644 --- a/app/src/components/MapTables.test.js +++ b/app/src/components/MapTables.test.js @@ -28,6 +28,8 @@ jest.mock('../api', () => ({ getMapFiles: jest.fn(), fetchMapSubscriptions: jest.fn(), getMapPins: jest.fn(), + setMapFileVisible: jest.fn(), + rebuildMapSearchIndex: jest.fn(), })); const api = require('../api'); @@ -156,3 +158,79 @@ describe('the Manage tab subscriptions table', () => { expect(screen.getByRole('button', {name: 'View All Regions'})).toBeEnabled(); }); }); + +describe('the Manage tab files table', () => { + const mapFile = (map_path, kind, extra = {}) => ({ + name: map_path.split('/').pop(), map_path, path: `map/${map_path}`, kind, + size: 1024, visible: true, has_search_index: false, title: null, ...extra, + }); + const FILES = [ + mapFile('us-west.pmtiles', 'basemap', {title: 'Protomaps Basemap'}), + mapFile('extras/features.pmtiles', 'overlay', {title: 'Topographic Features'}), + mapFile('terrain-planet.pmtiles', 'terrain'), + mapFile('broken.pmtiles', 'unknown'), + ]; + const rowOf = (text) => screen.getByText(text).closest('tr'); + const cellsOf = (text) => [...rowOf(text).querySelectorAll('td')].map(td => td.textContent); + + const renderFiles = async (files = FILES) => { + api.getMapFiles.mockResolvedValue({files}); + renderAt('/map/manage'); + await act(async () => { + }); + }; + + test('a file is listed with its directory, its own name, and how the map draws it', async () => { + await renderFiles(); + expect(cellsOf('extras/features.pmtiles').slice(0, 2)) + .toEqual(['extras/features.pmtilesTopographic Features', 'Overlay']); + expect(cellsOf('us-west.pmtiles')[1]).toBe('Basemap'); + expect(cellsOf('terrain-planet.pmtiles')[1]).toBe('Terrain'); + expect(cellsOf('broken.pmtiles')[1]).toBe('Unreadable'); + }); + + test('only a basemap offers a search index', async () => { + await renderFiles(); + const builds = screen.getAllByRole('button', {name: 'Build'}); + expect(builds).toHaveLength(1); + expect(rowOf('us-west.pmtiles')).toContainElement(builds[0]); + }); + + test('the search index of a file in a sub-directory is built by its path', async () => { + await renderFiles([mapFile('regions/oregon.pmtiles', 'basemap')]); + await act(async () => { + fireEvent.click(screen.getByRole('button', {name: 'Build'})); + }); + expect(api.rebuildMapSearchIndex).toHaveBeenCalledWith('regions/oregon.pmtiles'); + }); + + test('a file is ignored with its toggle, and the list is fetched again', async () => { + await renderFiles(); + const toggle = screen.getByRole('switch', {name: 'Show extras/features.pmtiles on the map'}); + expect(toggle).toBeChecked(); + + api.getMapFiles.mockResolvedValue({ + files: FILES.map(f => f.kind === 'overlay' ? {...f, visible: false} : f), + }); + const before = api.getMapFiles.mock.calls.length; + await act(async () => { + fireEvent.click(toggle); + }); + + expect(api.setMapFileVisible).toHaveBeenCalledWith('extras/features.pmtiles', false); + expect(api.getMapFiles.mock.calls.length).toBe(before + 1); + // Only the ignored file's toggle is off. + expect(screen.getByRole('switch', {name: 'Show extras/features.pmtiles on the map'})).not.toBeChecked(); + expect(screen.getByRole('switch', {name: 'Show us-west.pmtiles on the map'})).toBeChecked(); + }); + + test('an ignored file is shown again with its toggle', async () => { + await renderFiles([mapFile('satellite.pmtiles', 'overlay', {visible: false})]); + const toggle = screen.getByRole('switch', {name: 'Show satellite.pmtiles on the map'}); + expect(toggle).not.toBeChecked(); + await act(async () => { + fireEvent.click(toggle); + }); + expect(api.setMapFileVisible).toHaveBeenCalledWith('satellite.pmtiles', true); + }); +}); diff --git a/app/src/components/MapViewer.js b/app/src/components/MapViewer.js index dc37b2ae..2e04fe58 100644 --- a/app/src/components/MapViewer.js +++ b/app/src/components/MapViewer.js @@ -12,15 +12,25 @@ import {SettingsContext, ThemeContext} from "../contexts/contexts"; import {mapFlavor, mapSprite} from "../themes/names"; import {poiPopupHtml} from "./mapPoiPopup"; import {solarCalculatorPath} from "./calculators/solar"; - -// Terrain DEM file prefix for hillshade and contours. -const TERRAIN_PREFIX = "terrain-"; - -// Detect full planet files: "planet-20260329.pmtiles" or bare date like "20260329.pmtiles". -function isPlanetFile(name) { - if (name.startsWith("planet-")) return true; - return /^\d{8}\.pmtiles$/.test(name); -} +import { + addOverlaysToStyle, + buildOverlayLayers, + isOverlayEnabled, + isOverlayLayerEnabled, + isOverlayLayerId, + isRasterOverlay, + loadOverlayState, + mediaUrl, + overlayColor, + overlayLabel, + overlayPopupHtml, + planMapFiles, + pmtilesUrl, + saveOverlayState, + setAllOverlayLayersEnabled, + setOverlayEnabled, + setOverlayLayerEnabled, +} from "./mapOverlays"; // Layer groups matching the standalone viewer. const LAYER_GROUPS = { @@ -56,8 +66,8 @@ const SKIP_SECONDARY = new Set(["background", "earth"]); // Set up contour DEM source (must be called once before buildStyle). let demSource = null; let terrainUrl = null; -function initContourSource(filename) { - terrainUrl = `/media/map/${filename}`; +function initContourSource(path) { + terrainUrl = mediaUrl(path); if (demSource) return; demSource = new mlcontour.DemSource({ url: `pmtiles://${window.location.origin}${terrainUrl}`, @@ -73,8 +83,10 @@ function initContourSource(filename) { // scaleUnit: "metric" or "imperial" — affects contour intervals and labels. // `sprite` is deliberately separate from `flavor`: we ship two sprite sets (light, dark) // and the monochrome themes draw a `black` basemap, which has no sprites of its own. +// overlays: the map files which are not a basemap; overlayState: which of them (and of their +// layers) the user turned on. function buildStyle(sources, flavor = "light", hasTerrain = false, scaleUnit = "metric", - sprite = "light") { + sprite = "light", overlays = [], overlayState = {}) { const styleSources = {}; const allLayers = []; @@ -195,6 +207,8 @@ function buildStyle(sources, flavor = "light", hasTerrain = false, scaleUnit = " ); } + addOverlaysToStyle(styleSources, allLayers, overlays, overlayState); + return { version: 8, glyphs: "/map-assets/fonts/{fontstack}/{range}.pbf", @@ -219,7 +233,87 @@ function getInitialVisibility() { return v; } -function LayerControl({map, scaleUnit, onScaleUnitChange, visibilityRef}) { +// Show or hide the basemap layers of a layer group. Layer IDs are plain ("water") or prefixed +// with their source ("oregon.pmtiles:water"); an overlay's layers belong to no group, whatever +// they are named. +function setGroupVisibility(map, groupName, visible) { + const prefixes = LAYER_GROUPS[groupName]; + if (!prefixes) return; + for (const layer of map.getStyle()?.layers || []) { + if (isOverlayLayerId(layer.id)) continue; + const baseId = layer.id.includes(":") ? layer.id.split(":").slice(1).join(":") : layer.id; + if (prefixes.some(p => baseId.includes(p))) { + map.setLayoutProperty(layer.id, "visibility", visible ? "visible" : "none"); + } + } +} + +function applyGroupVisibility(map, visibility) { + for (const [groupName, visible] of Object.entries(visibility || {})) { + setGroupVisibility(map, groupName, visible); + } +} + +// One overlay file in the layer control: a checkbox for the file, and (for a vector file) one per +// layer behind a chevron. +function OverlayControl({file, label, state, onToggleFile, onToggleLayer, onToggleAllLayers}) { + const [expanded, setExpanded] = useState(false); + const enabled = isOverlayEnabled(state, file); + const vectorLayers = isRasterOverlay(file) ? [] : (file.vector_layers || []); + const zooms = Number.isFinite(file.min_zoom) && Number.isFinite(file.max_zoom) + ? `z${file.min_zoom}–${file.max_zoom}` : null; + const title = [file.description, file.path].filter(Boolean).join("\n"); + const linkStyle = {cursor: "pointer", textDecoration: "underline", color: "var(--muted)"}; + + return
+
+ onToggleFile(file, e.currentTarget.checked)} + /> + {zooms && {zooms}} + {vectorLayers.length > 0 && setExpanded(x => !x)} + > + + } +
+ {expanded &&
+
+ onToggleAllLayers(file, true)}>All + onToggleAllLayers(file, false)}>None +
+ {vectorLayers.map(layer => +
+ + + {layer.id} + } + checked={isOverlayLayerEnabled(state, file, layer.id)} + disabled={!enabled} + onChange={(e) => onToggleLayer(file, layer.id, e.currentTarget.checked)} + /> +
+ )} +
} +
; +} + +function LayerControl({ + map, scaleUnit, onScaleUnitChange, visibilityRef, + overlays = [], overlayState = {}, onToggleOverlay, onToggleOverlayLayer, + onToggleAllOverlayLayers, + }) { const [visibility, setVisibility] = useState(() => { const v = getInitialVisibility(); if (visibilityRef) visibilityRef.current = v; @@ -244,15 +338,7 @@ function LayerControl({map, scaleUnit, onScaleUnitChange, visibilityRef}) { const toggleGroup = useCallback((groupName, checked) => { if (!map) return; - const prefixes = LAYER_GROUPS[groupName]; - const allMapLayers = map.getStyle()?.layers || []; - for (const layer of allMapLayers) { - // Match both plain IDs and prefixed IDs (e.g., "water" and "file.pmtiles:water"). - const baseId = layer.id.includes(":") ? layer.id.split(":").slice(1).join(":") : layer.id; - if (prefixes.some(p => baseId.includes(p))) { - map.setLayoutProperty(layer.id, "visibility", checked ? "visible" : "none"); - } - } + setGroupVisibility(map, groupName, checked); setVisibility(prev => { const next = {...prev, [groupName]: checked}; if (visibilityRef) visibilityRef.current = next; @@ -314,6 +400,19 @@ function LayerControl({map, scaleUnit, onScaleUnitChange, visibilityRef}) { /> )} + {overlays.length > 0 && +
+
Overlays
+ {overlays.map(file => )} +
}
planetFile.size) { - planetFile = f; - } - } else { - regionFiles.push(f); - } + const {planet, regions, terrain, overlays: foundOverlays} = planMapFiles(data.files); + overlayFiles = foundOverlays; + if (terrain) { + hasTerrain = true; + terrainPath = terrain.path; } - if (planetFile) { - // Planet covers everything — sole vector source, no overview needed. - mapSources.push({name: planetFile.name, url: `pmtiles:///media/map/${planetFile.name}`}); + if (planet) { + // Planet covers everything — sole basemap source, no overview needed. + mapSources.push({name: planet.map_path, url: pmtilesUrl(planet.path)}); } else { // Use regional extracts. - for (const f of regionFiles) { - mapSources.push({name: f.name, url: `pmtiles:///media/map/${f.name}`}); + for (const f of regions) { + mapSources.push({name: f.map_path, url: pmtilesUrl(f.path)}); } // Add planet overview blob as low-zoom base layer (if available). try { @@ -612,16 +710,19 @@ export default function MapViewer() { if (destroyed) return; activeFilesRef.current = mapSources; hasTerrainRef.current = hasTerrain; + overlaysRef.current = overlayFiles; + setOverlays(overlayFiles); // Initialize contour source if terrain data is available. if (hasTerrain) { - initContourSource(terrainFileName); + initContourSource(terrainPath); } try { map = new maplibregl.Map({ container: mapContainer.current, - style: buildStyle(mapSources, mapFlavor(theme), hasTerrain, scaleUnit, mapSprite(theme)), + style: buildStyle(mapSources, mapFlavor(theme), hasTerrain, scaleUnit, mapSprite(theme), + overlayFiles, overlayStateRef.current), center: [initialLon, initialLat], zoom: initialZoom, attributionControl: true, @@ -683,11 +784,17 @@ export default function MapViewer() { .map(l => l.id) .filter(id => id === "pois" || id.endsWith(":pois")) .filter(id => map.getLayer(id)); + // An overlay is drawn over the basemap, so its features are what a click lands on first. + const overlayLayerIds = () => (map.getStyle()?.layers || []) + .filter(l => isOverlayLayerId(l.id) && l.type !== "raster") + .map(l => l.id) + .filter(id => map.getLayer(id)); + const featuresAt = (point, layers) => + layers.length ? map.queryRenderedFeatures(point, {layers}) : []; map.on("click", (e) => { if (destroyed) return; - const layers = poiLayerIds(); - if (!layers.length) return; - const html = poiPopupHtml(map.queryRenderedFeatures(e.point, {layers}), e.lngLat); + const html = overlayPopupHtml(featuresAt(e.point, overlayLayerIds())) + || poiPopupHtml(featuresAt(e.point, poiLayerIds()), e.lngLat); if (!html) return; new maplibregl.Popup({offset: 8, maxWidth: "260px", className: "wrolpi-map-popup"}) .setLngLat(e.lngLat) @@ -696,8 +803,7 @@ export default function MapViewer() { }); map.on("mousemove", (e) => { if (destroyed) return; - const layers = poiLayerIds(); - const hit = layers.length && map.queryRenderedFeatures(e.point, {layers}).length; + const hit = featuresAt(e.point, [...overlayLayerIds(), ...poiLayerIds()]).length; map.getCanvas().style.cursor = hit ? "pointer" : ""; }); @@ -744,18 +850,7 @@ export default function MapViewer() { if (!destroyed) { mapRef.current = map; // Apply saved layer visibility on initial load. - const savedVis = getInitialVisibility(); - const allMapLayers = map.getStyle()?.layers || []; - for (const [groupName, visible] of Object.entries(savedVis)) { - const prefixes = LAYER_GROUPS[groupName]; - if (!prefixes) continue; - for (const layer of allMapLayers) { - const baseId = layer.id.includes(":") ? layer.id.split(":").slice(1).join(":") : layer.id; - if (prefixes.some(p => baseId.includes(p))) { - map.setLayoutProperty(layer.id, "visibility", visible ? "visible" : "none"); - } - } - } + applyGroupVisibility(map, getInitialVisibility()); setMapReady(true); } }); @@ -794,29 +889,43 @@ export default function MapViewer() { const center = map.getCenter(); const zoom = map.getZoom(); + // The overlays are part of the style, as the user last set them. map.setStyle(buildStyle(activeFilesRef.current, mapFlavor(theme), hasTerrainRef.current, - scaleUnit, mapSprite(theme))); + scaleUnit, mapSprite(theme), overlaysRef.current, overlayStateRef.current)); map.once("style.load", () => { map.setCenter(center); map.setZoom(zoom); // Re-apply layer visibility state after style rebuild. - const vis = layerVisibilityRef.current; - if (vis) { - const allMapLayers = map.getStyle()?.layers || []; - for (const [groupName, visible] of Object.entries(vis)) { - const prefixes = LAYER_GROUPS[groupName]; - if (!prefixes) continue; - for (const layer of allMapLayers) { - const baseId = layer.id.includes(":") ? layer.id.split(":").slice(1).join(":") : layer.id; - if (prefixes.some(p => baseId.includes(p))) { - map.setLayoutProperty(layer.id, "visibility", visible ? "visible" : "none"); - } - } - } - } + applyGroupVisibility(map, layerVisibilityRef.current); }); }, [theme, mapReady, scaleUnit]); + // Remember what the user chose to see of an overlay, and show or hide its layers to match. + const changeOverlayState = useCallback((file, next) => { + overlayStateRef.current = next; + setOverlayState(next); + saveOverlayState(next); + const map = mapRef.current; + if (!map) return; + for (const layer of buildOverlayLayers(file, next)) { + if (map.getLayer(layer.id)) { + map.setLayoutProperty(layer.id, "visibility", layer.layout.visibility); + } + } + }, []); + + const handleToggleOverlay = useCallback((file, enabled) => { + changeOverlayState(file, setOverlayEnabled(overlayStateRef.current, file, enabled)); + }, [changeOverlayState]); + + const handleToggleOverlayLayer = useCallback((file, layerId, enabled) => { + changeOverlayState(file, setOverlayLayerEnabled(overlayStateRef.current, file, layerId, enabled)); + }, [changeOverlayState]); + + const handleToggleAllOverlayLayers = useCallback((file, enabled) => { + changeOverlayState(file, setAllOverlayLayersEnabled(overlayStateRef.current, file, enabled)); + }, [changeOverlayState]); + const handleScaleUnitChange = useCallback((unit) => { const map = mapRef.current; const sc = scaleControlRef.current; @@ -964,7 +1073,17 @@ export default function MapViewer() { return
{mapReady && } - {mapReady && } + {mapReady && } {contextMenu &&
{ + class FakeMap { + constructor(options) { + this.options = options; + this.style = options.style; + constructed.push(this); + } + + on(event, callback) { + // MapLibre fires `load` asynchronously once the style resolves. + if (event === 'load') setTimeout(() => callback(), 0); + return this; + } + + once() { + return this; + } + + getStyle() { + return this.style; + } + + setStyle(style) { + this.style = style; + } + + getLayer(id) { + return this.style.layers.find(l => l.id === id); + } + + setLayoutProperty(id, name, value) { + const layer = this.getLayer(id); + layer.layout = {...layer.layout, [name]: value}; + } + + visibility(id) { + return this.getLayer(id)?.layout?.visibility ?? 'visible'; + } + + getCanvas() { + return global.document.createElement('canvas'); + } + + getCenter() { + return {lat: 0, lng: 0}; + } + + getZoom() { + return 2; + } + + setCenter() { + } + + setZoom() { + } + + addControl() { + return this; + } + + removeControl() { + } + + remove() { + } + } + + class Control { + } + + return { + __esModule: true, + default: { + Map: FakeMap, addProtocol: jest.fn(), Marker: Control, Popup: Control, + NavigationControl: Control, FullscreenControl: Control, ScaleControl: Control, + GeolocateControl: Control, + }, + }; +}); +jest.mock('maplibre-gl/dist/maplibre-gl.css', () => ({})); +jest.mock('pmtiles', () => ({ + __esModule: true, Protocol: class { + tile = jest.fn(); + }, +})); +// The basemap theme: a layer of each kind the tests care about, for whichever source asks. +jest.mock('protomaps-themes-base', () => ({ + __esModule: true, + default: (source) => [ + {id: 'earth', type: 'fill', source}, + {id: 'water', type: 'fill', source}, + {id: 'places_locality', type: 'symbol', source}, + ], +})); +jest.mock('@acalcutt/maplibre-contour-pmtiles', () => ({__esModule: true, default: {}})); +jest.mock('../api', () => ({ + ...jest.requireActual('../api'), + getMapFiles: jest.fn(), + getMapPins: jest.fn(), +})); + +const api = require('../api'); + +const mapFile = (map_path, kind, extra = {}) => ({ + name: map_path.split('/').pop(), map_path, path: `map/${map_path}`, kind, + tile_type: 'mvt', size: 1024, visible: true, vector_layers: [], ...extra, +}); +const layer = (id, geometry) => ({id, geometry, minzoom: 0, maxzoom: 8, description: null}); + +const PLANET = mapFile('20260329.pmtiles', 'basemap', {size: 134e9}); +const REGION = mapFile('regions/oregon.pmtiles', 'basemap'); +// An overlay with a layer named like one of the basemap's. +const FEATURES = mapFile('extras/features.pmtiles', 'overlay', { + title: 'Topographic Features', description: 'Topographic features', min_zoom: 0, max_zoom: 8, + vector_layers: [layer('water', 'Polygon'), layer('power_lines', 'LineString'), layer('towers', 'Point')], +}); +const SATELLITE = mapFile('satellite.pmtiles', 'overlay', {tile_type: 'jpeg'}); + +const WATER = 'overlay:extras/features.pmtiles:water:fill'; +const POWER_LINES = 'overlay:extras/features.pmtiles:power_lines:line'; +const TOWERS = 'overlay:extras/features.pmtiles:towers:circle'; +const RASTER = 'overlay:satellite.pmtiles:raster'; + +/** Render the viewer with these map files, and open its layer control. Returns the map. */ +const renderViewer = async (files) => { + api.getMapFiles.mockResolvedValue({files}); + render(, {route: '/map'}); + await waitFor(() => expect(constructed).toHaveLength(1)); + // The layer control appears once the map has loaded; it starts collapsed. + fireEvent.click(await screen.findByTitle('Layers')); + return constructed[0]; +}; + +const click = async (element) => { + await act(async () => { + fireEvent.click(element); + }); +}; + +beforeEach(() => { + constructed.length = 0; + localStorage.clear(); + jest.clearAllMocks(); + api.getMapPins.mockResolvedValue({pins: []}); + // The layer control asks whether this is a narrow screen; the global stub's implementation is + // reset between tests. + window.matchMedia = jest.fn().mockImplementation(query => ({ + matches: false, media: query, onchange: null, + addListener: jest.fn(), removeListener: jest.fn(), + addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(), + })); + // The overview blob is only asked for when there is no planet file. + global.fetch = jest.fn().mockResolvedValue({ok: true}); +}); + +describe('which files the viewer draws', () => { + test('a planet file is the basemap, and an overlay is drawn with it', async () => { + const map = await renderViewer([PLANET, REGION, FEATURES]); + expect(Object.keys(map.style.sources)).toEqual(['20260329.pmtiles', 'overlay:extras/features.pmtiles']); + // The overlay is drawn as itself, not with the basemap theme. + expect(map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles').map(l => l.id)) + .toEqual([WATER, POWER_LINES, TOWERS]); + }); + + test('files are fetched from where they are, sub-directories included', async () => { + const map = await renderViewer([REGION, FEATURES]); + expect(map.style.sources['regions/oregon.pmtiles'].url).toBe('pmtiles:///media/map/regions/oregon.pmtiles'); + expect(map.style.sources['overlay:extras/features.pmtiles'].url) + .toBe('pmtiles:///media/map/extras/features.pmtiles'); + }); + + test('an ignored file is neither drawn nor offered', async () => { + const map = await renderViewer([{...PLANET, visible: false}, REGION, {...FEATURES, visible: false}, SATELLITE]); + // Without the planet file the regional basemap (over the overview) is drawn. + expect(Object.keys(map.style.sources)) + .toEqual(['map-overview', 'regions/oregon.pmtiles', 'overlay:satellite.pmtiles']); + expect(screen.queryByLabelText('Topographic Features')).not.toBeInTheDocument(); + expect(screen.getByLabelText('satellite')).toBeInTheDocument(); + }); + + test('no overlays, no Overlays section', async () => { + await renderViewer([PLANET]); + expect(screen.queryByText('Overlays')).not.toBeInTheDocument(); + }); +}); + +describe('an overlay in the layer control', () => { + test('is named by the file, and starts hidden', async () => { + const map = await renderViewer([PLANET, FEATURES, SATELLITE]); + expect(screen.getByText('Overlays')).toBeInTheDocument(); + expect(screen.getByLabelText('Topographic Features')).not.toBeChecked(); + expect(screen.getByLabelText('satellite')).not.toBeChecked(); + expect([WATER, POWER_LINES, TOWERS, RASTER].map(id => map.visibility(id))) + .toEqual(['none', 'none', 'none', 'none']); + }); + + test('is drawn when it is turned on, and that is remembered', async () => { + const map = await renderViewer([PLANET, FEATURES, SATELLITE]); + await click(screen.getByLabelText('Topographic Features')); + + expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'visible', 'visible']); + // The other overlay is untouched. + expect(map.visibility(RASTER)).toBe('none'); + expect(JSON.parse(localStorage.getItem(STORAGE_KEY_OVERLAYS))) + .toEqual({'extras/features.pmtiles': {enabled: true}}); + + await click(screen.getByLabelText('Topographic Features')); + expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['none', 'none', 'none']); + }); + + test('is drawn from the start when it was turned on before', async () => { + localStorage.setItem(STORAGE_KEY_OVERLAYS, JSON.stringify({ + 'extras/features.pmtiles': {enabled: true, layers: {towers: false}}, + })); + const map = await renderViewer([PLANET, FEATURES]); + expect(screen.getByLabelText('Topographic Features')).toBeChecked(); + expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'visible', 'none']); + }); + + test('each layer of a vector file has its own checkbox', async () => { + const map = await renderViewer([PLANET, FEATURES]); + await click(screen.getByLabelText('Topographic Features')); + await click(screen.getByRole('button', {name: 'Show layers of Topographic Features'})); + + await click(screen.getByLabelText('towers')); + expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'visible', 'none']); + + await click(screen.getByText('None')); + expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['none', 'none', 'none']); + expect(screen.getByLabelText('power_lines')).not.toBeChecked(); + + await click(screen.getByText('All')); + expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'visible', 'visible']); + }); + + test('a raster file has no layers to choose from', async () => { + const map = await renderViewer([PLANET, SATELLITE]); + expect(screen.queryByRole('button', {name: /layers of satellite/})).not.toBeInTheDocument(); + await click(screen.getByLabelText('satellite')); + expect(map.visibility(RASTER)).toBe('visible'); + }); +}); + +describe('the basemap layer groups', () => { + test("do not show or hide an overlay's layer of the same name", async () => { + const map = await renderViewer([PLANET, FEATURES]); + await click(screen.getByLabelText('Topographic Features')); + expect(map.visibility('water')).toBe('visible'); + expect(map.visibility(WATER)).toBe('visible'); + + // Hide the basemap's water: the overlay's `water` layer stays. + await click(screen.getByLabelText('Water')); + expect(map.visibility('water')).toBe('none'); + expect(map.visibility(WATER)).toBe('visible'); + + // Hide the overlay, then show the basemap's water: the overlay's stays hidden. + await click(screen.getByLabelText('Topographic Features')); + await click(screen.getByLabelText('Water')); + expect(map.visibility('water')).toBe('visible'); + expect(map.visibility(WATER)).toBe('none'); + }); +}); diff --git a/app/src/components/mapOverlays.js b/app/src/components/mapOverlays.js new file mode 100644 index 00000000..ad40385b --- /dev/null +++ b/app/src/components/mapOverlays.js @@ -0,0 +1,247 @@ +// Which map files the viewer draws, and how it draws the ones that are not a Protomaps basemap. +// +// The API says what each PMTiles file is (`kind`): a `basemap` is drawn with the basemap theme, +// `terrain` becomes hillshade and contours, and an `overlay` is any other vector or raster file. +// An overlay has no style of its own, so its layers are drawn generically: one color per layer, +// as fills, lines or circles. + +import {escapeHtml} from "./mapPoiPopup"; + +// Every MapLibre source and layer of an overlay starts with this, so the basemap's layer groups +// (which match layer names like "water") never touch them. +export const OVERLAY_PREFIX = "overlay:"; +export const STORAGE_KEY_OVERLAYS = "wrolpi-map-overlays"; + +const RASTER_SUFFIX = "raster"; +const VECTOR_TYPES = ["fill", "line", "circle"]; +// Readable on both the light and dark basemaps. +const OVERLAY_COLORS = [ + "#e6194b", "#3cb44b", "#4363d8", "#f58231", "#b455e0", "#17a2a2", + "#f032e6", "#b07a3b", "#d1495b", "#8a9a1b", "#5b7fff", "#e6a700", +]; +const POPUP_MAX_FEATURES = 3; +const POPUP_MAX_PROPERTIES = 12; + +// Detect full planet files: "planet-20260329.pmtiles" or bare date like "20260329.pmtiles". +export function isPlanetFile(name) { + if (name.startsWith("planet-")) return true; + return /^\d{8}\.pmtiles$/.test(name); +} + +// The URL path of a file in the media directory (`path` is relative to the media directory). +export function mediaUrl(path) { + return "/media/" + String(path).split("/").map(encodeURIComponent).join("/"); +} + +export function pmtilesUrl(path) { + return `pmtiles://${mediaUrl(path)}`; +} + +// Sort the map files into what the viewer does with each. Ignored files (`visible: false`) and +// unreadable files are left out. A planet file covers everything, so it replaces the regional +// extracts; overlays and terrain are drawn either way. +export function planMapFiles(files) { + const visible = (files || []).filter(f => f.visible !== false); + const basemaps = visible.filter(f => f.kind === "basemap"); + let planet = null; + for (const f of basemaps) { + if (isPlanetFile(f.name) && (!planet || f.size > planet.size)) planet = f; + } + const terrains = visible.filter(f => f.kind === "terrain"); + return { + planet, + regions: planet ? [] : basemaps, + terrain: terrains.length ? terrains[terrains.length - 1] : null, + overlays: visible.filter(f => f.kind === "overlay"), + }; +} + +export function isRasterOverlay(file) { + return file.tile_type !== "mvt"; +} + +function fileStem(name) { + return String(name).replace(/\.pmtiles$/, ""); +} + +// What to call an overlay: the name the file gives itself, else its file name. Files which would +// share a label also show where they are. +export function overlayLabel(file, files = []) { + const base = f => (f.title && f.title.trim()) || fileStem(f.name); + const label = base(file); + const shared = files.some(f => f.map_path !== file.map_path && base(f) === label); + return shared ? `${label} (${file.map_path})` : label; +} + +// A stable color for a layer: the same layer name is the same color in every file and session. +export function overlayColor(layerId) { + let hash = 5381; + for (const c of String(layerId)) hash = ((hash * 33) ^ c.charCodeAt(0)) >>> 0; + return OVERLAY_COLORS[hash % OVERLAY_COLORS.length]; +} + +// --- What the user chose to see. {[map_path]: {enabled: bool, layers: {[layerId]: bool}}} --- + +export function loadOverlayState() { + try { + const saved = JSON.parse(localStorage.getItem(STORAGE_KEY_OVERLAYS)); + if (saved && typeof saved === "object" && !Array.isArray(saved)) return saved; + } catch (e) { /* ignore */ } + return {}; +} + +export function saveOverlayState(state) { + try { localStorage.setItem(STORAGE_KEY_OVERLAYS, JSON.stringify(state)); } catch (e) { /* ignore */ } +} + +// An overlay is hidden until the user turns it on. +export function isOverlayEnabled(state, file) { + return state?.[file.map_path]?.enabled === true; +} + +// Once a file is on, each of its layers is drawn until the user turns that layer off. +export function isOverlayLayerEnabled(state, file, layerId) { + return state?.[file.map_path]?.layers?.[layerId] !== false; +} + +export function setOverlayEnabled(state, file, enabled) { + return {...state, [file.map_path]: {...state?.[file.map_path], enabled}}; +} + +export function setOverlayLayerEnabled(state, file, layerId, enabled) { + const entry = state?.[file.map_path] || {}; + return {...state, [file.map_path]: {...entry, layers: {...entry.layers, [layerId]: enabled}}}; +} + +export function setAllOverlayLayersEnabled(state, file, enabled) { + const layers = {}; + for (const l of file.vector_layers || []) layers[l.id] = enabled; + return {...state, [file.map_path]: {...state?.[file.map_path], layers}}; +} + +// --- MapLibre style --- + +export function overlaySourceId(file) { + return `${OVERLAY_PREFIX}${file.map_path}`; +} + +export function isOverlayLayerId(layerId) { + return String(layerId).startsWith(OVERLAY_PREFIX); +} + +// MapLibre puts a source's attribution in the page as HTML, and this text comes from a file +// someone downloaded: only its text is kept. +function attributionText(attribution) { + if (!attribution) return undefined; + const text = new DOMParser().parseFromString(String(attribution), "text/html").body.textContent || ""; + return text.trim() ? escapeHtml(text.trim()) : undefined; +} + +export function buildOverlaySource(file) { + const source = {type: isRasterOverlay(file) ? "raster" : "vector", url: pmtilesUrl(file.path)}; + if (isRasterOverlay(file)) source.tileSize = 256; + const attribution = attributionText(file.attribution); + if (attribution) source.attribution = attribution; + return source; +} + +// The geometry a generator recorded for a layer ("Point", "LineString", "Polygon") names the one +// way to draw it. Without that, the layer is drawn all three ways, each limited to its geometry. +const TYPE_OF_GEOMETRY = {Polygon: "fill", LineString: "line", Point: "circle"}; +const GEOMETRY_OF_TYPE = {fill: "Polygon", line: "LineString", circle: "Point"}; + +function paintOf(type, color) { + if (type === "fill") return {"fill-color": color, "fill-opacity": 0.25, "fill-outline-color": color}; + if (type === "line") return {"line-color": color, "line-width": 1.5}; + return { + "circle-color": color, "circle-radius": 4, + "circle-stroke-color": "#ffffff", "circle-stroke-width": 1, + }; +} + +// The style layers of an overlay file, each already visible or hidden as `state` says; a source +// with no visible layer requests no tiles. +export function buildOverlayLayers(file, state) { + const source = overlaySourceId(file); + const enabled = isOverlayEnabled(state, file); + const visibility = on => (on ? "visible" : "none"); + + if (isRasterOverlay(file)) { + return [{ + id: `${source}:${RASTER_SUFFIX}`, type: "raster", source, + layout: {visibility: visibility(enabled)}, + }]; + } + + const styleLayers = []; + for (const layer of file.vector_layers || []) { + const color = overlayColor(layer.id); + const known = TYPE_OF_GEOMETRY[layer.geometry]; + for (const type of known ? [known] : VECTOR_TYPES) { + const styleLayer = { + id: `${source}:${layer.id}:${type}`, + type, + source, + "source-layer": layer.id, + layout: {visibility: visibility(enabled && isOverlayLayerEnabled(state, file, layer.id))}, + paint: paintOf(type, color), + }; + if (!known) styleLayer.filter = ["==", "$type", GEOMETRY_OF_TYPE[type]]; + styleLayers.push(styleLayer); + } + } + return styleLayers; +} + +// Add the overlays to a style's sources and layers (the basemap's are already there). A raster +// overlay goes under the basemap's labels so the map stays readable; vector overlays go on top, +// fills under lines under points. +export function addOverlaysToStyle(styleSources, allLayers, overlays, state) { + const rasters = []; + const vectors = {fill: [], line: [], circle: []}; + for (const file of overlays || []) { + styleSources[overlaySourceId(file)] = buildOverlaySource(file); + for (const layer of buildOverlayLayers(file, state)) { + if (layer.type === "raster") rasters.push(layer); + else vectors[layer.type].push(layer); + } + } + const firstLabel = allLayers.findIndex(l => l.type === "symbol"); + allLayers.splice(firstLabel === -1 ? allLayers.length : firstLabel, 0, ...rasters); + allLayers.push(...vectors.fill, ...vectors.line, ...vectors.circle); +} + +// --- Popup --- + +// The popup HTML of the overlay features under a click, or null when there are none. An overlay's +// attributes are whatever its author chose, so they are listed as they are. +export function overlayPopupHtml(features) { + const seen = new Set(); + const blocks = []; + for (const feature of features || []) { + const layerId = feature.sourceLayer || feature.layer?.["source-layer"]; + const properties = feature.properties || {}; + if (!layerId) continue; + const key = JSON.stringify([layerId, properties]); + if (seen.has(key)) continue; + seen.add(key); + if (blocks.length >= POPUP_MAX_FEATURES) break; + + const entries = Object.entries(properties).filter(([, v]) => v !== null && v !== undefined && v !== ""); + const name = properties.name; + const rows = entries + .filter(([k]) => k !== "name") + .slice(0, POPUP_MAX_PROPERTIES) + .map(([k, v]) => `
${escapeHtml(k)}: ${escapeHtml(v)}`); + const more = entries.length - (name !== undefined ? 1 : 0) - rows.length; + blocks.push( + `
` + + `${escapeHtml(name !== undefined && name !== "" ? name : layerId)}` + + (name !== undefined && name !== "" ? `
${escapeHtml(layerId)}` : "") + + rows.join("") + + (more > 0 ? `
… ${more} more` : "") + + `
` + ); + } + return blocks.length ? blocks.join('
') : null; +} diff --git a/app/src/components/mapOverlays.test.js b/app/src/components/mapOverlays.test.js new file mode 100644 index 00000000..545bc096 --- /dev/null +++ b/app/src/components/mapOverlays.test.js @@ -0,0 +1,285 @@ +import { + addOverlaysToStyle, + buildOverlayLayers, + buildOverlaySource, + isOverlayEnabled, + isOverlayLayerEnabled, + loadOverlayState, + overlayColor, + overlayLabel, + overlayPopupHtml, + planMapFiles, + pmtilesUrl, + saveOverlayState, + setAllOverlayLayersEnabled, + setOverlayEnabled, + setOverlayLayerEnabled, + STORAGE_KEY_OVERLAYS, +} from './mapOverlays'; + +const file = (map_path, extra = {}) => ({ + name: map_path.split('/').pop(), map_path, path: `map/${map_path}`, + kind: 'overlay', tile_type: 'mvt', visible: true, size: 1, vector_layers: [], ...extra, +}); +const layer = (id, geometry = null) => ({id, geometry, minzoom: 0, maxzoom: 8, description: null}); + +const FEATURES = file('extras/features.pmtiles', { + title: 'Features', + vector_layers: [layer('power_lines', 'LineString'), layer('towers', 'Point'), layer('flood_zones', 'Polygon')], +}); +const SATELLITE = file('satellite.pmtiles', {tile_type: 'jpeg'}); + +describe('planMapFiles', () => { + const planet = file('20260329.pmtiles', {kind: 'basemap', size: 100}); + const region = file('regions/oregon.pmtiles', {kind: 'basemap', size: 5}); + const terrain = file('terrain-planet.pmtiles', {kind: 'terrain', tile_type: 'webp'}); + const unreadable = file('broken.pmtiles', {kind: 'unknown', tile_type: null}); + + test('a planet file replaces the regional basemaps, but not the overlays or terrain', () => { + const plan = planMapFiles([planet, region, terrain, FEATURES, SATELLITE, unreadable]); + expect(plan.planet).toBe(planet); + expect(plan.regions).toEqual([]); + expect(plan.terrain).toBe(terrain); + expect(plan.overlays).toEqual([FEATURES, SATELLITE]); + }); + + test('without a planet file the regional basemaps are drawn', () => { + const plan = planMapFiles([region, FEATURES]); + expect(plan.planet).toBeNull(); + expect(plan.regions).toEqual([region]); + expect(plan.overlays).toEqual([FEATURES]); + }); + + test('a file which is not a basemap is never drawn as one, whatever it is named', () => { + // Named like a planet file, but its layers are not the basemap schema. + const plan = planMapFiles([file('planet-features.pmtiles'), region]); + expect(plan.planet).toBeNull(); + expect(plan.regions).toEqual([region]); + }); + + test('an ignored file is not drawn at all', () => { + const plan = planMapFiles([ + {...planet, visible: false}, region, + {...terrain, visible: false}, {...FEATURES, visible: false}, SATELLITE, + ]); + // Ignoring the planet file brings the regional basemaps back. + expect(plan.planet).toBeNull(); + expect(plan.regions).toEqual([region]); + expect(plan.terrain).toBeNull(); + expect(plan.overlays).toEqual([SATELLITE]); + }); + + test('no files', () => { + expect(planMapFiles(undefined)).toEqual({planet: null, regions: [], terrain: null, overlays: []}); + }); +}); + +describe('overlayLabel', () => { + test('is the name the file gives itself', () => { + expect(overlayLabel(FEATURES, [FEATURES, SATELLITE])).toBe('Features'); + }); + + test('is the file name when the file has no name', () => { + expect(overlayLabel(SATELLITE, [FEATURES, SATELLITE])).toBe('satellite'); + expect(overlayLabel(file('blank.pmtiles', {title: ' '}))).toBe('blank'); + }); + + test('says where a file is when another has the same label', () => { + const other = file('older/features.pmtiles', {title: 'Features'}); + expect(overlayLabel(FEATURES, [FEATURES, other])).toBe('Features (extras/features.pmtiles)'); + expect(overlayLabel(other, [FEATURES, other])).toBe('Features (older/features.pmtiles)'); + }); +}); + +describe('overlayColor', () => { + test('is the same for the same layer, and a color', () => { + expect(overlayColor('power_lines')).toBe(overlayColor('power_lines')); + expect(overlayColor('power_lines')).toMatch(/^#[0-9a-f]{6}$/); + }); + + test('differs between layers', () => { + const colors = new Set(['power_lines', 'towers', 'flood_zones', 'water', 'place'].map(overlayColor)); + expect(colors.size).toBeGreaterThan(1); + }); +}); + +describe('what the user chose to see', () => { + beforeEach(() => localStorage.clear()); + + test('an overlay is hidden until it is turned on', () => { + expect(isOverlayEnabled({}, FEATURES)).toBe(false); + expect(isOverlayEnabled(setOverlayEnabled({}, FEATURES, true), FEATURES)).toBe(true); + }); + + test('the layers of a file are on until they are turned off', () => { + let state = setOverlayEnabled({}, FEATURES, true); + expect(isOverlayLayerEnabled(state, FEATURES, 'towers')).toBe(true); + state = setOverlayLayerEnabled(state, FEATURES, 'towers', false); + expect(isOverlayLayerEnabled(state, FEATURES, 'towers')).toBe(false); + expect(isOverlayLayerEnabled(state, FEATURES, 'power_lines')).toBe(true); + // Turning a layer off does not turn the file off. + expect(isOverlayEnabled(state, FEATURES)).toBe(true); + }); + + test('all the layers of a file can be turned off and on', () => { + let state = setAllOverlayLayersEnabled(setOverlayEnabled({}, FEATURES, true), FEATURES, false); + expect(FEATURES.vector_layers.map(l => isOverlayLayerEnabled(state, FEATURES, l.id))) + .toEqual([false, false, false]); + expect(isOverlayEnabled(state, FEATURES)).toBe(true); + state = setAllOverlayLayersEnabled(state, FEATURES, true); + expect(FEATURES.vector_layers.map(l => isOverlayLayerEnabled(state, FEATURES, l.id))) + .toEqual([true, true, true]); + }); + + test('is remembered by this browser', () => { + expect(loadOverlayState()).toEqual({}); + const state = setOverlayLayerEnabled(setOverlayEnabled({}, FEATURES, true), FEATURES, 'towers', false); + saveOverlayState(state); + expect(loadOverlayState()).toEqual({ + 'extras/features.pmtiles': {enabled: true, layers: {towers: false}}, + }); + }); + + test('a broken saved value is forgotten', () => { + localStorage.setItem(STORAGE_KEY_OVERLAYS, '{not json'); + expect(loadOverlayState()).toEqual({}); + localStorage.setItem(STORAGE_KEY_OVERLAYS, '[1, 2]'); + expect(loadOverlayState()).toEqual({}); + }); +}); + +describe('the style of an overlay', () => { + test('a file is fetched from where it is in the media directory', () => { + expect(pmtilesUrl('map/extras/my features.pmtiles')).toBe('pmtiles:///media/map/extras/my%20features.pmtiles'); + expect(buildOverlaySource(FEATURES)).toEqual({type: 'vector', url: 'pmtiles:///media/map/extras/features.pmtiles'}); + expect(buildOverlaySource(SATELLITE)).toEqual({ + type: 'raster', url: 'pmtiles:///media/map/satellite.pmtiles', tileSize: 256, + }); + }); + + test("only the text of a file's attribution reaches the page", () => { + const source = buildOverlaySource({ + ...FEATURES, + attribution: '© Somebody', + }); + expect(source.attribution).toBe('© Somebody'); + expect(buildOverlaySource({...FEATURES, attribution: '<script>'}).attribution) + .toBe('<script>'); + }); + + test('a layer is drawn the one way its geometry needs', () => { + const layers = buildOverlayLayers(FEATURES, setOverlayEnabled({}, FEATURES, true)); + expect(layers.map(l => [l.id, l.type, l['source-layer']])).toEqual([ + ['overlay:extras/features.pmtiles:power_lines:line', 'line', 'power_lines'], + ['overlay:extras/features.pmtiles:towers:circle', 'circle', 'towers'], + ['overlay:extras/features.pmtiles:flood_zones:fill', 'fill', 'flood_zones'], + ]); + expect(layers.every(l => l.source === 'overlay:extras/features.pmtiles' && !l.filter)).toBe(true); + expect(layers[0].paint['line-color']).toBe(overlayColor('power_lines')); + }); + + test('a layer of unknown geometry is drawn every way, each limited to its geometry', () => { + const unknown = file('unknown.pmtiles', {vector_layers: [layer('things')]}); + const layers = buildOverlayLayers(unknown, {}); + expect(layers.map(l => [l.type, l.filter])).toEqual([ + ['fill', ['==', '$type', 'Polygon']], + ['line', ['==', '$type', 'LineString']], + ['circle', ['==', '$type', 'Point']], + ]); + }); + + test('a raster file is one layer', () => { + expect(buildOverlayLayers(SATELLITE, {})).toEqual([{ + id: 'overlay:satellite.pmtiles:raster', type: 'raster', source: 'overlay:satellite.pmtiles', + layout: {visibility: 'none'}, + }]); + }); + + test('layers are visible only as the user chose', () => { + const visibility = state => buildOverlayLayers(FEATURES, state).map(l => l.layout.visibility); + // A new overlay starts hidden. + expect(visibility({})).toEqual(['none', 'none', 'none']); + let state = setOverlayEnabled({}, FEATURES, true); + expect(visibility(state)).toEqual(['visible', 'visible', 'visible']); + state = setOverlayLayerEnabled(state, FEATURES, 'towers', false); + expect(visibility(state)).toEqual(['visible', 'none', 'visible']); + // Turning the file off hides every layer, and remembers which were on. + state = setOverlayEnabled(state, FEATURES, false); + expect(visibility(state)).toEqual(['none', 'none', 'none']); + expect(visibility(setOverlayEnabled(state, FEATURES, true))).toEqual(['visible', 'none', 'visible']); + }); + + test('a raster overlay goes under the basemap labels, vector overlays on top', () => { + const sources = {basemap: {}}; + const layers = [ + {id: 'earth', type: 'fill'}, {id: 'roads', type: 'line'}, + {id: 'places', type: 'symbol'}, {id: 'pois', type: 'symbol'}, + ]; + addOverlaysToStyle(sources, layers, [FEATURES, SATELLITE], {}); + expect(Object.keys(sources)).toEqual(['basemap', 'overlay:extras/features.pmtiles', 'overlay:satellite.pmtiles']); + expect(layers.map(l => l.id)).toEqual([ + 'earth', 'roads', + 'overlay:satellite.pmtiles:raster', + 'places', 'pois', + // Fills under lines under points. + 'overlay:extras/features.pmtiles:flood_zones:fill', + 'overlay:extras/features.pmtiles:power_lines:line', + 'overlay:extras/features.pmtiles:towers:circle', + ]); + }); + + test('a raster overlay is drawn last when the basemap has no labels', () => { + const layers = [{id: 'earth', type: 'fill'}]; + addOverlaysToStyle({}, layers, [SATELLITE], {}); + expect(layers.map(l => l.id)).toEqual(['earth', 'overlay:satellite.pmtiles:raster']); + }); +}); + +describe('overlayPopupHtml', () => { + const feature = (sourceLayer, properties) => ({sourceLayer, properties}); + + test('nothing was clicked', () => { + expect(overlayPopupHtml([])).toBeNull(); + expect(overlayPopupHtml(undefined)).toBeNull(); + }); + + test('names the feature and lists its attributes', () => { + const html = overlayPopupHtml([feature('towers', {name: 'Big Tower', height_m: 120, owner: ''})]); + expect(html).toContain('Big Tower'); + expect(html).toContain('towers'); + expect(html).toContain('height_m: 120'); + // An empty attribute says nothing. + expect(html).not.toContain('owner'); + }); + + test('a feature without a name is called by its layer', () => { + const html = overlayPopupHtml([feature('power_lines', {voltage: 230000})]); + expect(html).toContain('power_lines'); + expect(html).toContain('voltage: 230000'); + }); + + test("a file's text cannot add markup to the page", () => { + const html = overlayPopupHtml([feature('layer', {name: '', 'k': 'v'})]); + expect(html).not.toContain(''); + expect(html).not.toContain(''); + expect(html).not.toContain(''); + expect(html).toContain('<img src=x onerror=alert(1)>'); + }); + + test('the same feature drawn twice is listed once, and a long list is cut short', () => { + const tower = feature('towers', {name: 'Big Tower'}); + expect(overlayPopupHtml([tower, {...tower}]).match(/Big Tower/g)).toHaveLength(1); + + const many = [1, 2, 3, 4, 5].map(i => feature('towers', {name: `Tower ${i}`})); + const html = overlayPopupHtml(many); + expect(html).toContain('Tower 3'); + expect(html).not.toContain('Tower 4'); + + const properties = Object.fromEntries([...Array(20).keys()].map(i => [`key${i}`, i])); + const long = overlayPopupHtml([feature('towers', properties)]); + expect(long).toContain('key11: 11'); + expect(long).not.toContain('key12: 12'); + expect(long).toContain('8 more'); + }); +}); diff --git a/app/src/components/mapPoiPopup.js b/app/src/components/mapPoiPopup.js index b744b71c..bf9b1720 100644 --- a/app/src/components/mapPoiPopup.js +++ b/app/src/components/mapPoiPopup.js @@ -2,7 +2,7 @@ // The Protomaps basemap keeps name, kind, kind_detail and elevation; there is no address, // phone or opening hours to show. -function escapeHtml(value) { +export function escapeHtml(value) { return String(value) .replace(/&/g, "&") .replace(/') +@map_bp.delete('/files/') @openapi.description('Delete a PMTiles map file') @wrol_mode_check async def delete_file(_: Request, filename: str): @@ -34,6 +34,21 @@ async def delete_file(_: Request, filename: str): return response.json({'error': 'File not found'}, HTTPStatus.NOT_FOUND) +@map_bp.post('/files/visible') +@openapi.description('Show a PMTiles map file on the map, or ignore it') +@validate(schema.MapFileVisibleRequest) +@wrol_mode_check +async def post_file_visible(_: Request, body: schema.MapFileVisibleRequest): + try: + found = lib.set_pmtiles_file_visible(body.map_path, body.visible) + except ValueError as e: + return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST) + + if found: + return response.empty() + return response.json({'error': 'File not found'}, HTTPStatus.NOT_FOUND) + + @map_bp.get('/subscribe') @openapi.description('Get map catalog and current subscriptions') def get_subscriptions(request: Request): @@ -148,7 +163,7 @@ async def rebuild_search_indexes(_: Request): return json_response({'error': 'No PMTiles files found'}, HTTPStatus.NOT_FOUND) -@map_bp.post('/search/rebuild/') +@map_bp.post('/search/rebuild/') @openapi.description('Rebuild search index for a single PMTiles file') @wrol_mode_check async def rebuild_single_search_index(_: Request, filename: str): diff --git a/modules/map/config.py b/modules/map/config.py new file mode 100644 index 00000000..2ded6ac6 --- /dev/null +++ b/modules/map/config.py @@ -0,0 +1,60 @@ +from dataclasses import dataclass, field +from typing import List + +from wrolpi.common import ConfigFile, logger + +logger = logger.getChild(__name__) + + +@dataclass +class MapsConfigValidator: + version: int = None + ignored_files: list = field(default_factory=list) + + +class MapsConfig(ConfigFile): + """Settings of the map files. + + `ignored_files` are PMTiles files (relative to the map directory) the map does not draw, offer as a layer, or + search. A file the config does not name is visible.""" + file_name = 'maps.yaml' + default_config = dict( + version=0, + ignored_files=[], + ) + validator = MapsConfigValidator + + @property + def ignored_files(self) -> List[str]: + return [str(i) for i in self._config.get('ignored_files') or []] + + def is_ignored(self, map_path: str) -> bool: + return str(map_path) in self.ignored_files + + def set_ignored(self, map_path: str, ignored: bool) -> bool: + """Ignore (or stop ignoring) a map file. Returns True if this changed the config.""" + map_path = str(map_path) + ignored_files = set(self.ignored_files) + if (map_path in ignored_files) == ignored: + return False + if ignored: + ignored_files.add(map_path) + else: + ignored_files.discard(map_path) + # Saves the config in the background. + self.update({'ignored_files': sorted(ignored_files)}) + return True + + +MAPS_CONFIG: MapsConfig = MapsConfig() + +# Test override. +TEST_MAPS_CONFIG = None + + +def get_maps_config() -> MapsConfig: + global TEST_MAPS_CONFIG + if isinstance(TEST_MAPS_CONFIG, ConfigFile): + return TEST_MAPS_CONFIG + return MAPS_CONFIG + diff --git a/modules/map/conftest.py b/modules/map/conftest.py new file mode 100644 index 00000000..58546d05 --- /dev/null +++ b/modules/map/conftest.py @@ -0,0 +1,51 @@ +import gzip +import json +import struct +from pathlib import Path +from typing import Callable + +import pytest + +PROTOMAPS_LAYERS = ('boundaries', 'buildings', 'earth', 'landcover', 'landuse', 'places', 'pois', 'roads', 'water') + + +def pmtiles_bytes(metadata: dict = None, tile_type: int = 1, min_zoom: int = 0, max_zoom: int = 8, + bounds: tuple = (-180.0, -85.0, 180.0, 85.0), compress: bool = True) -> bytes: + """A PMTiles version 3 file with a header and metadata, but no tiles.""" + raw = json.dumps(metadata if metadata is not None else dict()).encode() + if compress: + raw = gzip.compress(raw) + header = bytearray(127) + header[0:7] = b'PMTiles' + header[7] = 3 + # Root directory (empty), then the metadata. + struct.pack_into(' dict: + """PMTiles metadata of a vector file with these layers. `geometries` are recorded as tippecanoe does.""" + metadata['vector_layers'] = [dict(id=i, fields=dict(name='String'), minzoom=0, maxzoom=8) for i in layer_ids] + if geometries: + metadata['tilestats'] = dict(layers=[dict(layer=k, geometry=v, count=1) for k, v in geometries.items()]) + return metadata + + +@pytest.fixture +def make_pmtiles(test_directory) -> Callable[..., Path]: + """Create a readable PMTiles file in the media directory. A file is a Protomaps basemap unless `metadata` (or a + raster `tile_type`) says otherwise.""" + + def _(path: str, metadata: dict = None, **kwargs) -> Path: + path = test_directory / path + path.parent.mkdir(parents=True, exist_ok=True) + if metadata is None and kwargs.get('tile_type', 1) == 1: + metadata = vector_metadata(*PROTOMAPS_LAYERS, name='Protomaps Basemap', type='baselayer') + path.write_bytes(pmtiles_bytes(metadata, **kwargs)) + return path + + return _ diff --git a/modules/map/lib.py b/modules/map/lib.py index 84526e8a..27dc9f3e 100644 --- a/modules/map/lib.py +++ b/modules/map/lib.py @@ -5,7 +5,9 @@ from typing import List, Dict from sqlalchemy.orm import Session +from modules.map import pmtiles from modules.map.catalog import MAP_REGIONS, MAP_REGIONS_BY_NAME, MANIFEST_URL +from modules.map.config import get_maps_config from wrolpi.common import get_media_directory, walk, logger, get_wrolpi_config, aiohttp_get, verify_gpg_signature from wrolpi.downloader import DownloadFrequency, Download, save_downloads_config, download_manager @@ -19,47 +21,93 @@ def get_map_directory() -> Path: return map_directory +def iter_map_files(suffix: str) -> List[Path]: + """The files in the map directory (at any depth) whose name ends with `suffix`, sorted. + + Hidden directories are skipped; an unfinished download waits in one under its final name.""" + map_directory = get_map_directory() + paths = [] + for path in walk(map_directory): + if not path.name.endswith(suffix) or not path.is_file(): + continue + if any(i.startswith('.') for i in path.relative_to(map_directory).parts): + continue + paths.append(path) + return sorted(paths) + + +def get_map_path(path: Path) -> str: + """The name of a map file in the API and the maps config: its path relative to the map directory.""" + return path.relative_to(get_map_directory()).as_posix() + + def get_pmtiles_files() -> List[dict]: """Find all .pmtiles files in the map directory and return their metadata.""" - map_directory = get_map_directory() - paths = walk(map_directory) + maps_config = get_maps_config() files = [] - for path in sorted(paths): - if path.is_file() and path.suffix == '.pmtiles': - stat = path.stat() - files.append(dict( - name=path.name, - path=str(path.relative_to(get_media_directory())), - size=stat.st_size, - mtime=stat.st_mtime, - has_search_index=path.with_suffix('.search.db').is_file(), - )) + for path in iter_map_files('.pmtiles'): + stat = path.stat() + map_path = get_map_path(path) + files.append(dict( + name=path.name, + path=str(path.relative_to(get_media_directory())), + map_path=map_path, + size=stat.st_size, + mtime=stat.st_mtime, + has_search_index=path.with_suffix('.search.db').is_file(), + visible=not maps_config.is_ignored(map_path), + **pmtiles.describe(path), + )) return files +def _resolve_pmtiles_file(filename: str) -> Path | None: + """The PMTiles file in the map directory that `filename` (relative to the map directory) names, if it exists. + + Raises ValueError if the name leads outside of the map directory.""" + map_directory = get_map_directory().resolve() + # Prevent path traversal. + path = (map_directory / filename).resolve() + if not path.is_relative_to(map_directory): + raise ValueError(f'Invalid filename: {filename}') + + if path.is_file() and path.suffix == '.pmtiles': + return path + return None + + def delete_pmtiles_file(filename: str) -> bool: """Delete a PMTiles file from the map directory. Returns True if the file was deleted. Also deletes the companion .search.db file if it exists.""" - map_directory = get_map_directory() - # Prevent path traversal. - path = (map_directory / filename).resolve() - if not path.is_relative_to(map_directory.resolve()): - raise ValueError(f'Invalid filename: {filename}') + path = _resolve_pmtiles_file(filename) + if not path: + return False - if path.is_file() and path.suffix == '.pmtiles': - path.unlink() - logger.warning(f'Deleted PMTiles file: {path}') - # Also delete companion search index. - search_db = path.with_suffix('.search.db') - if search_db.is_file(): - search_db.unlink() - logger.warning(f'Deleted search index: {search_db}') - return True + map_path = path.relative_to(get_map_directory().resolve()).as_posix() + path.unlink() + logger.warning(f'Deleted PMTiles file: {path}') + # Also delete companion search index. + search_db = path.with_suffix('.search.db') + if search_db.is_file(): + search_db.unlink() + logger.warning(f'Deleted search index: {search_db}') + # A file that is gone is not ignored; a later file of the same name starts visible. + get_maps_config().set_ignored(map_path, False) + return True - return False + +def set_pmtiles_file_visible(filename: str, visible: bool) -> bool: + """Show a PMTiles file on the map, or ignore it. Returns False if there is no such file.""" + path = _resolve_pmtiles_file(filename) + if not path: + return False + + map_path = path.relative_to(get_map_directory().resolve()).as_posix() + get_maps_config().set_ignored(map_path, not visible) + return True def get_map_catalog() -> List[dict]: diff --git a/modules/map/pmtiles.py b/modules/map/pmtiles.py new file mode 100644 index 00000000..d6b46722 --- /dev/null +++ b/modules/map/pmtiles.py @@ -0,0 +1,195 @@ +"""Read the header and metadata of a PMTiles (version 3) file. + +A PMTiles file starts with a fixed 127 byte header, which says where the JSON metadata is. Neither needs the tile +data, so describing a file is two small reads. + +https://github.com/protomaps/PMTiles/blob/main/spec/v3/spec.md +""" +import json +import struct +import zlib +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +from wrolpi.common import logger + +logger = logger.getChild(__name__) + +__all__ = ['read_pmtiles_info', 'classify', 'describe', 'is_searchable', + 'KIND_BASEMAP', 'KIND_OVERLAY', 'KIND_TERRAIN', 'KIND_UNKNOWN'] + +MAGIC = b'PMTiles' +HEADER_SIZE = 127 +# Metadata larger than this (as stored, or once decompressed) is not read; the file is described by its header +# alone. A map file is something a person downloaded: a few bytes of it must not be able to fill the memory. +MAX_METADATA_SIZE = 16 * 1024 * 1024 + +COMPRESSION_NONE = 1 +COMPRESSION_GZIP = 2 + +TILE_TYPES = { + 1: 'mvt', + 2: 'png', + 3: 'jpeg', + 4: 'webp', + 5: 'avif', +} + +KIND_BASEMAP = 'basemap' +KIND_OVERLAY = 'overlay' +KIND_TERRAIN = 'terrain' +KIND_UNKNOWN = 'unknown' + +# A terrain (elevation) file is named, its tiles are images like any other raster file. +TERRAIN_PREFIX = 'terrain-' +# Layers every Protomaps basemap has; the map's basemap theme can only draw this schema. +BASEMAP_LAYERS = frozenset({'earth', 'water', 'roads'}) +# Layers the place search index is built from. +SEARCHABLE_LAYERS = frozenset({'places', 'pois'}) + +# (path, mtime_ns, size) -> info. A file is only read again when it changes. +_CACHE: Dict[Tuple[str, int, int], Optional[dict]] = dict() + + +def _tilestats_geometries(metadata: dict) -> Dict[str, str]: + """The geometry type of each layer, when the file's generator recorded it (tippecanoe does).""" + tilestats = metadata.get('tilestats') + layers = tilestats.get('layers') if isinstance(tilestats, dict) else None + geometries = dict() + for layer in layers if isinstance(layers, list) else []: + if isinstance(layer, dict) and layer.get('layer') and isinstance(layer.get('geometry'), str): + geometries[str(layer['layer'])] = layer['geometry'] + return geometries + + +def _vector_layers(metadata: dict) -> List[dict]: + geometries = _tilestats_geometries(metadata) + layers = [] + vector_layers = metadata.get('vector_layers') + for layer in vector_layers if isinstance(vector_layers, list) else []: + if not isinstance(layer, dict) or not layer.get('id'): + continue + id_ = str(layer['id']) + layers.append(dict( + id=id_, + minzoom=layer.get('minzoom'), + maxzoom=layer.get('maxzoom'), + description=layer.get('description') or None, + geometry=geometries.get(id_), + )) + return layers + + +def _text(value) -> Optional[str]: + return str(value) if value not in (None, '') else None + + +def _gunzip(raw: bytes) -> bytes: + """Decompress gzip data, refusing to produce more than MAX_METADATA_SIZE.""" + decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS) + data = decompressor.decompress(raw, MAX_METADATA_SIZE) + if decompressor.unconsumed_tail: + raise ValueError(f'metadata is larger than {MAX_METADATA_SIZE} bytes') + return data + + +def _read(path: Path) -> Optional[dict]: + with path.open('rb') as fh: + header = fh.read(HEADER_SIZE) + if len(header) < HEADER_SIZE or header[:7] != MAGIC or header[7] != 3: + return None + + metadata_offset, metadata_length = struct.unpack_from(' Optional[dict]: + """Describe a PMTiles file from its header and metadata. Returns None if the file is not a readable PMTiles + version 3 file; never raises.""" + try: + stat = path.stat() + except OSError: + return None + + key = (str(path), stat.st_mtime_ns, stat.st_size) + if key not in _CACHE: + try: + info = _read(path) + except (OSError, struct.error) as e: + logger.warning(f'Unable to read PMTiles file {path}: {e}') + info = None + # Forget what this path used to be. + for old in [i for i in _CACHE if i[0] == key[0]]: + del _CACHE[old] + _CACHE[key] = info + info = _CACHE[key] + return dict(info, vector_layers=[dict(i) for i in info['vector_layers']]) if info else None + + +def _layer_ids(info: Optional[dict]) -> set: + return {i['id'] for i in info['vector_layers']} if info else set() + + +def classify(name: str, info: Optional[dict]) -> str: + """How the map draws a file: `terrain` (hillshade and contours), `basemap` (Protomaps schema, drawn with the + basemap theme), `overlay` (anything else, vector or raster), or `unknown` (unreadable, never drawn).""" + if name.startswith(TERRAIN_PREFIX): + return KIND_TERRAIN + if not info: + return KIND_UNKNOWN + if info['tile_type'] == 'mvt' and BASEMAP_LAYERS <= _layer_ids(info): + return KIND_BASEMAP + return KIND_OVERLAY + + +def is_searchable(path: Path) -> bool: + """Whether a place search index can be built from this file.""" + info = read_pmtiles_info(path) + return classify(path.name, info) == KIND_BASEMAP and bool(SEARCHABLE_LAYERS & _layer_ids(info)) + + +EMPTY_INFO = dict( + tile_type=None, + min_zoom=None, + max_zoom=None, + bounds=None, + title=None, + description=None, + attribution=None, + metadata_type=None, + vector_layers=[], +) + + +def describe(path: Path) -> dict: + """The `kind` of a PMTiles file and what its header and metadata say, with empty values for an unreadable + file.""" + info = read_pmtiles_info(path) + return dict(info or EMPTY_INFO, kind=classify(path.name, info)) diff --git a/modules/map/schema.py b/modules/map/schema.py index 0bc5c820..79d33601 100644 --- a/modules/map/schema.py +++ b/modules/map/schema.py @@ -7,6 +7,12 @@ class MapSubscribeRequest: region: str +@dataclass +class MapFileVisibleRequest: + map_path: str + visible: bool + + @dataclass class MapPinRequest: lat: float diff --git a/modules/map/search.py b/modules/map/search.py index 8806d7b8..e7d98dd6 100644 --- a/modules/map/search.py +++ b/modules/map/search.py @@ -7,7 +7,9 @@ import sys from pathlib import Path from typing import List -from modules.map.lib import get_map_directory +from modules.map import pmtiles +from modules.map.config import get_maps_config +from modules.map.lib import get_map_directory, get_map_path, iter_map_files from wrolpi.common import logger, background_task from wrolpi.events import Events from wrolpi.flags import map_search_building @@ -17,10 +19,19 @@ logger = logger.getChild(__name__) BUILD_SCRIPT = Path(__file__).parent.parent.parent / 'wrolpi' / 'scripts' / 'build_map_search.py' +SEARCH_DB_SUFFIX = '.search.db' + + +def get_searchable_pmtiles_files() -> List[Path]: + """The PMTiles files a place search index can be built from.""" + return [i for i in iter_map_files('.pmtiles') if pmtiles.is_searchable(i)] + + def get_search_db_files() -> List[Path]: - """Find all .search.db files in the map directory.""" - map_directory = get_map_directory() - return sorted(map_directory.glob('*.search.db')) + """Find the .search.db files in the map directory (at any depth), except those of ignored map files.""" + maps_config = get_maps_config() + return [i for i in iter_map_files(SEARCH_DB_SUFFIX) + if not maps_config.is_ignored(get_map_path(i).removesuffix(SEARCH_DB_SUFFIX) + '.pmtiles')] def search_places(query: str, limit: int = 12, offset: int = 0, lat: float = None, lon: float = None) -> dict: @@ -176,20 +187,16 @@ def search_places_count(query: str) -> int: def get_search_status() -> dict: - """Return status of search indexes: which PMTiles files have indexes and which don't.""" - map_directory = get_map_directory() - - pmtiles_files = sorted(map_directory.glob('*.pmtiles')) - # Strip the double .search.db extension to get the PMTiles stem. - search_db_files = {p.name.removesuffix('.search.db') for p in get_search_db_files()} + """Return status of search indexes: which PMTiles files have indexes and which don't. + Only files a search index can be built from are listed (a Protomaps basemap; not terrain or an overlay).""" indexed = [] missing = [] - for pmtiles_path in pmtiles_files: - info = {'name': pmtiles_path.name, 'stem': pmtiles_path.stem} - if pmtiles_path.stem in search_db_files: - db_path = pmtiles_path.with_suffix('.search.db') + for pmtiles_path in get_searchable_pmtiles_files(): + info = {'name': pmtiles_path.name, 'stem': pmtiles_path.stem, 'map_path': get_map_path(pmtiles_path)} + db_path = pmtiles_path.with_suffix(SEARCH_DB_SUFFIX) + if db_path.is_file(): info['search_db_size'] = db_path.stat().st_size indexed.append(info) else: @@ -275,7 +282,7 @@ def rebuild_all_search_indexes(max_zoom: int = 10) -> bool: """Launch the build script for the entire map directory as a background task.""" map_directory = get_map_directory() - if not any(map_directory.glob('*.pmtiles')): + if not get_searchable_pmtiles_files(): return False if map_search_building.is_set(): diff --git a/modules/map/static/embed.html b/modules/map/static/embed.html index 3587e2e5..52c459aa 100644 --- a/modules/map/static/embed.html +++ b/modules/map/static/embed.html @@ -29,15 +29,21 @@ var sources = {}; var allLayers = []; - // Add user's PMTiles files (skip terrain). Includes map-overview if present. + // Add user's basemap PMTiles files: not terrain, overlays, or files the user ignores. var files = (data.files || []).filter(function(f) { - return f.name.indexOf("terrain") !== 0; + if (f.visible === false) return false; + return f.kind ? f.kind === "basemap" : f.name.indexOf("terrain") !== 0; }); files.forEach(function(f, i) { - sources[f.name] = {type: "vector", url: "pmtiles:///data/" + f.name}; - var layers = protomaps_themes_base.default(f.name, flavor); + // A file is named by its path in the map directory; it may be in a sub-directory. + var mapPath = f.map_path || f.name; + // Each part of the path is encoded: a `#` or `?` in a file name would otherwise end the + // path, and another file (or none) would be asked for. + var dataPath = "/data/" + String(mapPath).split("/").map(encodeURIComponent).join("/"); + sources[mapPath] = {type: "vector", url: "pmtiles://" + dataPath}; + var layers = protomaps_themes_base.default(mapPath, flavor); if (i > 0) { - layers.forEach(function(l) { l.id = f.name + ":" + l.id; }); + layers.forEach(function(l) { l.id = mapPath + ":" + l.id; }); } allLayers = allLayers.concat(layers); }); diff --git a/modules/map/static/index.html b/modules/map/static/index.html index 0fc07b89..ba4f9e76 100644 --- a/modules/map/static/index.html +++ b/modules/map/static/index.html @@ -204,6 +204,12 @@ var MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles"; var TERRAIN_PREFIX = "terrain-"; + // The URL path of a map file. Each part of its path is encoded: a `#` or `?` in a file name + // would otherwise end the path, and another file (or none) would be asked for. + function dataPath(mapPath) { + return "/data/" + String(mapPath).split("/").map(encodeURIComponent).join("/"); + } + function isPlanetFile(name) { if (name.indexOf("planet-") === 0) return true; return /^\d{8}\.pmtiles$/.test(name); @@ -293,7 +299,7 @@ var filename = sourceNames[fi]; sources[filename] = { type: "vector", - url: "pmtiles:///data/" + filename, + url: "pmtiles://" + dataPath(filename), }; var fileLayers = protomaps_themes_base.default(filename, flavor); if (si === 0 && fi === 0) { @@ -318,7 +324,7 @@ sources["terrain-dem"] = { type: "raster-dem", - url: "pmtiles://" + window.location.origin + "/data/" + terrainFileName, + url: "pmtiles://" + window.location.origin + dataPath(terrainFileName), encoding: "terrarium", tileSize: 512, }; @@ -705,9 +711,18 @@ var regionFiles = []; for (var i = 0; i < allFiles.length; i++) { var f = allFiles[i]; - if (f.name.startsWith(TERRAIN_PREFIX) && f.name.endsWith('.pmtiles')) { - terrainFileName = f.name; + // A file the user ignores is not drawn. + if (f.visible === false) continue; + // A file is named by its path in the map directory; it may be in a sub-directory. + f.mapPath = f.map_path || f.name; + var isTerrain = f.kind ? f.kind === "terrain" + : (f.name.startsWith(TERRAIN_PREFIX) && f.name.endsWith('.pmtiles')); + if (isTerrain) { + terrainFileName = f.mapPath; hasTerrain = true; + } else if (f.kind && f.kind !== "basemap") { + // Overlays (and unreadable files) are not the basemap schema this viewer draws. + continue; } else if (isPlanetFile(f.name)) { if (!planetFile || f.size > planetFile.size) { planetFile = f; @@ -720,13 +735,13 @@ var pmtilesFiles; if (planetFile) { // Planet covers everything — sole vector source, no overview needed. - pmtilesFiles = [planetFile.name]; + pmtilesFiles = [planetFile.mapPath]; hasPlanetOverview = false; return pmtilesFiles; } // Use regional extracts. - pmtilesFiles = regionFiles.map(function(f) { return f.name; }); + pmtilesFiles = regionFiles.map(function(f) { return f.mapPath; }); // Check for planet overview blob as low-zoom base layer. return fetch(MAP_OVERVIEW_URL, {method: "HEAD"}) @@ -739,7 +754,7 @@ // Initialize contour source if terrain available. if (hasTerrain && !demSource) { demSource = new mlcontour.DemSource({ - url: "pmtiles://" + window.location.origin + "/data/" + terrainFileName, + url: "pmtiles://" + window.location.origin + dataPath(terrainFileName), encoding: "terrarium", maxzoom: 8, worker: true, diff --git a/modules/map/test/test_api.py b/modules/map/test/test_api.py index 9bca98df..b4b2e442 100644 --- a/modules/map/test/test_api.py +++ b/modules/map/test/test_api.py @@ -1,8 +1,14 @@ import json from http import HTTPStatus +from unittest import mock import pytest +import yaml +from modules.map.config import get_maps_config +from modules.map.conftest import vector_metadata +from wrolpi.api_utils import api_app +from wrolpi.common import get_all_configs from wrolpi.conftest import production_like_sessions, write_lock_held_briefly @@ -180,3 +186,104 @@ async def test_subscription_writes_wait_for_a_concurrent_writer(async_client, te _, response = await async_client.get('/api/map/subscribe') regions = [i['region'] for i in response.json['subscriptions']] assert regions == (['us-alaska'] if step == 'subscribe' else []) + + +@pytest.mark.asyncio +async def test_get_files_describes_files(async_client, test_directory, make_pmtiles): + """A file is described by its own metadata, and by how the map draws it.""" + make_pmtiles('map/usa.pmtiles') + make_pmtiles('map/extras/features.pmtiles', + vector_metadata('towers', geometries=dict(towers='Point'), name='Features', description='Things')) + + request, response = await async_client.get('/api/map/files') + assert response.status_code == HTTPStatus.OK + files = {i['map_path']: i for i in response.json['files']} + assert files['usa.pmtiles']['kind'] == 'basemap' + assert files['usa.pmtiles']['title'] == 'Protomaps Basemap' + features = files['extras/features.pmtiles'] + assert features['kind'] == 'overlay' + assert features['title'] == 'Features' + assert features['description'] == 'Things' + assert features['path'] == 'map/extras/features.pmtiles' + assert features['visible'] is True + assert features['vector_layers'] == [ + dict(id='towers', minzoom=0, maxzoom=8, description=None, geometry='Point')] + + +@pytest.mark.asyncio +async def test_delete_file_sub_directory(async_client, test_directory, make_pmtiles): + """A file in a sub-directory can be deleted.""" + pmtiles_file = make_pmtiles('map/extras/deeper/features.pmtiles') + + request, response = await async_client.delete('/api/map/files/extras/deeper/features.pmtiles') + assert response.status_code == HTTPStatus.NO_CONTENT + assert not pmtiles_file.exists() + + +@pytest.mark.asyncio +async def test_rebuild_search_index_sub_directory(async_client, test_directory, make_pmtiles): + """The search index of a file in a sub-directory can be built.""" + pmtiles_file = make_pmtiles('map/regions/oregon.pmtiles') + + with mock.patch('modules.map.search._check_tippecanoe', return_value=True), \ + mock.patch('modules.map.search._run_build', new_callable=mock.AsyncMock) as mock_run_build: + request, response = await async_client.post('/api/map/search/rebuild/regions/oregon.pmtiles') + assert response.status_code == HTTPStatus.ACCEPTED + cmd, description = mock_run_build.call_args.args + assert str(pmtiles_file) in cmd + + +@pytest.mark.asyncio +async def test_file_visible(async_client, test_directory, make_pmtiles): + """A map file can be ignored and shown again; the choice is saved to the maps config.""" + make_pmtiles('map/extras/api-ignored.pmtiles') + config_file = test_directory / 'config/maps.yaml' + + body = dict(map_path='extras/api-ignored.pmtiles', visible=False) + request, response = await async_client.post('/api/map/files/visible', json=body) + assert response.status_code == HTTPStatus.NO_CONTENT + request, response = await async_client.get('/api/map/files') + assert [i['visible'] for i in response.json['files']] == [False] + assert yaml.safe_load(config_file.read_text())['ignored_files'] == ['extras/api-ignored.pmtiles'] + + body = dict(map_path='extras/api-ignored.pmtiles', visible=True) + request, response = await async_client.post('/api/map/files/visible', json=body) + assert response.status_code == HTTPStatus.NO_CONTENT + request, response = await async_client.get('/api/map/files') + assert [i['visible'] for i in response.json['files']] == [True] + assert yaml.safe_load(config_file.read_text())['ignored_files'] == [] + + +@pytest.mark.asyncio +async def test_file_visible_unknown_file(async_client, test_directory): + """A file which does not exist cannot be ignored.""" + body = dict(map_path='missing.pmtiles', visible=False) + request, response = await async_client.post('/api/map/files/visible', json=body) + assert response.status_code == HTTPStatus.NOT_FOUND + + body = dict(map_path='../../etc/passwd', visible=False) + request, response = await async_client.post('/api/map/files/visible', json=body) + assert response.status_code == HTTPStatus.BAD_REQUEST + + +@pytest.mark.asyncio +async def test_maps_config_import(async_client, test_directory, make_pmtiles): + """A maps config a person edited is applied when it is imported.""" + make_pmtiles('map/hand-edited.pmtiles') + make_pmtiles('map/other.pmtiles') + config = get_maps_config() + config.get_file().parent.mkdir(parents=True, exist_ok=True) + config.get_file().write_text(yaml.safe_dump(dict(version=1, ignored_files=['hand-edited.pmtiles']))) + + config.import_config() + + request, response = await async_client.get('/api/map/files') + visible = {i['map_path']: i['visible'] for i in response.json['files']} + assert visible == {'hand-edited.pmtiles': False, 'other.pmtiles': True} + + +def test_maps_config_is_shared(async_client): + """The maps config lives in the context the Sanic workers share (a config which does not is saved by one + worker and overwritten by another), and is among the configs WROLPi manages.""" + assert get_maps_config()._config is api_app.shared_ctx.maps_config + assert get_all_configs()['maps.yaml'] is get_maps_config() diff --git a/modules/map/test/test_lib.py b/modules/map/test/test_lib.py index b336df46..9f7491cb 100644 --- a/modules/map/test/test_lib.py +++ b/modules/map/test/test_lib.py @@ -3,6 +3,8 @@ from unittest import mock import pytest from modules.map import lib +from modules.map.config import get_maps_config +from modules.map.conftest import vector_metadata from wrolpi.common import get_wrolpi_config @@ -170,3 +172,92 @@ def test_get_custom_map_directory(async_client, test_directory, test_wrolpi_conf assert lib.get_map_directory() == (test_directory / 'custom/deep/map/directory') assert (test_directory / 'custom/deep/map/directory').is_dir() + + +def test_get_pmtiles_files_sub_directories(test_directory, make_pmtiles): + """Files in sub-directories of the map directory are listed by their path within it. Unfinished downloads + (in a hidden directory) are not listed.""" + make_pmtiles('map/usa.pmtiles') + make_pmtiles('map/extras/features.pmtiles', vector_metadata('towers', name='Features', type='overlay')) + make_pmtiles('map/extras/deeper/satellite.pmtiles', dict(), tile_type=3) + make_pmtiles('map/.partial/oregon.pmtiles') + + files = {i['map_path']: i for i in lib.get_pmtiles_files()} + assert sorted(files) == ['extras/deeper/satellite.pmtiles', 'extras/features.pmtiles', 'usa.pmtiles'] + + features = files['extras/features.pmtiles'] + assert features['name'] == 'features.pmtiles' + assert features['path'] == 'map/extras/features.pmtiles' + assert features['kind'] == 'overlay' + assert features['title'] == 'Features' + assert features['tile_type'] == 'mvt' + assert [i['id'] for i in features['vector_layers']] == ['towers'] + assert features['visible'] is True + + assert files['usa.pmtiles']['kind'] == 'basemap' + assert files['extras/deeper/satellite.pmtiles']['kind'] == 'overlay' + assert files['extras/deeper/satellite.pmtiles']['tile_type'] == 'jpeg' + + +def test_get_pmtiles_files_unreadable(test_directory, make_files_structure): + """A file which cannot be read is listed (so it can be deleted), as a file the map cannot draw.""" + make_files_structure(['map/empty.pmtiles']) + file, = lib.get_pmtiles_files() + assert file['kind'] == 'unknown' + assert file['title'] is None + assert file['vector_layers'] == [] + + +def test_delete_pmtiles_file_sub_directory(test_directory, make_pmtiles): + """A file in a sub-directory is deleted by its path within the map directory, with its search index.""" + pmtiles_file = make_pmtiles('map/extras/features.pmtiles') + search_db = pmtiles_file.with_suffix('.search.db') + search_db.touch() + same_name = make_pmtiles('map/features.pmtiles') + + assert lib.delete_pmtiles_file('extras/features.pmtiles') is True + assert not pmtiles_file.exists() + assert not search_db.exists() + # The file of the same name in the map directory is another file. + assert same_name.is_file() + + +def test_set_pmtiles_file_visible(async_client, test_directory, make_pmtiles): + """An ignored file is listed as not visible, in the maps config, until it is shown again.""" + make_pmtiles('map/extras/ignore-me.pmtiles') + make_pmtiles('map/ignore-me.pmtiles') + + assert lib.set_pmtiles_file_visible('extras/ignore-me.pmtiles', False) is True + assert get_maps_config().ignored_files == ['extras/ignore-me.pmtiles'] + visible = {i['map_path']: i['visible'] for i in lib.get_pmtiles_files()} + assert visible == {'ignore-me.pmtiles': True, 'extras/ignore-me.pmtiles': False} + + assert lib.set_pmtiles_file_visible('extras/ignore-me.pmtiles', True) is True + assert get_maps_config().ignored_files == [] + assert all(i['visible'] for i in lib.get_pmtiles_files()) + + +def test_set_pmtiles_file_visible_unknown_file(async_client, test_directory, make_pmtiles): + """Only a map file can be ignored.""" + make_pmtiles('map/usa.pmtiles') + (test_directory / 'map/notes.txt').write_text('notes') + + assert lib.set_pmtiles_file_visible('missing.pmtiles', False) is False + assert lib.set_pmtiles_file_visible('notes.txt', False) is False + with pytest.raises(ValueError): + lib.set_pmtiles_file_visible('../../etc/passwd', False) + assert get_maps_config().ignored_files == [] + + +def test_delete_pmtiles_file_forgets_ignored(async_client, test_directory, make_pmtiles): + """A deleted file is no longer ignored, so a new file of the same name is drawn.""" + make_pmtiles('map/ignored-then-deleted.pmtiles') + lib.set_pmtiles_file_visible('ignored-then-deleted.pmtiles', False) + assert get_maps_config().ignored_files == ['ignored-then-deleted.pmtiles'] + + assert lib.delete_pmtiles_file('ignored-then-deleted.pmtiles') is True + assert get_maps_config().ignored_files == [] + + make_pmtiles('map/ignored-then-deleted.pmtiles') + file, = lib.get_pmtiles_files() + assert file['visible'] is True diff --git a/modules/map/test/test_pmtiles.py b/modules/map/test/test_pmtiles.py new file mode 100644 index 00000000..5dafedbc --- /dev/null +++ b/modules/map/test/test_pmtiles.py @@ -0,0 +1,137 @@ +import os + +import pytest + +from modules.map import pmtiles +from modules.map.conftest import pmtiles_bytes, vector_metadata, PROTOMAPS_LAYERS + + +def test_read_vector_overlay(test_directory, make_pmtiles): + """The header and metadata of a vector file are read; the bulky tilestats are reduced to a geometry per layer.""" + metadata = vector_metadata( + 'power_lines', 'towers', 'flood_zones', + geometries=dict(power_lines='LineString', towers='Point'), + name='Features', description='Topographic features', attribution='Somebody', type='overlay', + ) + path = make_pmtiles('map/features.pmtiles', metadata, min_zoom=2, max_zoom=9, bounds=(-125.5, 24.0, -66.0, 49.5)) + + info = pmtiles.read_pmtiles_info(path) + assert info == dict( + tile_type='mvt', + min_zoom=2, + max_zoom=9, + bounds=[-125.5, 24.0, -66.0, 49.5], + title='Features', + description='Topographic features', + attribution='Somebody', + metadata_type='overlay', + vector_layers=[ + dict(id='power_lines', minzoom=0, maxzoom=8, description=None, geometry='LineString'), + dict(id='towers', minzoom=0, maxzoom=8, description=None, geometry='Point'), + dict(id='flood_zones', minzoom=0, maxzoom=8, description=None, geometry=None), + ], + ) + assert pmtiles.classify(path.name, info) == pmtiles.KIND_OVERLAY + + +def test_read_uncompressed_metadata(test_directory, make_pmtiles): + """Metadata which is not compressed is read too.""" + path = make_pmtiles('map/plain.pmtiles', vector_metadata('roads', name='Plain'), compress=False) + info = pmtiles.read_pmtiles_info(path) + assert info['title'] == 'Plain' + assert [i['id'] for i in info['vector_layers']] == ['roads'] + + +def test_read_without_metadata(test_directory, make_pmtiles): + """A raster file may say nothing about itself; it is described by its header.""" + path = make_pmtiles('map/satellite.pmtiles', dict(), tile_type=4, max_zoom=12) + info = pmtiles.read_pmtiles_info(path) + assert info['tile_type'] == 'webp' + assert info['max_zoom'] == 12 + assert info['title'] is None + assert info['vector_layers'] == [] + + +@pytest.mark.parametrize('content', [ + b'', + b'PMTiles', + b'not a pmtiles file' * 20, + # Version 2 has a different header. + b'PMTiles\x02' + bytes(200), +]) +def test_unreadable_file(test_directory, content): + """A file which is not a PMTiles version 3 file is not described, and reading it does not raise.""" + path = test_directory / 'broken.pmtiles' + path.write_bytes(content) + assert pmtiles.read_pmtiles_info(path) is None + assert pmtiles.read_pmtiles_info(test_directory / 'missing.pmtiles') is None + assert pmtiles.classify(path.name, None) == pmtiles.KIND_UNKNOWN + assert pmtiles.describe(path)['kind'] == pmtiles.KIND_UNKNOWN + assert pmtiles.describe(path)['vector_layers'] == [] + + +def test_broken_metadata(test_directory): + """A file whose metadata cannot be decoded is still described by its header.""" + content = bytearray(pmtiles_bytes(vector_metadata('roads', name='Roads'))) + # Corrupt the gzip stream. + content[127:137] = b'0123456789' + path = test_directory / 'corrupt.pmtiles' + path.write_bytes(bytes(content)) + + info = pmtiles.read_pmtiles_info(path) + assert info['tile_type'] == 'mvt' + assert info['title'] is None + assert info['vector_layers'] == [] + + +@pytest.mark.parametrize('name,metadata,tile_type,kind', [ + ('usa.pmtiles', vector_metadata(*PROTOMAPS_LAYERS), 1, pmtiles.KIND_BASEMAP), + # Only the Protomaps schema can be drawn by the basemap theme. + ('openmaptiles.pmtiles', vector_metadata('water', 'transportation', 'place'), 1, pmtiles.KIND_OVERLAY), + ('features.pmtiles', vector_metadata('towers'), 1, pmtiles.KIND_OVERLAY), + ('satellite.pmtiles', dict(), 3, pmtiles.KIND_OVERLAY), + # Terrain is named; its tiles are images like any raster file. + ('terrain-planet.pmtiles', dict(), 4, pmtiles.KIND_TERRAIN), +]) +def test_classify(test_directory, make_pmtiles, name, metadata, tile_type, kind): + path = make_pmtiles(f'map/{name}', metadata, tile_type=tile_type) + assert pmtiles.describe(path)['kind'] == kind + + +def test_is_searchable(test_directory, make_pmtiles): + """A search index is built from the place layers of a basemap.""" + assert pmtiles.is_searchable(make_pmtiles('map/usa.pmtiles')) + assert not pmtiles.is_searchable(make_pmtiles('map/bare.pmtiles', vector_metadata('earth', 'water', 'roads'))) + assert not pmtiles.is_searchable(make_pmtiles('map/features.pmtiles', vector_metadata('places', 'pois'))) + assert not pmtiles.is_searchable(make_pmtiles('map/terrain-x.pmtiles', tile_type=4)) + + +def test_changed_file_is_read_again(test_directory, make_pmtiles): + """A description is remembered until the file changes.""" + path = make_pmtiles('map/features.pmtiles', vector_metadata('towers', name='Before')) + assert pmtiles.read_pmtiles_info(path)['title'] == 'Before' + + stat = path.stat() + make_pmtiles('map/features.pmtiles', vector_metadata('towers', name='After!')) + os.utime(path, ns=(stat.st_atime_ns, stat.st_mtime_ns + 1_000_000_000)) + assert pmtiles.read_pmtiles_info(path)['title'] == 'After!' + + # A caller cannot change what is remembered. + pmtiles.read_pmtiles_info(path)['vector_layers'].clear() + assert [i['id'] for i in pmtiles.read_pmtiles_info(path)['vector_layers']] == ['towers'] + + +def test_metadata_which_decompresses_too_large(test_directory, make_pmtiles, monkeypatch): + """A little compressed metadata can decompress to a great deal; it is not decompressed past the limit, and the + file is described by its header.""" + monkeypatch.setattr(pmtiles, 'MAX_METADATA_SIZE', 10_000) + small = make_pmtiles('map/small.pmtiles', vector_metadata('roads', name='Small')) + assert pmtiles.read_pmtiles_info(small)['title'] == 'Small' + + # Compresses to far less than the limit, and decompresses to far more. + bomb = make_pmtiles('map/bomb.pmtiles', vector_metadata('roads', name='Bomb', padding='0' * 1_000_000)) + assert bomb.stat().st_size < 10_000 + info = pmtiles.read_pmtiles_info(bomb) + assert info['tile_type'] == 'mvt' + assert info['title'] is None + assert info['vector_layers'] == [] diff --git a/modules/map/test/test_search.py b/modules/map/test/test_search.py index b600208b..e21dc653 100644 --- a/modules/map/test/test_search.py +++ b/modules/map/test/test_search.py @@ -5,6 +5,9 @@ from unittest import mock import pytest +from modules.map.conftest import vector_metadata +from wrolpi.scripts import build_map_search + def _create_test_search_db(path: Path, features: list): """Create a minimal .search.db file with given features for testing.""" @@ -128,10 +131,10 @@ async def test_search_status_no_files(async_client, test_directory): @pytest.mark.asyncio -async def test_search_status_with_index(async_client, test_directory, search_db, make_files_structure): +async def test_search_status_with_index(async_client, test_directory, search_db, make_pmtiles): """Status endpoint shows which files have indexes.""" # Create a PMTiles file that matches the search.db stem. - make_files_structure(['map/test.pmtiles']) + make_pmtiles('map/test.pmtiles') request, response = await async_client.get('/api/map/search/status') assert response.status_code == HTTPStatus.OK @@ -140,9 +143,9 @@ async def test_search_status_with_index(async_client, test_directory, search_db, @pytest.mark.asyncio -async def test_search_status_missing_index(async_client, test_directory, make_files_structure): +async def test_search_status_missing_index(async_client, test_directory, make_pmtiles): """Status endpoint shows PMTiles files without search indexes.""" - make_files_structure(['map/usa.pmtiles']) + make_pmtiles('map/usa.pmtiles') request, response = await async_client.get('/api/map/search/status') assert response.status_code == HTTPStatus.OK @@ -164,3 +167,89 @@ async def test_delete_pmtiles_also_deletes_search_db(async_client, test_director # Search DB should also be deleted. assert not search_db.exists() + + +@pytest.mark.asyncio +async def test_search_status_sub_directory(async_client, test_directory, make_pmtiles): + """A map file in a sub-directory of the map directory is listed, with or without its index.""" + make_pmtiles('map/regions/oregon.pmtiles') + indexed = make_pmtiles('map/regions/idaho.pmtiles') + _create_test_search_db(indexed.with_suffix('.search.db'), []) + + request, response = await async_client.get('/api/map/search/status') + assert response.status_code == HTTPStatus.OK + assert [i['map_path'] for i in response.json['missing']] == ['regions/oregon.pmtiles'] + assert [i['map_path'] for i in response.json['indexed']] == ['regions/idaho.pmtiles'] + + +@pytest.mark.asyncio +async def test_search_status_only_lists_searchable_files(async_client, test_directory, make_pmtiles): + """A search index is built from a Protomaps basemap; an overlay, a raster file, a terrain file and an unreadable + file never have one, so they are not reported as missing it.""" + make_pmtiles('map/usa.pmtiles') + make_pmtiles('map/features.pmtiles', vector_metadata('power_lines', 'towers')) + make_pmtiles('map/satellite.pmtiles', tile_type=2) + make_pmtiles('map/terrain-planet.pmtiles', tile_type=4) + (test_directory / 'map/broken.pmtiles').write_bytes(b'not a pmtiles file') + + request, response = await async_client.get('/api/map/search/status') + assert response.status_code == HTTPStatus.OK + assert [i['name'] for i in response.json['missing']] == ['usa.pmtiles'] + assert response.json['indexed'] == [] + + +def _place(name: str) -> tuple: + return name, 'locality', 45.0, -122.0, 5.0, 'test', 'city', 100, 'Oregon' + + +@pytest.mark.asyncio +async def test_search_sub_directory_index(async_client, test_directory, make_pmtiles): + """Places of a search index in a sub-directory are found.""" + pmtiles_file = make_pmtiles('map/regions/oregon.pmtiles') + _create_test_search_db(pmtiles_file.with_suffix('.search.db'), [_place('Subdirville')]) + + request, response = await async_client.get('/api/map/search?q=Subdirville') + assert response.status_code == HTTPStatus.OK + assert [i['name'] for i in response.json['results']] == ['Subdirville'] + + +@pytest.mark.asyncio +async def test_search_skips_ignored_file(async_client, test_directory, make_pmtiles): + """The places of an ignored map file are not found, and are found again once the file is visible.""" + pmtiles_file = make_pmtiles('map/regions/hidden.pmtiles') + _create_test_search_db(pmtiles_file.with_suffix('.search.db'), [_place('Hiddenville')]) + other = make_pmtiles('map/shown.pmtiles') + _create_test_search_db(other.with_suffix('.search.db'), [_place('Shownville')]) + + body = dict(map_path='regions/hidden.pmtiles', visible=False) + request, response = await async_client.post('/api/map/files/visible', json=body) + assert response.status_code == HTTPStatus.NO_CONTENT + + request, response = await async_client.get('/api/map/search?q=Hiddenville') + assert response.json['results'] == [] + # Only the ignored file is skipped. + request, response = await async_client.get('/api/map/search?q=Shownville') + assert [i['name'] for i in response.json['results']] == ['Shownville'] + + body = dict(map_path='regions/hidden.pmtiles', visible=True) + request, response = await async_client.post('/api/map/files/visible', json=body) + assert response.status_code == HTTPStatus.NO_CONTENT + request, response = await async_client.get('/api/map/search?q=Hiddenville') + assert [i['name'] for i in response.json['results']] == ['Hiddenville'] + + +def test_build_all_in_directory_selects_searchable_files(test_directory, make_pmtiles, monkeypatch): + """Building every index looks in sub-directories, and does not decode files it cannot index: unfinished + downloads, overlays, raster and terrain files.""" + make_pmtiles('map/usa.pmtiles') + make_pmtiles('map/regions/oregon.pmtiles') + make_pmtiles('map/.partial/idaho.pmtiles') + make_pmtiles('map/features.pmtiles', vector_metadata('power_lines')) + make_pmtiles('map/satellite.pmtiles', tile_type=2) + make_pmtiles('map/terrain-planet.pmtiles', tile_type=4) + + built = [] + monkeypatch.setattr(build_map_search, 'build_search_index', + lambda path, max_zoom=None: built.append(path.relative_to(test_directory / 'map').as_posix())) + build_map_search.build_all_in_directory(test_directory / 'map') + assert built == ['regions/oregon.pmtiles', 'usa.pmtiles'] diff --git a/wrolpi/common.py b/wrolpi/common.py index 321b5902..65b7422f 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -500,6 +500,7 @@ SYNCED_CONFIG_FILE_NAMES = frozenset({ 'download_manager.yaml', 'inventory/catalog.yaml', 'map_pins.yaml', + 'maps.yaml', 'playlists.yaml', 'tags.yaml', 'videos_downloader.yaml', @@ -1511,6 +1512,10 @@ def get_all_configs() -> Dict[str, ConfigFile]: if map_pins_config := get_map_pins_config(): all_configs[map_pins_config.file_name] = map_pins_config + from modules.map.config import get_maps_config + if maps_config := get_maps_config(): + all_configs[maps_config.file_name] = maps_config + from modules.flasher.config import get_flasher_config if flasher_config := get_flasher_config(): all_configs[flasher_config.file_name] = flasher_config @@ -1695,6 +1700,16 @@ async def import_all_db_configs() -> dict[str, bool]: logger.warning(f'Failed to import map pins config: {e}') results['map_pins'] = False + # Maps (YAML-only, no DB) + try: + from modules.map.config import get_maps_config + await asyncio.to_thread(get_maps_config().import_config) + results['maps'] = True + logger.debug('maps config imported') + except Exception as e: + logger.warning(f'Failed to import maps config: {e}') + results['maps'] = False + # Bookmarks (YAML-only, no DB) try: from wrolpi.bookmarks import get_bookmarks_config diff --git a/wrolpi/contexts.py b/wrolpi/contexts.py index 75715cdb..4397e85e 100644 --- a/wrolpi/contexts.py +++ b/wrolpi/contexts.py @@ -40,6 +40,7 @@ def attach_shared_contexts(app: Sanic): app.shared_ctx.archive_downloader_config = manager.dict() app.shared_ctx.download_cache_config = manager.dict() app.shared_ctx.map_pins_config = manager.dict() + app.shared_ctx.maps_config = manager.dict() app.shared_ctx.flasher_config = manager.dict() app.shared_ctx.bookmarks_config = manager.dict() app.shared_ctx.sync_config = manager.dict() @@ -347,6 +348,12 @@ def initialize_configs_contexts(app: Sanic): except Exception as e: logger.error(f'Failed to initialize in-memory map pins config: {e}') + try: + from modules.map.config import MAPS_CONFIG + MAPS_CONFIG.initialize(app.shared_ctx.maps_config) + except Exception as e: + logger.error(f'Failed to initialize in-memory maps config: {e}') + try: from modules.flasher.config import FLASHER_CONFIG FLASHER_CONFIG.initialize(app.shared_ctx.flasher_config) diff --git a/wrolpi/scripts/build_map_search.py b/wrolpi/scripts/build_map_search.py index f1035c3b..114dfe07 100755 --- a/wrolpi/scripts/build_map_search.py +++ b/wrolpi/scripts/build_map_search.py @@ -226,13 +226,29 @@ def build_search_index(pmtiles_path, output_path=None, max_zoom=DEFAULT_MAX_ZOOM return output_path +def _is_searchable(pmtiles_path): + """Whether the file has the layers a search index is built from; decoding a large file to find nothing is slow. + + This script also runs without WROLPi installed, then every file is tried.""" + project_root = str(Path(__file__).resolve().parent.parent.parent) + if project_root not in sys.path: + sys.path.insert(0, project_root) + try: + from modules.map.pmtiles import is_searchable + except ImportError: + return True + return is_searchable(pmtiles_path) + + def build_all_in_directory(directory, max_zoom=DEFAULT_MAX_ZOOM): """Build search indexes for all .pmtiles files in a directory. - Skips terrain files (which contain no place data). + Sub-directories are searched too, except hidden ones (unfinished downloads). Skips terrain files (which + contain no place data) and files without the layers the index is built from. """ directory = Path(directory).resolve() - pmtiles_files = sorted(directory.glob('*.pmtiles')) + pmtiles_files = sorted(p for p in directory.rglob('*.pmtiles') + if p.is_file() and not any(i.startswith('.') for i in p.relative_to(directory).parts)) if not pmtiles_files: print(f'No .pmtiles files found in {directory}') @@ -240,7 +256,7 @@ def build_all_in_directory(directory, max_zoom=DEFAULT_MAX_ZOOM): # Skip terrain and planet files. pmtiles_files = [p for p in pmtiles_files - if 'terrain' not in p.stem.lower() and not is_planet_file(p.name)] + if 'terrain' not in p.stem.lower() and not is_planet_file(p.name) and _is_searchable(p)] print(f'Found {len(pmtiles_files)} PMTiles files in {directory}') results = [] diff --git a/wrolpi/sync/lib.py b/wrolpi/sync/lib.py index e519e109..240210eb 100644 --- a/wrolpi/sync/lib.py +++ b/wrolpi/sync/lib.py @@ -510,6 +510,7 @@ SYNCED_CONFIG_IMPORTS = ( ('playlists.yaml', _import_playlists), ('zims.yaml', _import_zims), ('map_pins.yaml', _import_plain('map_pins.yaml')), + ('maps.yaml', _import_plain('maps.yaml')), ('bookmarks.yaml', _import_plain('bookmarks.yaml')), ('videos_downloader.yaml', _import_plain('videos_downloader.yaml')), ('archives_downloader.yaml', _import_plain('archives_downloader.yaml')),