feat(core,fuse,gui): Proton theme, photos on the map and an opt-in street map

- The Proton accent preference becomes a whole Proton theme that also
  holds against a GTK theme imported from gtk.css; folders get Proton's
  purple folder icon while it is on.
- Places map markers show one of each town's photos with a count, and
  zoomed in on a town every photo sits where it was taken
  (Request::PlaceLocations). Photos taken on one spot are listed in a
  popover. "Show on map" in the photo viewer goes to the Places map.
- The built-in map draws country borders, sea and land in their own
  colours.
- An opt-in street map from OpenFreeMap (vector tiles drawn with cairo,
  cached on disk up to 256 MB), with the OpenStreetMap credit on the map
  and in About.
- Translations for all catalogs; changelog folded into 2.3.0.
This commit is contained in:
nvrl committed 2026-09-28 03:12:57 +02:00
1 parent 4fd14eb745
commit fde9c2d271
37 files changed
+5846 -2214

No files matched your search

+112 -21
View File
@@ -69,10 +69,6 @@ use pdfs_core::service;
const APP_ID: &str = "io.narl.proton-drive-linux";
/// Proton brand purple, applied as the libadwaita accent when the user opts in
/// (Preferences → Appearance), so switches, buttons and links all pick it up.
const PROTON_PURPLE: &str = "#6d4aff";
/// How often the window re-reads mount status, cache usage and the pin list.
const REFRESH_INTERVAL: Duration = Duration::from_secs(2);
@@ -213,7 +209,7 @@ fn main() -> glib::ExitCode {
app.connect_startup(|_| {
load_proton_theme();
if let Ok(dirs) = AppDirs::new() {
set_proton_accent(dirs.load_config().proton_accent.unwrap_or(false));
set_proton_theme(dirs.load_config().proton_theme.unwrap_or(false));
}
// Refresh the file manager's right-click pin/unpin scripts, so they always
// match the installed `pdfs`.
@@ -289,8 +285,8 @@ pub(crate) fn spawn_tray() {
}
/// Register the bundled GResources (custom icons, the stylesheet) and load the
/// app stylesheet. The Proton accent is a separate provider, applied by
/// [`set_proton_accent`] from the saved preference.
/// app stylesheet. The Proton theme is a separate provider, applied by
/// [`set_proton_theme`] from the saved preference.
fn load_proton_theme() {
let bytes = include_bytes!(concat!(env!("OUT_DIR"), "/pdfs.gresource"));
let resource_data = glib::Bytes::from_static(bytes);
@@ -309,38 +305,124 @@ fn load_proton_theme() {
// `button { padding: 6px 10px; min-width: 16px }` would otherwise pad every
// photo tile and push the grid past the window. Every rule in the sheet is
// scoped to the app's own classes, so nothing else the user styled changes.
// One above the Proton theme too, so the app's rules refine it.
gtk4::style_context_add_provider_for_display(
&display,
&provider,
gtk4::STYLE_PROVIDER_PRIORITY_USER + 1,
gtk4::STYLE_PROVIDER_PRIORITY_USER + 2,
);
gtk4::IconTheme::for_display(&display).add_resource_path("/de/nils/protondrivelinux/icons");
}
thread_local! {
/// The Proton purple accent provider while it is installed. Kept so turning
/// the preference off can remove exactly what turning it on added.
static PROTON_ACCENT: RefCell<Option<gtk4::CssProvider>> = const { RefCell::new(None) };
/// The Proton theme provider while it is installed. Kept so turning the
/// preference off can remove exactly what turning it on added.
static PROTON_THEME: RefCell<Option<gtk4::CssProvider>> = const { RefCell::new(None) };
}
/// Paint the app in Proton purple (`on`) or follow the system accent colour.
/// Every accent-coloured widget reads `--accent-bg-color`, so overriding that
/// one variable recolours the whole app.
fn set_proton_accent(on: bool) {
/// Whether the Proton theme is on.
fn proton_theme_active() -> bool {
PROTON_THEME.with(|slot| slot.borrow().is_some())
}
/// libadwaita's own stylesheet, bundled in the library.
const ADWAITA_STYLESHEET: &str = "/org/gnome/Adwaita/styles/gtk.css";
/// The Proton palette laid over it, from our own bundle.
const PROTON_PALETTE: &str = "/de/nils/protondrivelinux/proton-theme.css";
/// Make the theme provider's `@media (prefers-color-scheme)` and
/// `(prefers-contrast)` rules match what libadwaita shows, now and whenever it
/// changes. A provider evaluates those itself, and a new one assumes light.
///
/// The properties are set by name because they only exist since GTK 4.20, and
/// the app still runs on older GTK, whose libadwaita has no such rules anyway.
fn follow_style_manager(provider: &gtk4::CssProvider) {
fn set_enum(provider: &gtk4::CssProvider, property: &str, nick: &str) {
let Some(pspec) = provider.find_property(property) else {
return;
};
if let Some(value) = glib::EnumClass::with_type(pspec.value_type())
.and_then(|class| class.to_value_by_nick(nick))
{
provider.set_property_from_value(property, &value);
}
}
fn apply(provider: &gtk4::CssProvider, manager: &adw::StyleManager) {
let scheme = if manager.is_dark() { "dark" } else { "light" };
set_enum(provider, "prefers-color-scheme", scheme);
let contrast = if manager.is_high_contrast() {
"more"
} else {
"no-preference"
};
set_enum(provider, "prefers-contrast", contrast);
}
let manager = adw::StyleManager::default();
apply(provider, &manager);
// Weak, so a provider the preference removed isn't kept alive; its
// handlers then do nothing.
let weak = provider.downgrade();
let weak_dark = weak.clone();
manager.connect_dark_notify(move |manager| {
if let Some(provider) = weak_dark.upgrade() {
apply(&provider, manager);
}
});
manager.connect_high_contrast_notify(move |manager| {
if let Some(provider) = weak.upgrade() {
apply(&provider, manager);
}
});
}
/// Paint the app in the Proton web apps' colours (`on`) or follow the system
/// theme and accent colour.
///
/// Setting libadwaita's colour variables alone isn't enough: a GTK theme the
/// user's `gtk.css` imports (Catppuccin, Fluent, ...) sits above the app and
/// hard-codes its own accent into hundreds of rules. So the theme provider,
/// one above the user's CSS, first resets every property, then re-applies
/// libadwaita's whole stylesheet and finally the Proton palette, which leaves
/// nothing of the user's theme inside the app.
fn set_proton_theme(on: bool) {
let Some(display) = gtk4::gdk::Display::default() else {
return;
};
PROTON_ACCENT.with(|slot| {
PROTON_THEME.with(|slot| {
let mut slot = slot.borrow_mut();
match (on, slot.as_ref()) {
(true, None) => {
let stylesheet = |path| {
gio::resources_lookup_data(path, gio::ResourceLookupFlags::NONE)
.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
};
let palette = stylesheet(PROTON_PALETTE).unwrap_or_default();
let css = match stylesheet(ADWAITA_STYLESHEET) {
// Its images are named relative to the sheet, which a
// string loaded here doesn't have.
Ok(adwaita) => format!(
"* {{ all: unset; }}\n{}\n{palette}",
adwaita.replace(
"url(\"assets/",
"url(\"resource:///org/gnome/Adwaita/styles/assets/"
)
),
// Still recolours everything that follows libadwaita's
// variables; only a custom theme's own rules show through.
Err(e) => {
tracing::warn!("libadwaita stylesheet not found, only recolouring: {e}");
palette
}
};
let provider = gtk4::CssProvider::new();
provider
.load_from_string(&format!(":root {{ --accent-bg-color: {PROTON_PURPLE}; }}"));
follow_style_manager(&provider);
provider.load_from_string(&css);
gtk4::style_context_add_provider_for_display(
&display,
&provider,
gtk4::STYLE_PROVIDER_PRIORITY_APPLICATION + 1,
gtk4::STYLE_PROVIDER_PRIORITY_USER + 1,
);
*slot = Some(provider);
}
@@ -454,7 +536,8 @@ fn build_window(app: &adw::Application) {
upload_limit_row: main_widgets.upload_limit_row.clone(),
download_limit_row: main_widgets.download_limit_row.clone(),
mountpoint_row: main_widgets.mountpoint_row.clone(),
accent_row: main_widgets.accent_row.clone(),
theme_row: main_widgets.theme_row.clone(),
online_map_row: main_widgets.online_map_row.clone(),
tray_row: main_widgets.tray_row.clone(),
language_row: main_widgets.language_row.clone(),
settings_suppress: Cell::new(false),
@@ -1368,7 +1451,15 @@ 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, which are in the public domain.",
"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.",
)),
);
dialog.add_legal_section(
"OpenStreetMap",
None,
gtk4::License::Custom,
Some(&gettext(
"The street map, when turned on, comes from <a href=\"https://openfreemap.org/\">OpenFreeMap</a> in the <a href=\"https://www.openmaptiles.org/\">OpenMapTiles</a> schema. Map data © <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors, available under the Open Database License.",
)),
);
dialog.add_legal_section(
+9
View File
@@ -2797,6 +2797,15 @@ pub(crate) fn attach_drop(ui: &Rc<Ui>, item: &gtk4::ListItem, anchor: &gtk4::Box
anchor.add_controller(target);
}
/// The full-colour icon for an entry: [`icon_base_for`], except that folders
/// are Proton's own purple ones while the Proton theme is on.
pub(crate) fn icon_for(entry: &DirEntry) -> &'static str {
if entry.is_dir && proton_theme_active() {
return "pdfs-proton-folder";
}
icon_base_for(entry)
}
/// Pick a freedesktop icon base name for an entry from its kind / extension.
/// Callers append `-symbolic` for the column view's small icons.
pub(crate) fn icon_base_for(entry: &DirEntry) -> &'static str {
+877
View File
@@ -0,0 +1,877 @@
//! 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.
//!
//! 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
//! OpenMapTiles schema; both have to be credited wherever the map shows.
//!
//! Tiles are kept on disk under the cache directory, per build of the tile
//! set. A build never changes, so a cached tile is good until OpenFreeMap
//! publishes the next one, and then the old build's directory goes. Town and
//! country names are not baked into the images: they come back as [`Label`]s
//! for the map to set on top, where it can keep them upright, sharp and apart
//! from each other.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use gtk4::cairo;
use super::mvt::{self, Kind, Layer};
/// Where OpenFreeMap describes its current tile set.
const TILEJSON_URL: &str = "https://tiles.openfreemap.org/planet";
/// The deepest zoom OpenFreeMap has tiles for. Closer in, a tile is drawn
/// from part of its ancestor at this zoom.
pub(crate) const DATA_MAX_ZOOM: u8 = 14;
/// A tile's edge in logical px at the zoom it was made for.
pub(crate) const TILE_EDGE: f64 = 256.0;
/// How many tiles are fetched at once.
const PARALLEL_FETCHES: usize = 6;
/// How long one fetch may take.
const FETCH_TIMEOUT: Duration = Duration::from_secs(20);
/// Past this size the tile cache is emptied rather than left to grow.
const DISK_BUDGET: u64 = 256 * 1024 * 1024;
/// One tile of the Web Mercator grid: at zoom `z` the world is `2^z` tiles
/// wide and tall, counted from the north-west.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct TileKey {
pub(crate) z: u8,
pub(crate) x: u32,
pub(crate) y: u32,
}
impl TileKey {
pub(crate) fn parent(self) -> Option<Self> {
(self.z > 0).then(|| Self {
z: self.z - 1,
x: self.x / 2,
y: self.y / 2,
})
}
/// The tile whose data this one is drawn from.
fn data(self) -> Self {
let mut key = self;
while key.z > DATA_MAX_ZOOM {
key = key.parent().unwrap_or(key);
}
key
}
}
/// The colours of the map, for a light or a dark window.
pub(crate) struct Palette {
pub(crate) land: u32,
pub(crate) water: u32,
wood: u32,
grass: u32,
ice: u32,
sand: u32,
residential: u32,
industrial: u32,
building: u32,
motorway: u32,
primary: u32,
road: u32,
casing: u32,
rail: u32,
path: u32,
pub(crate) border: u32,
state_border: u32,
pub(crate) coast: u32,
pub(crate) text: u32,
pub(crate) halo: u32,
pub(crate) water_text: u32,
}
pub(crate) const LIGHT: Palette = Palette {
land: 0xf4f2ee,
water: 0xb3cde3,
wood: 0xd3e5c5,
grass: 0xdcebcf,
ice: 0xf2f6f9,
sand: 0xefe7d2,
residential: 0xebe7e2,
industrial: 0xebe4e8,
building: 0xdcd5ce,
motorway: 0xf2c98f,
primary: 0xfbe4ad,
road: 0xffffff,
casing: 0xd2cbc1,
rail: 0xb5afa8,
path: 0xbfae9c,
border: 0x9d94b5,
state_border: 0xc2bbd2,
coast: 0x9fbbd4,
text: 0x34313d,
halo: 0xffffff,
water_text: 0x4f7398,
};
pub(crate) const DARK: Palette = Palette {
land: 0x24222d,
water: 0x141c2b,
wood: 0x212c26,
grass: 0x232d27,
ice: 0x2c313a,
sand: 0x2d2b27,
residential: 0x292733,
industrial: 0x2b2833,
building: 0x322f3c,
motorway: 0x7a6647,
primary: 0x625a4b,
road: 0x46434f,
casing: 0x1a1822,
rail: 0x4e4a5a,
path: 0x3f3b49,
border: 0x857ca0,
state_border: 0x5c556f,
coast: 0x2c3b52,
text: 0xe7e4ef,
halo: 0x16141c,
water_text: 0x86a6cb,
};
pub(crate) fn palette(dark: bool) -> &'static Palette {
if dark { &DARK } else { &LIGHT }
}
pub(crate) fn set_rgb(cr: &cairo::Context, color: u32, alpha: f64) {
cr.set_source_rgba(
f64::from((color >> 16) & 0xff) / 255.0,
f64::from((color >> 8) & 0xff) / 255.0,
f64::from(color & 0xff) / 255.0,
alpha,
);
}
/// What kind of place a name stands for, which sets how it is written and
/// which names win when they would overlap.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) enum LabelClass {
Country,
State,
City,
Town,
Village,
Suburb,
Hamlet,
Water,
}
impl LabelClass {
fn from_place(class: &str) -> Option<Self> {
Some(match class {
"country" => Self::Country,
"state" | "province" => Self::State,
"city" => Self::City,
"town" => Self::Town,
"village" => Self::Village,
"suburb" | "quarter" => Self::Suburb,
"hamlet" | "neighbourhood" | "isolated_dwelling" => Self::Hamlet,
_ => return None,
})
}
/// The zoom from which such names are shown at all.
pub(crate) fn min_zoom(self) -> u8 {
match self {
Self::Country | Self::Water | Self::City => 0,
Self::State => 4,
Self::Town => 8,
Self::Village => 11,
Self::Suburb => 12,
Self::Hamlet => 14,
}
}
/// The zoom past which such names are left out again: a country's name
/// is no help once its towns are.
pub(crate) fn max_zoom(self) -> u8 {
match self {
Self::Country => 7,
Self::State => 9,
_ => u8::MAX,
}
}
}
/// A name to set on the map, at its place in world space (0..1 both ways).
#[derive(Clone, Debug)]
pub(crate) struct Label {
pub(crate) x: f64,
pub(crate) y: f64,
pub(crate) text: String,
pub(crate) class: LabelClass,
/// Lower is more important, within a class.
pub(crate) rank: f64,
}
/// A finished tile: premultiplied ARGB pixels, as cairo keeps them.
pub(crate) struct Raster {
pub(crate) key: TileKey,
pub(crate) dark: bool,
pub(crate) edge: i32,
pub(crate) pixels: Vec<u8>,
pub(crate) labels: Vec<Label>,
}
impl Raster {
pub(crate) fn surface(self) -> Option<cairo::ImageSurface> {
let stride = self.edge * 4;
cairo::ImageSurface::create_for_data(
self.pixels,
cairo::Format::ARgb32,
self.edge,
self.edge,
stride,
)
.ok()
}
}
pub(crate) enum Done {
Tile(Raster),
/// Nothing came: no network, or no such tile. The outline shows there.
Failed(TileKey),
/// The tile went off screen before its turn.
Dropped(TileKey),
}
struct Job {
key: TileKey,
dark: bool,
}
/// The worker thread making tiles. Dropping it stops the thread once the
/// fetches under way are done.
pub(crate) struct Tiles {
jobs: async_channel::Sender<Job>,
wanted: Arc<Mutex<HashSet<TileKey>>>,
/// Device pixels per logical px the tiles are made at.
pub(crate) scale: i32,
}
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>) {
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 = 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}");
}
(
Self {
jobs,
wanted,
scale,
},
done_rx,
)
}
pub(crate) fn request(&self, key: TileKey, dark: bool) {
let _ = self.jobs.try_send(Job { key, dark });
}
/// The tiles on screen now. A queued tile that isn't is skipped.
pub(crate) fn set_wanted(&self, keys: HashSet<TileKey>) {
if let Ok(mut wanted) = self.wanted.lock() {
*wanted = keys;
}
}
}
struct Worker {
dir: PathBuf,
language: String,
scale: i32,
wanted: Arc<Mutex<HashSet<TileKey>>>,
done: async_channel::Sender<Done>,
}
impl Worker {
fn run(self, jobs: async_channel::Receiver<Job>) {
let runtime = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(runtime) => runtime,
Err(e) => {
tracing::warn!("map tiles: no runtime: {e}");
return;
}
};
let client = match reqwest::Client::builder()
.user_agent(concat!(
"proton-drive-linux/",
env!("CARGO_PKG_VERSION"),
" (",
env!("CARGO_PKG_REPOSITORY"),
")"
))
.timeout(FETCH_TIMEOUT)
.build()
{
Ok(client) => client,
Err(e) => {
tracing::warn!("map tiles: no HTTP client: {e}");
return;
}
};
let worker = Arc::new(self);
runtime.block_on(async move {
let source = Arc::new(tokio::sync::Mutex::new(None::<String>));
let slots = Arc::new(tokio::sync::Semaphore::new(PARALLEL_FETCHES));
while let Ok(job) = jobs.recv().await {
let Ok(permit) = slots.clone().acquire_owned().await else {
break;
};
let (worker, client, source) = (worker.clone(), client.clone(), source.clone());
tokio::spawn(async move {
let done = worker.make(&client, &source, job).await;
let _ = worker.done.send(done).await;
drop(permit);
});
}
// Let the tiles under way finish before the runtime goes.
let _ = slots.acquire_many(PARALLEL_FETCHES as u32).await;
});
}
async fn make(
self: &Arc<Self>,
client: &reqwest::Client,
source: &tokio::sync::Mutex<Option<String>>,
job: Job,
) -> Done {
let key = job.key;
let still_wanted = self.wanted.lock().map(|w| w.contains(&key)).unwrap_or(true);
if !still_wanted {
return Done::Dropped(key);
}
let Some(data) = self.load(client, source, key.data()).await else {
return Done::Failed(key);
};
let worker = self.clone();
let made = tokio::task::spawn_blocking(move || {
let layers = mvt::decode(&data)?;
render(&layers, key, job.dark, worker.scale, &worker.language)
})
.await;
match made {
Ok(Some(raster)) => Done::Tile(raster),
_ => Done::Failed(key),
}
}
/// The tile's data, from the disk cache or else from OpenFreeMap.
async fn load(
&self,
client: &reqwest::Client,
source: &tokio::sync::Mutex<Option<String>>,
key: TileKey,
) -> Option<Vec<u8>> {
let template = {
let mut source = source.lock().await;
if source.is_none() {
*source = self.tile_source(client).await;
}
source.clone()?
};
let path = self
.build_dir(&template)?
.join(key.z.to_string())
.join(key.x.to_string())
.join(format!("{}.pbf", key.y));
if let Ok(data) = tokio::fs::read(&path).await {
return Some(data);
}
let url = template
.replace("{z}", &key.z.to_string())
.replace("{x}", &key.x.to_string())
.replace("{y}", &key.y.to_string());
let reply = client.get(&url).send().await.ok()?;
if !reply.status().is_success() {
tracing::debug!("map tile {url}: {}", reply.status());
return None;
}
let data = reply.bytes().await.ok()?.to_vec();
if let Some(parent) = path.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
}
let _ = tokio::fs::write(&path, &data).await;
Some(data)
}
/// The URL template of OpenFreeMap's current build, remembered on disk so
/// the cached tiles still show without a network.
async fn tile_source(&self, client: &reqwest::Client) -> Option<String> {
let saved = self.dir.join("tiles.json");
let fetched = async {
let reply = client.get(TILEJSON_URL).send().await.ok()?;
if !reply.status().is_success() {
return None;
}
reply.bytes().await.ok()
}
.await;
let (json, fresh) = match fetched {
Some(json) => (json.to_vec(), true),
None => (tokio::fs::read(&saved).await.ok()?, false),
};
let template = tile_template(&json)?;
if fresh {
let _ = tokio::fs::create_dir_all(&self.dir).await;
let _ = tokio::fs::write(&saved, &json).await;
let (dir, build) = (self.dir.clone(), build_name(&template)?);
let _ = tokio::task::spawn_blocking(move || prune(&dir, &build)).await;
}
Some(template)
}
fn build_dir(&self, template: &str) -> Option<PathBuf> {
Some(self.dir.join(build_name(template)?))
}
}
/// 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()?;
let template = doc.get("tiles")?.get(0)?.as_str()?;
template
.starts_with("https://")
.then(|| template.to_owned())
}
/// The tile set's build, the path segment before `/{z}`: a safe directory
/// name, or `None`.
fn build_name(template: &str) -> Option<String> {
let head = template.split("/{z}").next()?;
let name = head.rsplit('/').next()?;
let safe = !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
&& name != "."
&& name != "..";
safe.then(|| name.to_owned())
}
/// Remove the cached builds other than `keep`, and `keep` itself once it
/// holds more than [`DISK_BUDGET`].
fn prune(dir: &Path, keep: &str) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
let stale = entry.file_name() != keep || dir_size(&path) > DISK_BUDGET;
if stale && let Err(e) = std::fs::remove_dir_all(&path) {
tracing::debug!("map tiles: cannot remove {}: {e}", path.display());
}
}
}
fn dir_size(dir: &Path) -> u64 {
let Ok(entries) = std::fs::read_dir(dir) else {
return 0;
};
entries
.flatten()
.map(|entry| match entry.metadata() {
Ok(meta) if meta.is_dir() => dir_size(&entry.path()),
Ok(meta) => meta.len(),
Err(_) => 0,
})
.sum()
}
/// Draw tile `key` from the layers of its data tile, at `scale` device px
/// per logical px, and gather the names on it.
fn render(
layers: &[Layer],
key: TileKey,
dark: bool,
scale: i32,
language: &str,
) -> Option<Raster> {
let edge = (TILE_EDGE as i32) * scale.max(1);
let surface = cairo::ImageSurface::create(cairo::Format::ARgb32, edge, edge).ok()?;
let labels = {
let cr = cairo::Context::new(&surface).ok()?;
cr.scale(f64::from(scale), f64::from(scale));
let painter = Painter {
cr: &cr,
key,
data: key.data(),
colors: palette(dark),
};
painter.paint(layers);
gather_labels(layers, key.data(), language)
};
surface.flush();
let pixels = surface.take_data().ok()?.to_vec();
Some(Raster {
key,
dark,
edge,
pixels,
labels,
})
}
struct Painter<'a> {
cr: &'a cairo::Context,
key: TileKey,
data: TileKey,
colors: &'static Palette,
}
impl Painter<'_> {
fn paint(&self, layers: &[Layer]) {
let c = self.colors;
let z = self.key.z;
set_rgb(self.cr, c.land, 1.0);
let _ = self.cr.paint();
let layer = |name: &str| layers.iter().find(|l| l.name == name);
if let Some(layer) = layer("landcover") {
self.fill(layer, |class| match class {
"wood" | "forest" => Some(c.wood),
"grass" | "wetland" => Some(c.grass),
"ice" | "glacier" => Some(c.ice),
"sand" | "beach" => Some(c.sand),
_ => None,
});
}
if let Some(layer) = layer("landuse") {
self.fill(layer, |class| match class {
"residential" | "suburb" | "neighbourhood" => Some(c.residential),
"industrial" | "commercial" | "retail" | "railway" => Some(c.industrial),
"stadium" | "pitch" | "playground" | "cemetery" => Some(c.grass),
_ => None,
});
}
if let Some(layer) = layer("park") {
self.fill(layer, |_| Some(c.grass));
}
if let Some(layer) = layer("water") {
self.fill(layer, |_| Some(c.water));
}
if let Some(layer) = layer("waterway") {
self.stroke(layer, |class| {
let (base, from) = match class {
"river" => (1.2, 8),
"canal" => (1.0, 12),
"stream" => (0.6, 13),
_ => return None,
};
(z >= from).then(|| (c.water, grow(base, z), false))
});
}
if z >= 13
&& let Some(layer) = layer("building")
{
self.fill(layer, |_| Some(c.building));
}
if let Some(layer) = layer("transportation") {
self.roads(layer);
}
if let Some(layer) = layer("boundary") {
self.borders(layer);
}
}
/// Map tile units of the data tile onto this tile's logical px.
fn to_px(&self, layer: &Layer, (u, v): (f64, f64)) -> (f64, f64) {
let k = f64::from(1u32 << (self.key.z - self.data.z));
let ox = f64::from(self.key.x) - f64::from(self.data.x) * k;
let oy = f64::from(self.key.y) - f64::from(self.data.y) * k;
(
(u / layer.extent * k - ox) * TILE_EDGE,
(v / layer.extent * k - oy) * TILE_EDGE,
)
}
fn trace(&self, layer: &Layer, part: &[(f64, f64)], close: bool) {
for (i, &point) in part.iter().enumerate() {
let (x, y) = self.to_px(layer, point);
if i == 0 {
self.cr.move_to(x, y);
} else {
self.cr.line_to(x, y);
}
}
if close {
self.cr.close_path();
}
}
/// Fill the layer's polygons in the colour `color` picks by class.
fn fill(&self, layer: &Layer, color: impl Fn(&str) -> Option<u32>) {
self.cr.set_fill_rule(cairo::FillRule::EvenOdd);
for feature in &layer.features {
if feature.kind != Kind::Polygon {
continue;
}
let class = layer.text(feature, "class").unwrap_or("");
let Some(rgb) = color(class) else {
continue;
};
self.cr.new_path();
for part in &feature.parts {
self.trace(layer, part, true);
}
set_rgb(self.cr, rgb, 1.0);
let _ = self.cr.fill();
}
}
/// Stroke the layer's lines as `style` says by class: colour, width in
/// px, and whether dashed.
fn stroke(&self, layer: &Layer, style: impl Fn(&str) -> Option<(u32, f64, bool)>) {
self.cr.set_line_cap(cairo::LineCap::Round);
self.cr.set_line_join(cairo::LineJoin::Round);
for feature in &layer.features {
if feature.kind != Kind::Line {
continue;
}
let class = layer.text(feature, "class").unwrap_or("");
let Some((rgb, width, dashed)) = style(class) else {
continue;
};
self.cr.new_path();
for part in &feature.parts {
self.trace(layer, part, false);
}
set_rgb(self.cr, rgb, 1.0);
self.cr.set_line_width(width);
let dash = [width * 2.0, width * 2.0];
self.cr.set_dash(if dashed { &dash } else { &[] }, 0.0);
let _ = self.cr.stroke();
}
self.cr.set_dash(&[], 0.0);
}
/// Roads, minor first so the major ones cross over them, each on a
/// darker casing once they are wide enough for one.
fn roads(&self, layer: &Layer) {
let c = self.colors;
let z = self.key.z;
let road = |class: &str| -> Option<(u32, f64, u8)> {
let (color, width, rank) = match class {
"motorway" if z >= 6 => (c.motorway, grow(2.2, z), 4),
"trunk" if z >= 7 => (c.motorway, grow(2.2, z), 4),
"primary" if z >= 8 => (c.primary, grow(1.8, z), 3),
"secondary" if z >= 10 => (c.road, grow(1.4, z), 2),
"tertiary" if z >= 11 => (c.road, grow(1.4, z), 2),
"minor" | "busway" if z >= 12 => (c.road, grow(1.0, z), 1),
"service" if z >= 14 => (c.road, grow(0.6, z), 0),
_ => return None,
};
Some((color, width, rank))
};
for rank in 0..=4u8 {
let pick = |class: &str| road(class).filter(|r| r.2 == rank);
if z >= 12 {
self.stroke(layer, |class| {
pick(class).map(|(_, width, _)| (c.casing, width + 1.5, false))
});
}
self.stroke(layer, |class| {
pick(class).map(|(color, width, _)| (color, width, false))
});
}
self.stroke(layer, |class| match class {
"rail" | "transit" if z >= 10 => Some((c.rail, grow(0.7, z).min(2.5), false)),
"path" | "track" if z >= 14 => Some((c.path, 0.8, true)),
_ => None,
});
}
fn borders(&self, layer: &Layer) {
let c = self.colors;
let z = self.key.z;
self.cr.set_line_cap(cairo::LineCap::Round);
for feature in &layer.features {
if feature.kind != Kind::Line || layer.number(feature, "maritime") == Some(1.0) {
continue;
}
let (color, width, dashed) = match layer.number(feature, "admin_level") {
Some(level) if level <= 2.0 => {
(c.border, (0.9 * 1.12f64.powi(i32::from(z))).min(2.5), false)
}
Some(level) if level <= 4.0 && z >= 5 => (c.state_border, 0.8, true),
_ => continue,
};
let dashed = dashed || layer.number(feature, "disputed") == Some(1.0);
self.cr.new_path();
for part in &feature.parts {
self.trace(layer, part, false);
}
set_rgb(self.cr, color, 1.0);
self.cr.set_line_width(width);
self.cr
.set_dash(if dashed { &[3.0, 2.5] } else { &[] }, 0.0);
let _ = self.cr.stroke();
}
self.cr.set_dash(&[], 0.0);
}
}
/// A line width that grows with the zoom, as the things it stands for get
/// bigger on screen.
fn grow(base: f64, z: u8) -> f64 {
(base * 1.4f64.powi(i32::from(z) - 10)).clamp(0.5, 24.0)
}
/// The names of towns, countries and seas on data tile `data`, in world
/// space. Names in the tile's buffer beyond its edge are left to the
/// neighbour they belong to.
fn gather_labels(layers: &[Layer], data: TileKey, language: &str) -> Vec<Label> {
let n = f64::from(1u32 << data.z);
let mut labels = Vec::new();
for layer in layers {
let water = match layer.name.as_str() {
"place" => false,
"water_name" => true,
_ => continue,
};
for feature in &layer.features {
if feature.kind != Kind::Point {
continue;
}
let class = if water {
LabelClass::Water
} else {
let Some(class) = layer
.text(feature, "class")
.and_then(LabelClass::from_place)
else {
continue;
};
class
};
let Some(text) = label_name(layer, feature, language) else {
continue;
};
let rank = layer.number(feature, "rank").unwrap_or(99.0);
for &(u, v) in feature.parts.iter().flatten() {
if !(0.0..layer.extent).contains(&u) || !(0.0..layer.extent).contains(&v) {
continue;
}
labels.push(Label {
x: (f64::from(data.x) + u / layer.extent) / n,
y: (f64::from(data.y) + v / layer.extent) / n,
text: text.clone(),
class,
rank,
});
}
}
}
labels
}
/// A feature's name in `language` where the map has it, else in Latin
/// letters, else as written locally.
fn label_name(layer: &Layer, feature: &mvt::Feature, language: &str) -> Option<String> {
[
format!("name:{language}"),
format!("name_{language}"),
"name:latin".to_owned(),
"name".to_owned(),
]
.iter()
.find_map(|key| layer.text(feature, key).filter(|name| !name.is_empty()))
.map(|name| name.replace('\n', " "))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deep_tiles_draw_from_their_ancestor_at_the_data_zoom() {
let key = TileKey {
z: 16,
x: 34_336,
y: 22_437,
};
assert_eq!(
key.data(),
TileKey {
z: 14,
x: 8_584,
y: 5_609
}
);
let shallow = TileKey { z: 3, x: 4, y: 2 };
assert_eq!(shallow.data(), shallow);
}
#[test]
fn the_build_comes_from_the_tile_template() {
let json = br#"{"tiles":["https://tiles.openfreemap.org/planet/20260913_164504_pt/{z}/{x}/{y}.pbf"]}"#;
let template = tile_template(json).unwrap();
assert_eq!(build_name(&template).as_deref(), Some("20260913_164504_pt"));
assert_eq!(build_name("https://example.org/../{z}/{x}/{y}.pbf"), None);
assert_eq!(
tile_template(br#"{"tiles":["http://plain.example/{z}"]}"#),
None
);
}
#[test]
fn an_old_build_is_pruned_and_the_current_one_kept() {
let dir = std::env::temp_dir().join(format!("pdfs-map-prune-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("old/1/0")).unwrap();
std::fs::create_dir_all(dir.join("new/1/0")).unwrap();
std::fs::write(dir.join("new/1/0/0.pbf"), b"tile").unwrap();
std::fs::write(dir.join("tiles.json"), b"{}").unwrap();
prune(&dir, "new");
assert!(!dir.join("old").exists());
assert!(dir.join("new/1/0/0.pbf").exists());
assert!(dir.join("tiles.json").exists());
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn roads_widen_as_the_map_zooms_in() {
assert!(grow(1.4, 14) > grow(1.4, 10));
assert_eq!(grow(2.2, 30), 24.0);
}
}
+2
View File
@@ -5,6 +5,8 @@ pub(crate) mod devices;
pub(crate) mod duplicates;
pub(crate) mod locations;
pub(crate) mod login;
pub(crate) mod map_tiles;
pub(crate) mod mvt;
pub(crate) mod photo_viewer;
pub(crate) mod photos;
pub(crate) mod places;
+386
View File
@@ -0,0 +1,386 @@
//! A reader for Mapbox Vector Tiles, the format the online Places map's tiles
//! come in: protobuf, one message per tile, holding named layers of point,
//! line and polygon features with key/value tags.
//!
//! Only what drawing needs is read — layer names, tags and geometry — and a
//! tile that doesn't parse is `None` rather than an error: the map then shows
//! the outline underneath it. The format is at
//! <https://github.com/mapbox/vector-tile-spec>.
/// One layer of a tile, such as `water` or `transportation`.
pub(crate) struct Layer {
pub(crate) name: String,
/// The tile's width in geometry units; 4096 almost everywhere.
pub(crate) extent: f64,
keys: Vec<String>,
values: Vec<Value>,
pub(crate) features: Vec<Feature>,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Value {
Text(String),
Number(f64),
Bool(bool),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
Point,
Line,
Polygon,
}
pub(crate) struct Feature {
pub(crate) kind: Kind,
/// Pairs of indices into the layer's keys and values.
tags: Vec<(u32, u32)>,
/// Points, lines or polygon rings, in tile units. A point feature holds
/// one part with all its points.
pub(crate) parts: Vec<Vec<(f64, f64)>>,
}
impl Layer {
/// The value `feature` carries for `key`.
pub(crate) fn tag(&self, feature: &Feature, key: &str) -> Option<&Value> {
feature.tags.iter().find_map(|&(k, v)| {
(self.keys.get(k as usize)? == key).then(|| self.values.get(v as usize))?
})
}
pub(crate) fn text(&self, feature: &Feature, key: &str) -> Option<&str> {
match self.tag(feature, key)? {
Value::Text(text) => Some(text),
_ => None,
}
}
pub(crate) fn number(&self, feature: &Feature, key: &str) -> Option<f64> {
match self.tag(feature, key)? {
Value::Number(n) => Some(*n),
_ => None,
}
}
}
/// Every layer of the tile in `data`.
pub(crate) fn decode(data: &[u8]) -> Option<Vec<Layer>> {
let mut tile = Reader::new(data);
let mut layers = Vec::new();
while let Some((field, wire)) = tile.field()? {
match field {
3 => layers.push(decode_layer(tile.bytes()?)?),
_ => tile.skip(wire)?,
}
}
Some(layers)
}
fn decode_layer(data: &[u8]) -> Option<Layer> {
let mut layer = Layer {
name: String::new(),
extent: 4096.0,
keys: Vec::new(),
values: Vec::new(),
features: Vec::new(),
};
let mut reader = Reader::new(data);
while let Some((field, wire)) = reader.field()? {
match field {
1 => layer.name = reader.text()?,
2 => {
if let Some(feature) = decode_feature(reader.bytes()?) {
layer.features.push(feature);
}
}
3 => layer.keys.push(reader.text()?),
4 => layer.values.push(decode_value(reader.bytes()?)?),
5 => layer.extent = reader.varint()? as f64,
_ => reader.skip(wire)?,
}
}
Some(layer)
}
fn decode_value(data: &[u8]) -> Option<Value> {
let mut reader = Reader::new(data);
let mut value = Value::Bool(false);
while let Some((field, wire)) = reader.field()? {
value = match field {
1 => Value::Text(reader.text()?),
2 => Value::Number(f64::from(f32::from_bits(reader.fixed32()?))),
3 => Value::Number(f64::from_bits(reader.fixed64()?)),
4 | 5 => Value::Number(reader.varint()? as i64 as f64),
6 => Value::Number(zigzag(reader.varint()?) as f64),
7 => Value::Bool(reader.varint()? != 0),
_ => {
reader.skip(wire)?;
continue;
}
};
}
Some(value)
}
/// A feature, or `None` for one this map can't draw (unknown geometry type,
/// or broken).
fn decode_feature(data: &[u8]) -> Option<Feature> {
let mut reader = Reader::new(data);
let mut kind = None;
let mut tags = Vec::new();
let mut geometry = Vec::new();
while let Some((field, wire)) = reader.field()? {
match field {
2 => {
let packed = reader.packed()?;
tags = packed
.as_chunks::<2>()
.0
.iter()
.map(|&[k, v]| (k as u32, v as u32))
.collect();
}
3 => {
kind = match reader.varint()? {
1 => Some(Kind::Point),
2 => Some(Kind::Line),
3 => Some(Kind::Polygon),
_ => None,
}
}
4 => geometry = reader.packed()?,
_ => reader.skip(wire)?,
}
}
let kind = kind?;
Some(Feature {
kind,
tags,
parts: decode_geometry(kind, &geometry)?,
})
}
/// Turn the command stream of a feature's geometry into its parts. Positions
/// are deltas from the previous one, carried across parts.
fn decode_geometry(kind: Kind, commands: &[u64]) -> Option<Vec<Vec<(f64, f64)>>> {
let mut parts: Vec<Vec<(f64, f64)>> = Vec::new();
let (mut x, mut y) = (0i64, 0i64);
let mut i = 0;
while i < commands.len() {
let command = commands[i] & 7;
let count = (commands[i] >> 3) as usize;
i += 1;
match command {
// MoveTo starts a part — except for points, which all share one.
1 | 2 => {
if i + 2 * count > commands.len() {
return None;
}
for n in 0..count {
x += zigzag(commands[i + 2 * n]);
y += zigzag(commands[i + 2 * n + 1]);
let starts = command == 1 && (kind != Kind::Point || parts.is_empty());
if starts {
parts.push(Vec::new());
}
parts.last_mut()?.push((x as f64, y as f64));
}
i += 2 * count;
}
// ClosePath: the ring's end joins its start, which drawing does.
7 => {}
_ => return None,
}
}
Some(parts)
}
fn zigzag(n: u64) -> i64 {
((n >> 1) as i64) ^ -((n & 1) as i64)
}
/// The protobuf wire format, as far as vector tiles use it.
struct Reader<'a> {
data: &'a [u8],
at: usize,
}
impl<'a> Reader<'a> {
fn new(data: &'a [u8]) -> Self {
Self { data, at: 0 }
}
/// The next field's number and wire type; `Some(None)` at the end, `None`
/// on a broken message.
fn field(&mut self) -> Option<Option<(u64, u8)>> {
if self.at >= self.data.len() {
return Some(None);
}
let key = self.varint()?;
Some(Some((key >> 3, (key & 7) as u8)))
}
fn varint(&mut self) -> Option<u64> {
let mut value = 0u64;
for shift in (0..64).step_by(7) {
let byte = *self.data.get(self.at)?;
self.at += 1;
value |= u64::from(byte & 0x7f) << shift;
if byte & 0x80 == 0 {
return Some(value);
}
}
None
}
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let end = self.at.checked_add(n)?;
let bytes = self.data.get(self.at..end)?;
self.at = end;
Some(bytes)
}
fn bytes(&mut self) -> Option<&'a [u8]> {
let len = usize::try_from(self.varint()?).ok()?;
self.take(len)
}
fn text(&mut self) -> Option<String> {
Some(String::from_utf8_lossy(self.bytes()?).into_owned())
}
fn fixed32(&mut self) -> Option<u32> {
Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
}
fn fixed64(&mut self) -> Option<u64> {
Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?))
}
fn packed(&mut self) -> Option<Vec<u64>> {
let mut inner = Reader::new(self.bytes()?);
let mut values = Vec::new();
while inner.at < inner.data.len() {
values.push(inner.varint()?);
}
Some(values)
}
fn skip(&mut self, wire: u8) -> Option<()> {
match wire {
0 => {
self.varint()?;
}
1 => {
self.take(8)?;
}
2 => {
self.bytes()?;
}
5 => {
self.take(4)?;
}
_ => return None,
}
Some(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn varint(mut n: u64, out: &mut Vec<u8>) {
while n >= 0x80 {
out.push((n as u8) | 0x80);
n >>= 7;
}
out.push(n as u8);
}
fn field(number: u64, bytes: &[u8], out: &mut Vec<u8>) {
varint(number << 3 | 2, out);
varint(bytes.len() as u64, out);
out.extend_from_slice(bytes);
}
fn packed(values: &[u64]) -> Vec<u8> {
let mut out = Vec::new();
for &v in values {
varint(v, &mut out);
}
out
}
fn zz(n: i64) -> u64 {
((n << 1) ^ (n >> 63)) as u64
}
/// A tile with one `water` layer holding one square tagged class=lake.
fn lake_tile() -> Vec<u8> {
let mut feature = Vec::new();
field(2, &packed(&[0, 0]), &mut feature);
varint(3 << 3, &mut feature);
varint(3, &mut feature);
let square = [
1 | 1 << 3,
zz(10),
zz(10),
2 | 3 << 3,
zz(20),
zz(0),
zz(0),
zz(20),
zz(-20),
zz(0),
7 | 1 << 3,
];
field(4, &packed(&square), &mut feature);
let mut value = Vec::new();
field(1, b"lake", &mut value);
let mut layer = Vec::new();
field(1, b"water", &mut layer);
field(2, &feature, &mut layer);
field(3, b"class", &mut layer);
field(4, &value, &mut layer);
varint(5 << 3, &mut layer);
varint(4096, &mut layer);
let mut tile = Vec::new();
field(3, &layer, &mut tile);
tile
}
#[test]
fn a_polygon_decodes_with_its_tags() {
let layers = decode(&lake_tile()).unwrap();
let [water] = &layers[..] else {
panic!("one layer expected");
};
assert_eq!(water.name, "water");
assert_eq!(water.extent, 4096.0);
let feature = &water.features[0];
assert_eq!(feature.kind, Kind::Polygon);
assert_eq!(water.text(feature, "class"), Some("lake"));
assert_eq!(water.text(feature, "name"), None);
assert_eq!(
feature.parts,
vec![vec![(10.0, 10.0), (30.0, 10.0), (30.0, 30.0), (10.0, 30.0)]]
);
}
#[test]
fn a_cut_off_tile_is_rejected() {
let tile = lake_tile();
assert!(decode(&tile[..tile.len() - 3]).is_none());
}
#[test]
fn points_of_one_feature_share_a_part() {
let commands = [1 | 2 << 3, zz(5), zz(5), zz(1), zz(-1)];
let parts = decode_geometry(Kind::Point, &commands).unwrap();
assert_eq!(parts, vec![vec![(5.0, 5.0), (6.0, 4.0)]]);
}
}
@@ -1390,12 +1390,14 @@ pub(crate) fn open_photo_viewer(ui: &Rc<Ui>, initial_uid: String) {
let toggle_off = info_toggle.clone();
info_close.connect_clicked(move |_| toggle_off.set_active(false));
let ui_map = ui.clone();
let viewer_map = viewer.clone();
let w_map = window.clone();
info_map.connect_clicked(move |_| {
if let Some((lat, lon)) = *viewer_map.coords.borrow() {
open_path(&format!(
"https://www.openstreetmap.org/?mlat={lat:.6}&mlon={lon:.6}#map=16/{lat:.6}/{lon:.6}"
));
let coords = *viewer_map.coords.borrow();
if let Some((lat, lon)) = coords {
w_map.close();
show_on_map(&ui_map, lat, lon);
}
});
+198 -3
View File
@@ -10,6 +10,9 @@ use crate::*;
/// Edge length in px of a place's cover, the same as an album's.
const COVER_EDGE: i32 = 200;
/// Edge length in px of a photo in the list of photos taken on one spot.
const SPOT_EDGE: i32 = 96;
/// How often the listing is asked for again while photo locations are read.
const MAPPING_POLL: std::time::Duration = std::time::Duration::from_secs(2);
@@ -232,6 +235,8 @@ fn place_card(ui: &Rc<Ui>, place: &PlaceInfo) -> gtk4::Button {
button.set_tooltip_text(Some(&format!("{}\n{subtitle}", place.name)));
want_cover(ui, place.cover.uid.clone(), &picture);
// The map marks the town with the same photo.
cover_map_marker(ui, &place.cover.uid, &picture);
let ui_open = ui.clone();
let place = place.clone();
@@ -239,6 +244,175 @@ fn place_card(ui: &Rc<Ui>, place: &PlaceInfo) -> gtk4::Button {
button
}
/// Hand the map the photo `picture` shows once it is there.
fn cover_map_marker(ui: &Rc<Ui>, uid: &str, picture: &gtk4::Picture) {
let map = Rc::downgrade(&ui.gallery.places_map);
let set = move |picture: &gtk4::Picture, uid: &str| {
let texture = picture.paintable().and_downcast::<gtk4::gdk::Texture>();
if let (Some(map), Some(texture)) = (map.upgrade(), texture) {
map.set_cover(uid, &texture);
}
};
set(picture, uid);
let uid = uid.to_owned();
picture.connect_paintable_notify(move |picture| set(picture, &uid));
}
/// Get the map the thumbnail of a photo it marks on its own, through the
/// gallery's thumbnail pipeline.
fn want_map_thumb(ui: &Rc<Ui>, photo: &PhotoItem) {
if let Some(texture) = ui.gallery.photo_tex.borrow().get(&photo.uid) {
ui.gallery.places_map.set_cover(&photo.uid, texture);
return;
}
// A town's card may be waiting for the same photo: share its picture
// rather than take its place in the queue.
let waiting = ui.gallery.thumb_wanted.borrow().get(&photo.uid).cloned();
let picture = waiting.unwrap_or_else(|| {
let picture = gtk4::Picture::new();
want_thumb(ui, photo, &picture);
picture
});
cover_map_marker(ui, &photo.uid, &picture);
schedule_thumbs(ui);
}
/// List the photos taken on one spot of the map in a popover at `(x, y)`;
/// clicking one opens it in its town.
fn show_spot_photos(ui: &Rc<Ui>, photos: Vec<(PlaceInfo, PhotoItem)>, (x, y): (f64, f64)) {
let Some((place, _)) = photos.first() else {
return;
};
let popover = gtk4::Popover::new();
popover.set_parent(ui.gallery.places_map.widget());
popover.set_pointing_to(Some(&gtk4::gdk::Rectangle::new(x as i32, y as i32, 1, 1)));
let content = gtk4::Box::new(gtk4::Orientation::Vertical, 6);
content.set_margin_top(6);
content.set_margin_bottom(6);
content.set_margin_start(6);
content.set_margin_end(6);
let title = gtk4::Label::builder()
.label(&place.name)
.halign(gtk4::Align::Start)
.build();
title.add_css_class("heading");
let count = gtk4::Label::builder()
.label(ngettext_f(
"{n} photo",
"{n} photos",
photos.len() as u64,
&[],
))
.halign(gtk4::Align::Start)
.build();
count.add_css_class("dim-label");
count.add_css_class("caption");
content.append(&title);
content.append(&count);
let grid = gtk4::FlowBox::builder()
.selection_mode(gtk4::SelectionMode::None)
.homogeneous(true)
.min_children_per_line(1)
.max_children_per_line(4)
.row_spacing(4)
.column_spacing(4)
.build();
for (place, photo) in photos {
let picture = gtk4::Picture::builder()
.content_fit(gtk4::ContentFit::Cover)
.can_shrink(true)
.width_request(SPOT_EDGE)
.height_request(SPOT_EDGE)
.build();
spot_thumb(ui, &photo, &picture);
let button = gtk4::Button::builder()
.child(&picture)
.tooltip_text(format_capture_time(photo.capture_time))
.build();
button.add_css_class("flat");
button.add_css_class("places-spot-photo");
let ui_open = ui.clone();
let popover_open = popover.clone();
button.connect_clicked(move |_| {
popover_open.popdown();
open_place_photo(&ui_open, place.clone(), photo.uid.clone());
});
grid.append(&button);
}
schedule_thumbs(ui);
let scroller = gtk4::ScrolledWindow::builder()
.hscrollbar_policy(gtk4::PolicyType::Never)
.propagate_natural_width(true)
.propagate_natural_height(true)
.max_content_height(360)
.child(&grid)
.build();
content.append(&scroller);
popover.set_child(Some(&content));
// Gone with its last use; its parent is the map, which stays.
popover.connect_closed(|popover| {
let popover = popover.clone();
glib::idle_add_local_once(move || popover.unparent());
});
popover.popup();
}
/// Show photo's thumbnail in `picture`, sharing one another widget is
/// already waiting for.
fn spot_thumb(ui: &Rc<Ui>, photo: &PhotoItem, picture: &gtk4::Picture) {
let waiting = ui.gallery.thumb_wanted.borrow().get(&photo.uid).cloned();
match waiting {
Some(waiting) => {
waiting
.bind_property("paintable", picture, "paintable")
.sync_create()
.build();
}
None => want_thumb(ui, photo, picture),
}
}
/// Get the map the photos of town `id` with where each was taken.
fn load_place_locations(ui: &Rc<Ui>, id: u32) {
let rx = spawn_request(ui.dirs.control_socket(), Request::PlaceLocations { id });
let ui = ui.clone();
glib::spawn_future_local(async move {
match rx.recv().await {
Ok(Ok(Response::PhotoLocations { items })) => {
ui.gallery.places_map.set_locations(id, items)
}
// The map keeps showing the town as one marker.
Ok(Ok(Response::Error { message, .. })) => {
tracing::debug!("place locations failed: {message}")
}
Ok(Ok(_)) | Ok(Err(_)) | Err(_) => tracing::debug!("place locations: no reply"),
}
});
}
/// Open `place` and then photo `uid` in it, paging through the town until
/// the photo has loaded.
fn open_place_photo(ui: &Rc<Ui>, place: PlaceInfo, uid: String) {
open_place(ui, place);
view_when_loaded(ui, uid);
}
fn view_when_loaded(ui: &Rc<Ui>, uid: String) {
let ui_page = ui.clone();
ui.gallery.page_waiters.borrow_mut().push(Box::new(move || {
let ui = ui_page;
if find_photo_index(&ui.gallery.model, &uid).is_some() {
open_photo_viewer(&ui, uid);
} else if ui.gallery.has_more.get() && ui.gallery.place.borrow().is_some() {
view_when_loaded(&ui, uid);
ui.gallery.burst.set(true);
load_gallery(&ui, true);
}
}));
}
/// Open one place in the gallery: the timeline view, paged from that town.
fn open_place(ui: &Rc<Ui>, place: PlaceInfo) {
ui.gallery.title.set_title(&place.name);
@@ -302,10 +476,31 @@ pub(crate) fn wire_places(ui: &Rc<Ui>) {
}
});
let map = &ui.gallery.places_map;
let ui_open = ui.clone();
ui.gallery
.places_map
.connect_open(move |place| open_place(&ui_open, place));
map.connect_open(move |place| open_place(&ui_open, place));
let ui_photo = ui.clone();
map.connect_open_photo(move |place, uid| open_place_photo(&ui_photo, place, uid));
let ui_locations = ui.clone();
map.connect_want_locations(move |id| load_place_locations(&ui_locations, id));
let ui_thumb = ui.clone();
map.connect_want_thumb(move |photo| want_map_thumb(&ui_thumb, &photo));
let ui_spot = ui.clone();
map.connect_open_spot(move |photos, at| show_spot_photos(&ui_spot, photos, at));
map.set_online(ui.dirs.load_config().online_map, ui.dirs.cache_dir());
}
/// Switch to the Places map and zoom in on `(latitude, longitude)`, where a
/// photo in the viewer was taken.
pub(crate) fn show_on_map(ui: &Rc<Ui>, latitude: f64, longitude: f64) {
ui.gallery.places_map_btn.set_active(true);
if ui.gallery.places_btn.is_active() {
// Already in Places, perhaps inside a town: back out to the listing.
show_places(ui);
} else {
ui.gallery.places_btn.set_active(true);
}
ui.gallery.places_map.show_spot(latitude, longitude);
}
/// Show the places as cards or on the map, as the Grid/Map toggle says.
File diff suppressed because it is too large. Load diff
+58 -21
View File
@@ -44,8 +44,10 @@ pub(crate) struct StatusState {
pub(crate) download_limit_row: adw::SpinRow,
/// Shows where the primary mount lives; its Change button picks a new one.
pub(crate) mountpoint_row: adw::ActionRow,
/// "Proton purple accent" toggle. Guarded by [`Self::settings_suppress`].
pub(crate) accent_row: adw::SwitchRow,
/// "Proton theme" toggle. Guarded by [`Self::settings_suppress`].
pub(crate) theme_row: adw::SwitchRow,
/// Street map on the Places map. Guarded by [`Self::settings_suppress`].
pub(crate) online_map_row: adw::SwitchRow,
/// "Show tray icon" toggle. Guarded by [`Self::settings_suppress`].
pub(crate) tray_row: adw::SwitchRow,
/// Language picker: "System Default", then [`i18n::LANGUAGES`]. Guarded by
@@ -139,7 +141,8 @@ pub(crate) struct MainWidgets {
/// Shows the active mountpoint; its suffix button picks a new one.
pub(crate) mountpoint_row: adw::ActionRow,
pub(crate) mountpoint_button: gtk4::Button,
pub(crate) accent_row: adw::SwitchRow,
pub(crate) theme_row: adw::SwitchRow,
pub(crate) online_map_row: adw::SwitchRow,
pub(crate) tray_row: adw::SwitchRow,
pub(crate) language_row: adw::ComboRow,
}
@@ -207,13 +210,20 @@ pub(crate) fn build_main_page() -> MainWidgets {
let appearance_group = adw::PreferencesGroup::builder()
.title(gettext("Appearance"))
.build();
let accent_row = adw::SwitchRow::builder()
.title(gettext("Proton purple accent"))
let theme_row = adw::SwitchRow::builder()
.title(gettext("Proton theme"))
.subtitle(gettext(
"Use the Proton brand color instead of the system accent color",
"Use Proton's colors instead of the system theme and accent color",
))
.build();
appearance_group.add(&accent_row);
appearance_group.add(&theme_row);
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.",
))
.build();
appearance_group.add(&online_map_row);
let tray_row = adw::SwitchRow::builder()
.title(gettext("Show tray icon"))
.subtitle(gettext("Sync status and quick actions in the panel"))
@@ -395,7 +405,8 @@ pub(crate) fn build_main_page() -> MainWidgets {
purge_button,
mountpoint_row,
mountpoint_button,
accent_row,
theme_row,
online_map_row,
tray_row,
language_row,
}
@@ -455,7 +466,7 @@ pub(crate) const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
pub(crate) const MIB: f64 = 1024.0 * 1024.0;
/// Wire the Preferences controls: the cache-budget editor, the purge button, the
/// start-on-login switch, the mountpoint chooser and the accent toggle. Initial widget state is
/// start-on-login switch, the mountpoint chooser and the theme toggle. Initial widget state is
/// read once from config / systemd here (the refresh loop owns only the live
/// mount + cache-usage read-out), with [`Ui::settings_suppress`] set around the
/// programmatic populate so the change handlers don't fire on it.
@@ -482,8 +493,9 @@ pub(crate) fn wire_settings(
.set_subtitle(&ui.dirs.resolved_mountpoint(&config).display().to_string());
ui.status.autostart_row.set_active(service::is_enabled());
ui.status
.accent_row
.set_active(config.proton_accent.unwrap_or(false));
.theme_row
.set_active(config.proton_theme.unwrap_or(false));
ui.status.online_map_row.set_active(config.online_map);
ui.status.tray_row.set_active(!config.tray_hidden);
ui.status
.language_row
@@ -585,20 +597,45 @@ pub(crate) fn wire_settings(
let ui_mp = ui.clone();
mountpoint_button.connect_clicked(move |_| prompt_mountpoint(&ui_mp));
// Accent: saved with the rest of the config, applied right away.
let ui_accent = ui.clone();
ui.status.accent_row.connect_active_notify(move |row| {
if ui_accent.status.settings_suppress.get() {
// Theme: saved with the rest of the config, applied right away.
let ui_theme = ui.clone();
ui.status.theme_row.connect_active_notify(move |row| {
if ui_theme.status.settings_suppress.get() {
return;
}
let on = row.is_active();
set_proton_accent(on);
let mut config = ui_accent.dirs.load_config();
config.proton_accent = Some(on);
if let Err(e) = ui_accent.dirs.save_config(&config) {
set_proton_theme(on);
// Folders swap their icon with the theme; have every row bound again.
let rows = ui_theme.browser.model.n_items();
ui_theme.browser.model.items_changed(0, rows, rows);
let mut config = ui_theme.dirs.load_config();
config.proton_theme = Some(on);
if let Err(e) = ui_theme.dirs.save_config(&config) {
toast_error(
&ui_accent,
&gettext("Couldn't save the accent color"),
&ui_theme,
&gettext("Couldn't save the theme"),
&e.to_string(),
);
}
});
// Street map: saved, and the Places map switches over right away.
let ui_map = ui.clone();
ui.status.online_map_row.connect_active_notify(move |row| {
if ui_map.status.settings_suppress.get() {
return;
}
let on = row.is_active();
ui_map
.gallery
.places_map
.set_online(on, ui_map.dirs.cache_dir());
let mut config = ui_map.dirs.load_config();
config.online_map = on;
if let Err(e) = ui_map.dirs.save_config(&config) {
toast_error(
&ui_map,
&gettext("Couldn't save the map setting"),
&e.to_string(),
);
}
+1 -1
View File
@@ -359,7 +359,7 @@ pub(crate) fn wire_details(ui: &Rc<Ui>) {
pub(crate) fn show_details(ui: &Rc<Ui>, entry: &DirEntry) {
ui.details.details_suppress.set(true);
let d = &ui.details.details;
d.icon.set_icon_name(Some(icon_base_for(entry)));
d.icon.set_icon_name(Some(icon_for(entry)));
d.name.set_label(&entry.name);
d.kind.set_label(&if entry.is_dir {
gettext("Folder")
@@ -173,7 +173,7 @@ pub(crate) fn bind_file_thumbnail(
let fallback_name = if symbolic_fallback {
format!("{}-symbolic", icon_base_for(entry))
} else {
icon_base_for(entry).to_string()
icon_for(entry).to_string()
};
fallback.set_icon_name(Some(&fallback_name));
fallback.set_visible(true);