feat(gui): offline basemap under the Places map

Places now draws the proton-map-rs basemap that Proton Gallery uses: seas by
depth, lakes, rivers, built-up areas, borders and town names, in light and
dark. Tiles render on two worker threads into the existing tile layer, so
caching, ancestor stand-ins and density restarts work as before. Opening
Places sends no request.

The OpenFreeMap street map stays opt-in and replaces the basemap while it
is turned on. Without the basemap file the map falls back to the coarse
Natural Earth outlines.

scripts/fetch-basemap.sh downloads basemap-v1.pmtiles and checks it against
a pinned SHA-256. The deb, rpm, tarball, local and AUR PKGBUILDs, COPR spec
and Nix package install it to /usr/share/proton-drive-linux. PDFS_BASEMAP
points the app at another copy.

The new credit and preference text is translated in every catalog.
This commit is contained in:
nvrl committed 2026-11-22 00:44:14 +01:00
1 parent 7be4c7db1e
commit 795dd7edb0
34 files changed
+753 -292

No files matched your search

+6
View File
@@ -23,6 +23,8 @@ path = "src/prompt.rs"
[dependencies]
proton-gallery-rs.workspace = true
# The offline basemap under the Places map.
proton-map-rs.workspace = true
base64.workspace = true
pdfs-core.workspace = true
tracing.workspace = true
@@ -43,3 +45,7 @@ pangocairo = "0.22"
reqwest = { version = "0.13", default-features = false, features = ["rustls", "webpki-roots"] }
# The system libintl (glibc) rather than a bundled gettext build.
gettext-rs = { version = "0.8", features = ["gettext-system"] }
[dev-dependencies]
# Builds small basemaps for the map tests.
proton-map-rs = { workspace = true, features = ["writer"] }
+1 -1
View File
@@ -1476,7 +1476,7 @@ fn install_window_actions(ui: &Rc<Ui>, window: &adw::ApplicationWindow) {
None,
gtk4::License::Custom,
Some(&gettext(
"The places map is drawn from <a href=\"https://www.naturalearthdata.com/\">Natural Earth</a> land outlines and country borders, which are in the public domain.",
"The places map is drawn from <a href=\"https://www.naturalearthdata.com/\">Natural Earth</a> land, water and borders, which are in the public domain.",
)),
);
dialog.add_legal_section(
+211 -22
View File
@@ -1,7 +1,12 @@
//! The online street map under the Places map: vector tiles from OpenFreeMap,
//! fetched and drawn on a worker thread, and handed to the map as finished
//! images.
//! The tiles under the Places map, made on worker threads and handed to the
//! map as finished images. They come from one of two sources.
//!
//! The offline basemap is a PMTiles file installed with the app and drawn by
//! `proton-map-rs`, the same map Proton Gallery shows: seas, lakes, rivers,
//! built-up areas, borders and town names from Natural Earth and GeoNames.
//! It sends nothing anywhere. Its names are drawn into the tiles.
//!
//! The online street map is vector tiles from OpenFreeMap.
//! It is off unless turned on in Preferences, since every tile fetched tells
//! OpenFreeMap which part of the world is being looked at. OpenFreeMap needs
//! no account or key, and its tiles are OpenStreetMap data in the
@@ -20,9 +25,17 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use gtk4::cairo;
use proton_map::{Basemap, Style, TileId};
use super::mvt::{self, Kind, Layer};
/// The basemap's file name, wherever it is installed.
pub(crate) const BASEMAP_FILE: &str = "basemap-v1.pmtiles";
/// How many threads draw basemap tiles. Drawing is all CPU; two keep the map
/// quick without taking the machine.
const BASEMAP_THREADS: usize = 2;
/// Where OpenFreeMap describes its current tile set.
const TILEJSON_URL: &str = "https://tiles.openfreemap.org/planet";
@@ -254,8 +267,20 @@ struct Job {
dark: bool,
}
/// The worker thread making tiles. Dropping it stops the thread once the
/// fetches under way are done.
/// Where a tile worker gets its tiles.
pub(crate) enum Source {
/// OpenFreeMap's street map, cached under `cache_dir`, with names in
/// `language` where the map has them.
Online {
cache_dir: PathBuf,
language: String,
},
/// The basemap installed at this path.
Offline(PathBuf),
}
/// The worker threads making tiles. Dropping it stops them once the tiles
/// under way are done.
pub(crate) struct Tiles {
jobs: async_channel::Sender<Job>,
wanted: Arc<Mutex<HashSet<TileKey>>>,
@@ -264,27 +289,35 @@ pub(crate) struct Tiles {
}
impl Tiles {
/// Start the worker, caching under `cache_dir`, drawing names in
/// `language` where the map has them. Finished tiles arrive on the
/// returned channel.
pub(crate) fn start(
cache_dir: PathBuf,
language: String,
scale: i32,
) -> (Self, async_channel::Receiver<Done>) {
/// Start the worker for `source`. Finished tiles arrive on the returned
/// channel.
pub(crate) fn start(source: Source, scale: i32) -> (Self, async_channel::Receiver<Done>) {
let (jobs, job_rx) = async_channel::unbounded();
let (done_tx, done_rx) = async_channel::unbounded();
let wanted = Arc::new(Mutex::new(HashSet::new()));
let worker = Worker {
dir: cache_dir,
language,
scale,
wanted: wanted.clone(),
done: done_tx,
let spawned = match source {
Source::Online {
cache_dir,
language,
} => {
let worker = Worker {
dir: cache_dir,
language,
scale,
wanted: wanted.clone(),
done: done_tx,
};
std::thread::Builder::new()
.name("map-tiles".into())
.spawn(move || worker.run(job_rx))
}
Source::Offline(path) => {
let wanted = wanted.clone();
std::thread::Builder::new()
.name("map-basemap".into())
.spawn(move || draw_basemap(&path, scale, &wanted, &job_rx, &done_tx))
}
};
let spawned = std::thread::Builder::new()
.name("map-tiles".into())
.spawn(move || worker.run(job_rx));
if let Err(e) = spawned {
tracing::warn!("map tiles: cannot start the worker: {e}");
}
@@ -463,6 +496,126 @@ impl Worker {
}
}
/// Where the basemap may be installed, most specific first.
fn basemap_paths() -> Vec<PathBuf> {
let mut paths = Vec::new();
if let Some(path) = std::env::var_os("PDFS_BASEMAP") {
paths.push(PathBuf::from(path));
}
if let Some(dir) = std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(Path::to_path_buf))
{
paths.push(dir.join("../share/proton-drive-linux").join(BASEMAP_FILE));
}
paths.push(Path::new("/usr/share/proton-drive-linux").join(BASEMAP_FILE));
if let Some(dir) = std::env::var_os("XDG_DATA_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|home| Path::new(&home).join(".local/share")))
{
paths.push(dir.join("proton-drive-linux").join(BASEMAP_FILE));
}
if cfg!(debug_assertions) {
// `scripts/fetch-basemap.sh` puts it here for development builds.
paths
.push(Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../data")).join(BASEMAP_FILE));
}
paths
}
/// The installed basemap's path, if there is one.
pub(crate) fn find_basemap() -> Option<PathBuf> {
basemap_paths().into_iter().find(|path| path.is_file())
}
/// The basemap, read once per run: the map restarts its worker when the
/// window moves to a screen of another density, and the file is 25 MB.
fn open_basemap(path: &Path) -> Option<Arc<Basemap>> {
static OPENED: Mutex<Option<(PathBuf, Arc<Basemap>)>> = Mutex::new(None);
let mut opened = OPENED.lock().ok()?;
if let Some((at, basemap)) = opened.as_ref()
&& at == path
{
return Some(basemap.clone());
}
match Basemap::open(path) {
Ok(basemap) => {
let basemap = Arc::new(basemap);
*opened = Some((path.to_path_buf(), basemap.clone()));
Some(basemap)
}
Err(e) => {
tracing::warn!("map tiles: cannot open the basemap: {e}");
None
}
}
}
/// Open the basemap at `path` and draw the tiles asked for on
/// [`BASEMAP_THREADS`] threads until the map lets go of the worker. Without
/// a readable basemap every tile fails, and the outline shows.
fn draw_basemap(
path: &Path,
scale: i32,
wanted: &Mutex<HashSet<TileKey>>,
jobs: &async_channel::Receiver<Job>,
done: &async_channel::Sender<Done>,
) {
let basemap = open_basemap(path);
std::thread::scope(|scope| {
for _ in 0..BASEMAP_THREADS {
let basemap = basemap.clone();
scope.spawn(move || {
while let Ok(job) = jobs.recv_blocking() {
let key = job.key;
let still_wanted = wanted.lock().map(|w| w.contains(&key)).unwrap_or(true);
let result = match &basemap {
_ if !still_wanted => Done::Dropped(key),
Some(basemap) => Done::Tile(draw_basemap_tile(basemap, job, scale)),
None => Done::Failed(key),
};
if done.send_blocking(result).is_err() {
break;
}
}
});
}
});
}
/// One basemap tile at `scale` device px per logical px.
fn draw_basemap_tile(basemap: &Basemap, job: Job, scale: i32) -> Raster {
let style = if job.dark {
Style::dark()
} else {
Style::light()
};
let key = job.key;
let tile = proton_map::render_tile(
basemap,
TileId::new(key.z, key.x, key.y),
scale.max(1) as f32,
&style,
);
Raster {
key,
dark: job.dark,
edge: tile.width as i32,
pixels: rgba_to_cairo(tile.rgba),
labels: Vec::new(),
}
}
/// Premultiplied RGBA bytes to cairo's premultiplied ARGB, one native-endian
/// word per pixel.
fn rgba_to_cairo(mut pixels: Vec<u8>) -> Vec<u8> {
for px in pixels.as_chunks_mut::<4>().0 {
let [r, g, b, a] = *px;
*px = u32::from_be_bytes([a, r, g, b]).to_ne_bytes();
}
pixels
}
/// The first tile URL template in a TileJSON document.
fn tile_template(json: &[u8]) -> Option<String> {
let doc: serde_json::Value = serde_json::from_slice(json).ok()?;
@@ -823,6 +976,42 @@ fn label_name(layer: &Layer, feature: &mvt::Feature, language: &str) -> Option<S
mod tests {
use super::*;
fn empty_basemap() -> Basemap {
Basemap::from_bytes(proton_map::pmtiles::writer::Writer::new().finish(
"{}",
[-180.0, -85.0, 180.0, 85.0],
[0.0, 0.0],
))
.expect("empty archive opens")
}
#[test]
fn rgba_pixels_become_cairo_words() {
let pixels = rgba_to_cairo(vec![0x11, 0x22, 0x33, 0xff]);
let word = u32::from_ne_bytes(pixels.try_into().expect("one pixel"));
assert_eq!(word, 0xff11_2233);
}
#[test]
fn basemap_tiles_come_at_the_screen_density_in_the_theme_asked() {
let basemap = empty_basemap();
let key = TileKey { z: 3, x: 4, y: 2 };
for dark in [false, true] {
let raster = draw_basemap_tile(&basemap, Job { key, dark }, 2);
assert_eq!((raster.key, raster.dark), (key, dark));
assert_eq!(raster.edge, 512);
assert_eq!(raster.pixels.len(), 512 * 512 * 4);
// An empty basemap is all open sea.
let sea = if dark { Style::dark() } else { Style::light() }.water[0];
let word = u32::from_ne_bytes(raster.pixels[..4].try_into().expect("a pixel"));
assert_eq!(
word & 0x00ff_ffff,
u32::from_be_bytes([0, sea.r, sea.g, sea.b])
);
assert!(raster.surface().is_some());
}
}
#[test]
fn deep_tiles_draw_from_their_ancestor_at_the_data_zoom() {
let key = TileKey {
+104 -62
View File
@@ -2,13 +2,13 @@
//! their newest photo, and once the map is zoomed in close, each photo where
//! it was taken.
//!
//! Underneath is one of two maps. The built-in one is drawn here from Natural
//! Underneath are up to two maps. The outline is drawn here from Natural
//! Earth's 1:50m land polygons and country borders (public domain), trimmed
//! into `data/land.txt` and `data/borders.txt` by
//! `scripts/natural-earth-land.py`; it needs no network and tells nobody
//! anything. The street map from OpenFreeMap ([`super::map_tiles`]) is
//! opt-in, in Preferences, and draws over the built-in one wherever its tiles
//! have arrived.
//! `scripts/natural-earth-land.py`, and is always there. Over it go tiles
//! ([`super::map_tiles`]) wherever they have arrived: the offline basemap
//! installed with the app, which needs no network and tells nobody anything,
//! or, when turned on in Preferences, the street map from OpenFreeMap.
//!
//! The projection is Web Mercator, the one every other map uses, so the
//! world looks the way people expect. Markers that would overlap on screen
@@ -27,7 +27,7 @@ use std::time::{Duration, Instant};
use gtk4::cairo;
use pdfs_core::control::PhotoLocation;
use super::map_tiles::{self, Done, Label, LabelClass, Palette, TILE_EDGE, TileKey, Tiles};
use super::map_tiles::{self, Done, Label, LabelClass, Palette, Source, TILE_EDGE, TileKey, Tiles};
use crate::*;
const LAND: &str = include_str!("../../../data/land.txt");
@@ -37,8 +37,8 @@ const BORDERS: &str = include_str!("../../../data/borders.txt");
const MAX_LATITUDE: f64 = 85.0;
/// How far in the map zooms, as a multiple of the whole world fitting the
/// widget: far enough for photos in one town to part on the built-in map,
/// and down to single streets on the street map.
/// widget: far enough for photos in one town to part on the outline and the
/// basemap, and down to single streets on the street map.
const MAX_ZOOM: f64 = 8192.0;
const ONLINE_MAX_ZOOM: f64 = 65536.0;
@@ -66,7 +66,7 @@ const MIN_SEGMENT: f64 = 0.75;
/// Edge in px of the square a marker's photo is scaled down to once.
const COVER_PX: i32 = 128;
/// How many street-map tiles stay in memory.
/// How many map tiles stay in memory.
const TILE_CACHE: usize = 160;
/// Photo marker covers kept, 64 KiB each. A town's own cover is never
@@ -190,7 +190,7 @@ struct Marker {
target: Target,
}
/// A street-map tile ready to draw, and the names on it.
/// A map tile ready to draw, and the names on it.
struct CachedTile {
surface: cairo::ImageSurface,
labels: Rc<Vec<Label>>,
@@ -198,9 +198,11 @@ struct CachedTile {
used: u64,
}
/// The street map, while it is turned on.
struct Online {
/// The tiles drawn over the outline, from the basemap or the street map.
struct TileLayer {
tiles: Tiles,
/// Whether they come from the street map.
online: bool,
cache: HashMap<TileKey, CachedTile>,
pending: HashSet<TileKey>,
failed: HashMap<TileKey, Instant>,
@@ -239,7 +241,11 @@ struct MapState {
drag_origin: Option<View>,
/// The scale a pinch started from.
pinch_origin: Option<View>,
online: Option<Online>,
tiles: Option<TileLayer>,
/// Whether the street map is turned on in Preferences.
street_map: bool,
/// The installed basemap, if any.
basemap: Option<PathBuf>,
cache_dir: Option<PathBuf>,
/// The spot [`PlacesMap::show_spot`] went to, ringed until the map is
/// fitted to all places again.
@@ -295,32 +301,11 @@ impl PlacesMap {
buttons.append(&zoom);
buttons.append(&fit);
let link = |url: &str, name: &str| format!("<a href=\"{url}\">{name}</a>");
let credit = gtk4::Label::builder()
.use_markup(true)
.halign(gtk4::Align::End)
.valign(gtk4::Align::End)
.visible(false)
.label(gettext_f(
// Translators: the credit on the street map. {openfreemap},
// {openmaptiles} and {openstreetmap} are the linked names of
// the projects, which stay as they are.
"{openfreemap} © {openmaptiles} Data from {openstreetmap}",
&[
(
"openfreemap",
&link("https://openfreemap.org", "OpenFreeMap"),
),
(
"openmaptiles",
&link("https://www.openmaptiles.org/", "OpenMapTiles"),
),
(
"openstreetmap",
&link("https://www.openstreetmap.org/copyright", "OpenStreetMap"),
),
],
))
.build();
credit.add_css_class("places-map-credit");
credit.add_css_class("caption");
@@ -354,7 +339,9 @@ impl PlacesMap {
pointer: (0.0, 0.0),
drag_origin: None,
pinch_origin: None,
online: None,
tiles: None,
street_map: false,
basemap: map_tiles::find_basemap(),
cache_dir: None,
pin: None,
}),
@@ -494,39 +481,53 @@ impl PlacesMap {
self.area.queue_draw();
}
/// Draw OpenFreeMap's street map under the markers, or stop, keeping its
/// tiles in `cache_dir`.
/// Draw OpenFreeMap's street map under the markers, keeping its tiles in
/// `cache_dir`, or else the installed basemap.
pub(crate) fn set_online(self: &Rc<Self>, on: bool, cache_dir: PathBuf) {
{
let mut state = self.state.borrow_mut();
state.cache_dir = Some(cache_dir);
if on == state.online.is_some() {
let started = state.tiles.is_some() || state.basemap.is_none();
if on == state.street_map && started {
return;
}
state.online = None;
}
self.credit.set_visible(on);
if on {
self.start_tiles();
state.street_map = on;
state.tiles = None;
}
self.start_tiles();
self.clamp_zoom();
self.area.queue_draw();
}
/// Start a tile worker for the widget's current pixel density.
/// Start a tile worker for the widget's current pixel density, and show
/// the credit for what it draws.
fn start_tiles(self: &Rc<Self>) {
let Some(dir) = self.state.borrow().cache_dir.clone() else {
let source = {
let state = self.state.borrow();
match (&state.cache_dir, &state.basemap) {
(Some(dir), _) if state.street_map => {
let language = gtk4::pango::Language::default().to_string();
let language = language.split(['-', '_']).next().unwrap_or("en").to_owned();
Some(Source::Online {
cache_dir: dir.join("map-tiles"),
language,
})
}
(_, Some(basemap)) => Some(Source::Offline(basemap.clone())),
_ => None,
}
};
let Some(source) = source else {
self.credit.set_visible(false);
return;
};
let language = gtk4::pango::Language::default().to_string();
let language = language.split(['-', '_']).next().unwrap_or("en").to_owned();
let (tiles, done) = Tiles::start(
dir.join("map-tiles"),
language,
self.area.scale_factor().max(1),
);
self.state.borrow_mut().online = Some(Online {
let online = matches!(source, Source::Online { .. });
self.credit.set_label(&credit_text(online));
self.credit.set_visible(true);
let (tiles, done) = Tiles::start(source, self.area.scale_factor().max(1));
self.state.borrow_mut().tiles = Some(TileLayer {
tiles,
online,
cache: HashMap::new(),
pending: HashSet::new(),
failed: HashMap::new(),
@@ -546,7 +547,7 @@ impl PlacesMap {
fn tile_done(&self, done: Done) {
let mut state = self.state.borrow_mut();
let Some(online) = state.online.as_mut() else {
let Some(online) = state.tiles.as_mut() else {
return;
};
match done {
@@ -732,7 +733,7 @@ impl PlacesMap {
}
fn max_scale(&self) -> f64 {
let zoom = if self.state.borrow().online.is_some() {
let zoom = if self.state.borrow().tiles.as_ref().is_some_and(|t| t.online) {
ONLINE_MAX_ZOOM
} else {
MAX_ZOOM
@@ -827,11 +828,11 @@ impl PlacesMap {
let restart = self
.state
.borrow()
.online
.tiles
.as_ref()
.is_some_and(|o| o.tiles.scale != area.scale_factor().max(1));
if restart {
self.state.borrow_mut().online = None;
self.state.borrow_mut().tiles = None;
self.start_tiles();
}
@@ -846,7 +847,7 @@ impl PlacesMap {
let view = state.view;
state.draws += 1;
paint_outline(cr, view, size, colors);
let labels = match state.online.as_mut() {
let labels = match state.tiles.as_mut() {
Some(online) => paint_tiles(cr, online, view, size, dark, area.scale_factor()),
None => Vec::new(),
};
@@ -999,16 +1000,16 @@ fn paint_outline(cr: &cairo::Context, view: View, size: (f64, f64), colors: &Pal
let _ = cr.stroke();
}
/// The street-map zoom whose tiles come closest to their own size on screen.
/// The tile zoom whose tiles come closest to their own size on screen.
fn tile_zoom(scale: f64) -> u8 {
(scale / TILE_EDGE).log2().round().clamp(0.0, 18.0) as u8
}
/// Draw the street-map tiles on screen, asking for the missing ones and
/// standing in their nearest ancestor meanwhile. Returns the names on them.
/// Draw the map tiles on screen, asking for the missing ones and standing in
/// their nearest ancestor meanwhile. Returns the names on them.
fn paint_tiles(
cr: &cairo::Context,
online: &mut Online,
online: &mut TileLayer,
view: View,
size: (f64, f64),
dark: bool,
@@ -1565,6 +1566,47 @@ impl PlacesMap {
/// How many town names a merged marker's tooltip lists.
const TOOLTIP_NAMES: usize = 5;
/// The credit for the map's tiles, as Pango markup.
fn credit_text(online: bool) -> String {
let link = |url: &str, name: &str| format!("<a href=\"{url}\">{name}</a>");
if online {
gettext_f(
// Translators: the credit on the street map. {openfreemap},
// {openmaptiles} and {openstreetmap} are the linked names of
// the projects, which stay as they are.
"{openfreemap} © {openmaptiles} Data from {openstreetmap}",
&[
(
"openfreemap",
&link("https://openfreemap.org", "OpenFreeMap"),
),
(
"openmaptiles",
&link("https://www.openmaptiles.org/", "OpenMapTiles"),
),
(
"openstreetmap",
&link("https://www.openstreetmap.org/copyright", "OpenStreetMap"),
),
],
)
} else {
gettext_f(
// Translators: the credit on the offline map. {naturalearth} and
// {geonames} are the linked names of the projects, which stay as
// they are.
"Map data © {naturalearth} (public domain) and {geonames} (CC BY 4.0)",
&[
(
"naturalearth",
&link("https://www.naturalearthdata.com/", "Natural Earth"),
),
("geonames", &link("https://www.geonames.org/", "GeoNames")),
],
)
}
}
fn map_button(icon: &str, tooltip: &str) -> gtk4::Button {
let button = gtk4::Button::from_icon_name(icon);
button.set_tooltip_text(Some(tooltip));
+1 -1
View File
@@ -245,7 +245,7 @@ pub(crate) fn build_main_page() -> MainWidgets {
let online_map_row = adw::SwitchRow::builder()
.title(gettext("Street map for Places"))
.subtitle(gettext(
"Show streets and town names from OpenFreeMap. It learns which parts of the world you look at.",
"Show streets from OpenFreeMap instead of the offline map. It learns which parts of the world you look at.",
))
.build();
appearance_group.add(&online_map_row);