mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-01 04:16:24 -05:00
A style beside a PMTiles overlay says how the map draws it (#963)
When a MapLibre style (and optionally a sprite sheet) sits beside a PMTiles file, the overlay is drawn with it instead of the generic colors: `<name>.style.json` and `<name>.sprite.json/.png`, or `style.json` and `sprite.json/.png` shared by the files of a directory. Only the style's layers which draw that file are used; its sources, sprite and glyph URLs never are. Fonts are replaced by the ones the map has, images are pointed at the overlay's own sprite (as strings, expressions or property functions), and each layer is validated so one the map could not draw is skipped instead of stopping the map. The sprite is served by the API, which falls back to the single resolution sheet when there is no double resolution one.
This commit is contained in:
parent
adb0adbd94
commit
4f58d2862f
12 changed files with 1003 additions and 12 deletions
|
|
@ -49,6 +49,19 @@ async def post_file_visible(_: Request, body: schema.MapFileVisibleRequest):
|
|||
return response.json({'error': 'File not found'}, HTTPStatus.NOT_FOUND)
|
||||
|
||||
|
||||
@map_bp.get('/files/sprite/<name:path>')
|
||||
@openapi.description("Get the sprite sheet beside a PMTiles map file: `<map file>[@2x].json` or `.png`")
|
||||
async def get_file_sprite(_: Request, name: str):
|
||||
try:
|
||||
sprite = lib.get_sidecar_sprite_file(name)
|
||||
except ValueError as e:
|
||||
return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST)
|
||||
|
||||
if sprite:
|
||||
return await response.file(sprite)
|
||||
return response.json({'error': 'Sprite not found'}, HTTPStatus.NOT_FOUND)
|
||||
|
||||
|
||||
@map_bp.get('/subscribe')
|
||||
@openapi.description('Get map catalog and current subscriptions')
|
||||
def get_subscriptions(request: Request):
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import json
|
||||
import re
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import List, Dict
|
||||
|
|
@ -41,6 +42,48 @@ def get_map_path(path: Path) -> str:
|
|||
return path.relative_to(get_map_directory()).as_posix()
|
||||
|
||||
|
||||
def find_sidecar_style(path: Path) -> Path | None:
|
||||
"""The MapLibre style a person put beside a PMTiles file to say how it is drawn: `<stem>.style.json`, else the
|
||||
`style.json` shared by the files of its directory."""
|
||||
for candidate in (path.with_suffix('.style.json'), path.parent / 'style.json'):
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def find_sidecar_sprite(path: Path, extension: str = 'json', high_resolution: bool = False) -> Path | None:
|
||||
"""The sprite sheet (the icons of a sidecar style) beside a PMTiles file: `<stem>.sprite.json` and
|
||||
`<stem>.sprite.png`, else the `sprite.json` and `sprite.png` shared by the files of its directory.
|
||||
|
||||
A sheet may also come at double resolution (`sprite@2x.json`, `sprite@2x.png`). The sheet of the other
|
||||
resolution is returned when the one asked for does not exist; a sprite file says its own pixel ratio."""
|
||||
for base in (path.with_suffix('.sprite'), path.parent / 'sprite'):
|
||||
resolutions = [i for i in ('', '@2x')
|
||||
if base.with_name(f'{base.name}{i}.json').is_file()
|
||||
and base.with_name(f'{base.name}{i}.png').is_file()]
|
||||
if resolutions:
|
||||
wanted = '@2x' if high_resolution else ''
|
||||
resolution = wanted if wanted in resolutions else resolutions[0]
|
||||
return base.with_name(f'{base.name}{resolution}.{extension}')
|
||||
return None
|
||||
|
||||
|
||||
SPRITE_NAME = re.compile(r'^(?P<filename>.+\.pmtiles)(?P<high_resolution>@2x)?\.(?P<extension>json|png)$')
|
||||
|
||||
|
||||
def get_sidecar_sprite_file(name: str) -> Path | None:
|
||||
"""The sprite file MapLibre asks for as `<map file>[@2x].(json|png)`, if that map file has a sprite.
|
||||
|
||||
Raises ValueError if the name is not such a name, or leads outside of the map directory."""
|
||||
match = SPRITE_NAME.match(name)
|
||||
if not match:
|
||||
raise ValueError(f'Invalid sprite name: {name}')
|
||||
path = _resolve_pmtiles_file(match.group('filename'))
|
||||
if not path:
|
||||
return None
|
||||
return find_sidecar_sprite(path, match.group('extension'), bool(match.group('high_resolution')))
|
||||
|
||||
|
||||
def get_pmtiles_files() -> List[dict]:
|
||||
"""Find all .pmtiles files in the map directory and return their metadata."""
|
||||
maps_config = get_maps_config()
|
||||
|
|
@ -49,6 +92,7 @@ def get_pmtiles_files() -> List[dict]:
|
|||
for path in iter_map_files('.pmtiles'):
|
||||
stat = path.stat()
|
||||
map_path = get_map_path(path)
|
||||
style = find_sidecar_style(path)
|
||||
files.append(dict(
|
||||
name=path.name,
|
||||
path=str(path.relative_to(get_media_directory())),
|
||||
|
|
@ -57,6 +101,8 @@ def get_pmtiles_files() -> List[dict]:
|
|||
mtime=stat.st_mtime,
|
||||
has_search_index=path.with_suffix('.search.db').is_file(),
|
||||
visible=not maps_config.is_ignored(map_path),
|
||||
style_path=str(style.relative_to(get_media_directory())) if style else None,
|
||||
has_sprite=find_sidecar_sprite(path) is not None,
|
||||
**pmtiles.describe(path),
|
||||
))
|
||||
|
||||
|
|
|
|||
|
|
@ -287,3 +287,56 @@ def test_maps_config_is_shared(async_client):
|
|||
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()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_file_sprite(async_client, test_directory, make_pmtiles):
|
||||
"""MapLibre asks for the sprite of a map file as `<map file>.json` and `.png`, and as `@2x` on a dense screen;
|
||||
it gets the single resolution sheet when that is all there is."""
|
||||
make_pmtiles('map/extras/features.pmtiles', vector_metadata('towers'))
|
||||
extras = test_directory / 'map/extras'
|
||||
(extras / 'sprite.json').write_text('{"tower": {"x": 0, "y": 0, "width": 8, "height": 8, "pixelRatio": 1}}')
|
||||
(extras / 'sprite.png').write_bytes(b'single')
|
||||
|
||||
request, response = await async_client.get('/api/map/files/sprite/extras/features.pmtiles.json')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['tower']['pixelRatio'] == 1
|
||||
request, response = await async_client.get('/api/map/files/sprite/extras/features.pmtiles.png')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.body == b'single'
|
||||
# There is no double resolution sheet.
|
||||
request, response = await async_client.get('/api/map/files/sprite/extras/features.pmtiles@2x.png')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.body == b'single'
|
||||
|
||||
(extras / 'sprite@2x.json').write_text('{"tower": {"x": 0, "y": 0, "width": 16, "height": 16, "pixelRatio": 2}}')
|
||||
(extras / 'sprite@2x.png').write_bytes(b'double')
|
||||
request, response = await async_client.get('/api/map/files/sprite/extras/features.pmtiles@2x.png')
|
||||
assert response.body == b'double'
|
||||
request, response = await async_client.get('/api/map/files/sprite/extras/features.pmtiles@2x.json')
|
||||
assert response.json['tower']['pixelRatio'] == 2
|
||||
request, response = await async_client.get('/api/map/files/sprite/extras/features.pmtiles.png')
|
||||
assert response.body == b'single'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_file_sprite_missing(async_client, test_directory, make_pmtiles):
|
||||
"""Only the sprite of a map file is served."""
|
||||
make_pmtiles('map/features.pmtiles', vector_metadata('towers'))
|
||||
(test_directory / 'secret.json').write_text('{"secret": true}')
|
||||
(test_directory / 'map/notes.json').write_text('{"notes": true}')
|
||||
|
||||
# The file has no sprite.
|
||||
request, response = await async_client.get('/api/map/files/sprite/features.pmtiles.json')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
# There is no such map file.
|
||||
request, response = await async_client.get('/api/map/files/sprite/missing.pmtiles.json')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
# Not the name of a sprite.
|
||||
for name in ('notes.json', 'features.pmtiles', 'features.pmtiles.txt', 'features.pmtiles@3x.png'):
|
||||
request, response = await async_client.get(f'/api/map/files/sprite/{name}')
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, name
|
||||
# Outside of the map directory.
|
||||
request, response = await async_client.get('/api/map/files/sprite/..%2Fsecret.pmtiles.json')
|
||||
assert response.status_code in (HTTPStatus.BAD_REQUEST, HTTPStatus.NOT_FOUND)
|
||||
assert b'secret' not in response.body or response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
|
|
|||
|
|
@ -261,3 +261,70 @@ def test_delete_pmtiles_file_forgets_ignored(async_client, test_directory, make_
|
|||
make_pmtiles('map/ignored-then-deleted.pmtiles')
|
||||
file, = lib.get_pmtiles_files()
|
||||
assert file['visible'] is True
|
||||
|
||||
|
||||
def _make_sprite(base, resolutions=('',)):
|
||||
"""Create sprite sheets (`<base>.json`, `<base>.png`); each says which it is."""
|
||||
for resolution in resolutions:
|
||||
base.with_name(f'{base.name}{resolution}.json').write_text(f'{{"sheet": "{base.name}{resolution}"}}')
|
||||
base.with_name(f'{base.name}{resolution}.png').write_bytes(f'{base.name}{resolution}'.encode())
|
||||
|
||||
|
||||
def test_sidecar_style(test_directory, make_pmtiles):
|
||||
"""A style beside a map file says how it is drawn: its own, else the one its directory shares."""
|
||||
own = make_pmtiles('map/extras/own.pmtiles', vector_metadata('towers'))
|
||||
shared = make_pmtiles('map/extras/shared.pmtiles', vector_metadata('towers'))
|
||||
elsewhere = make_pmtiles('map/elsewhere.pmtiles', vector_metadata('towers'))
|
||||
assert lib.find_sidecar_style(own) is None
|
||||
|
||||
(test_directory / 'map/extras/style.json').write_text('{}')
|
||||
(test_directory / 'map/extras/own.style.json').write_text('{}')
|
||||
assert lib.find_sidecar_style(own) == test_directory / 'map/extras/own.style.json'
|
||||
assert lib.find_sidecar_style(shared) == test_directory / 'map/extras/style.json'
|
||||
# A directory's style is not the style of the files in other directories.
|
||||
assert lib.find_sidecar_style(elsewhere) is None
|
||||
|
||||
files = {i['map_path']: i for i in lib.get_pmtiles_files()}
|
||||
assert files['extras/own.pmtiles']['style_path'] == 'map/extras/own.style.json'
|
||||
assert files['extras/shared.pmtiles']['style_path'] == 'map/extras/style.json'
|
||||
assert files['elsewhere.pmtiles']['style_path'] is None
|
||||
assert {i['has_sprite'] for i in files.values()} == {False}
|
||||
|
||||
|
||||
def test_sidecar_sprite(test_directory, make_pmtiles):
|
||||
"""A sprite sheet is a .json and a .png; a file's own is used before the one its directory shares."""
|
||||
own = make_pmtiles('map/extras/own.pmtiles', vector_metadata('towers'))
|
||||
shared = make_pmtiles('map/extras/shared.pmtiles', vector_metadata('towers'))
|
||||
extras = test_directory / 'map/extras'
|
||||
|
||||
# Half of a sheet is not a sheet.
|
||||
(extras / 'sprite.json').write_text('{}')
|
||||
assert lib.find_sidecar_sprite(shared) is None
|
||||
|
||||
_make_sprite(extras / 'sprite')
|
||||
_make_sprite(extras / 'own.sprite')
|
||||
assert lib.find_sidecar_sprite(shared, 'json') == extras / 'sprite.json'
|
||||
assert lib.find_sidecar_sprite(shared, 'png') == extras / 'sprite.png'
|
||||
assert lib.find_sidecar_sprite(own, 'png') == extras / 'own.sprite.png'
|
||||
|
||||
files = {i['map_path']: i['has_sprite'] for i in lib.get_pmtiles_files()}
|
||||
assert files == {'extras/own.pmtiles': True, 'extras/shared.pmtiles': True}
|
||||
|
||||
|
||||
def test_sidecar_sprite_resolution(test_directory, make_pmtiles):
|
||||
"""The sheet of the other resolution is used when the one asked for does not exist."""
|
||||
path = make_pmtiles('map/extras/features.pmtiles', vector_metadata('towers'))
|
||||
extras = test_directory / 'map/extras'
|
||||
|
||||
_make_sprite(extras / 'sprite')
|
||||
assert lib.find_sidecar_sprite(path, 'png', high_resolution=True) == extras / 'sprite.png'
|
||||
|
||||
_make_sprite(extras / 'sprite', ('@2x',))
|
||||
assert lib.find_sidecar_sprite(path, 'png', high_resolution=True) == extras / 'sprite@2x.png'
|
||||
assert lib.find_sidecar_sprite(path, 'json', high_resolution=True) == extras / 'sprite@2x.json'
|
||||
assert lib.find_sidecar_sprite(path, 'png') == extras / 'sprite.png'
|
||||
|
||||
# Only the double resolution sheet exists.
|
||||
(extras / 'sprite.json').unlink()
|
||||
assert lib.find_sidecar_sprite(path, 'png') == extras / 'sprite@2x.png'
|
||||
assert lib.find_sidecar_sprite(path, 'json') == extras / 'sprite@2x.json'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue