crates/sverigekartan/src/lib.rs
//! **Sverigekartan, native** — the map of Sweden from a korp map server, in a window.
//!
//! The map is facett's: [`facett_mapfeed`] is the same feed (wire, decode, debounced
//! viewport fetches, scene hand-over) and the same two viewer adapters
//! (`ServerOsm2d`, `ServerOsm3d`) the Streamlit component runs in the browser. This
//! crate adds only the window around them: a 2D/3D switch that keeps the place, an
//! address search (`/v1/geocode`), the nearest address to a click (`/v1/revgeocode`),
//! and a native transport ([`facett_mapfeed::native::ThreadTransport`]: worker
//! threads, https over rustls on graviola). It has no wire code of its own, so it
//! follows facett-mapfeed when the wire moves.
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use egui::{Color32, FontId, Key, Pos2, Stroke};
use facett_core::Facet;
use facett_mapfeed::geocode::{self, Address};
use facett_mapfeed::native::ThreadTransport;
use facett_mapfeed::transport::{Outcome, Pending, Transport};
use facett_mapfeed::view::{MapView, ViewAsk};
use facett_mapfeed::viewers::{ServerOsm2d, ServerOsm3d};
use facett_mapfeed::{Clock, ServerPayload, SystemClock, feed_for};
/// The public map server.
pub const DEFAULT_SERVER: &str = "https://karta.gunnar.rs";
/// The region the public server serves.
pub const DEFAULT_REGION: &str = "sweden";
/// The zoom a found address is shown at (a few streets across).
pub const ADDRESS_ZOOM: f64 = 17.0;
/// How many hits a search lists.
const MAX_HITS: u32 = 8;
/// What the command line asked for.
#[derive(Clone, Debug, PartialEq)]
pub struct Options {
pub server: String,
pub region: String,
pub start_3d: bool,
/// `--at lon,lat,zoom`: open there instead of on the whole region.
pub at: Option<[f64; 3]>,
}
impl Default for Options {
fn default() -> Self {
Self {
server: DEFAULT_SERVER.into(),
region: DEFAULT_REGION.into(),
start_3d: false,
at: None,
}
}
}
/// The `--help` text.
pub const USAGE: &str = "\
sverigekartan — the map of Sweden from a korp map server (2D and 3D, address search)
USAGE:
sverigekartan [--server URL] [--region NAME] [--3d] [--at LON,LAT,ZOOM]
OPTIONS:
--server URL the map server (default https://karta.gunnar.rs)
--region NAME the region to show (default sweden)
--3d open in 3D
--at LON,LAT,ZOOM open at this point and slippy zoom (e.g. 18.07,59.33,13)
-h, --help this text
-V, --version the version
MOUSE: drag = pan · wheel = zoom · click = the nearest address
3D: left-drag = orbit · right/middle-drag = pan";
/// What the command line means: options, or a text to print and leave with.
#[derive(Debug, PartialEq)]
pub enum Cli {
Run(Options),
Print(String),
}
/// Read the command line (without the program name).
pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Cli, String> {
let mut o = Options::default();
let mut it = args.into_iter();
while let Some(a) = it.next() {
let (flag, inline) = match a.split_once('=') {
Some((f, v)) if f.starts_with("--") => (f.to_string(), Some(v.to_string())),
_ => (a.clone(), None),
};
let mut value = |name: &str| {
inline
.clone()
.or_else(|| it.next())
.ok_or_else(|| format!("{name} needs a value"))
};
match flag.as_str() {
"-h" | "--help" => return Ok(Cli::Print(USAGE.into())),
"-V" | "--version" => {
return Ok(Cli::Print(format!(
"sverigekartan {}",
env!("CARGO_PKG_VERSION")
)));
}
"--server" => {
let s = value("--server")?;
if !(s.starts_with("http://") || s.starts_with("https://")) {
return Err(format!("--server must be an http(s) URL, got {s:?}"));
}
o.server = s;
}
"--region" => o.region = value("--region")?,
"--3d" => o.start_3d = true,
"--at" => {
let s = value("--at")?;
let v: Vec<f64> = s
.split(',')
.map(|p| p.trim().parse::<f64>())
.collect::<Result<_, _>>()
.map_err(|_| format!("--at wants LON,LAT,ZOOM, got {s:?}"))?;
match v[..] {
[lon, lat, zoom]
if (-180.0..=180.0).contains(&lon)
&& (-85.0..=85.0).contains(&lat)
&& (0.0..=22.0).contains(&zoom) =>
{
o.at = Some([lon, lat, zoom]);
}
_ => return Err(format!("--at wants LON,LAT,ZOOM (zoom 0-22), got {s:?}")),
}
}
_ => return Err(format!("unknown argument {a:?} (see --help)")),
}
}
Ok(Cli::Run(o))
}
/// 2D or 3D.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
TwoD,
ThreeD,
}
/// A reply of the host's own requests, landed on the UI thread.
enum Landed {
Search(u64, Result<geocode::GeocodeReply, String>),
Nearest(u64, (f64, f64), Result<geocode::RevGeocodeReply, String>),
}
/// A marked place: a found address or the address nearest a click.
#[derive(Clone, Debug, PartialEq)]
pub struct Marked {
pub lonlat: (f64, f64),
pub label: String,
/// What it is: `"sökträff"`, or the click's distance to the address.
pub note: String,
}
/// **The window's state.** [`App::ui`] draws one frame; `main` and the headless shot
/// runner call it the same way.
pub struct App {
opts: Options,
transport: ThreadTransport,
clock: Rc<dyn Clock>,
mode: Mode,
map2d: Option<ServerOsm2d>,
map3d: Option<ServerOsm3d>,
search: String,
hits: Vec<Address>,
show_hits: bool,
search_note: Option<String>,
marked: Option<Marked>,
landed: Rc<RefCell<Vec<Landed>>>,
/// The latest search / nearest request (older replies are dropped) and its handle.
search_seq: u64,
search_pending: Option<Box<dyn Pending>>,
nearest_seq: u64,
nearest_pending: Option<Box<dyn Pending>>,
/// The last click each viewer reported (its own click counter).
seen_click: [u64; 2],
/// Where the search box sits (the hit list opens under it).
search_rect: egui::Rect,
}
impl App {
/// A window on `opts`; `wake` repaints when a reply lands (an egui context's
/// `request_repaint`).
#[must_use]
pub fn new(opts: Options, wake: Option<Arc<dyn Fn() + Send + Sync>>) -> Self {
let transport =
ThreadTransport::new(concat!("sverigekartan/", env!("CARGO_PKG_VERSION")), wake);
let mut app = Self {
mode: if opts.start_3d {
Mode::ThreeD
} else {
Mode::TwoD
},
opts,
transport,
clock: Rc::new(SystemClock),
map2d: None,
map3d: None,
search: String::new(),
hits: Vec::new(),
show_hits: false,
search_note: None,
marked: None,
landed: Rc::default(),
search_seq: 0,
search_pending: None,
nearest_seq: 0,
nearest_pending: None,
seen_click: [0; 2],
search_rect: egui::Rect::NOTHING,
};
let at = app.opts.at;
match app.mode {
Mode::TwoD => app.map2d = Some(app.build_2d(at)),
Mode::ThreeD => app.map3d = Some(app.build_3d(at)),
}
app
}
fn payload(&self, at: Option<[f64; 3]>) -> ServerPayload {
ServerPayload {
server: self.opts.server.clone(),
region: self.opts.region.clone(),
title: Some("Sverigekartan".into()),
view: None,
center_zoom: at,
max: 0,
}
}
fn transport(&self) -> Rc<dyn Transport> {
Rc::new(self.transport.clone())
}
fn build_2d(&self, at: Option<[f64; 3]>) -> ServerOsm2d {
let p = self.payload(at);
ServerOsm2d::new(
&p,
feed_for(&p, self.transport(), self.clock.clone()),
self.clock.clone(),
)
}
fn build_3d(&self, at: Option<[f64; 3]>) -> ServerOsm3d {
let p = self.payload(at);
ServerOsm3d::new(
&p,
feed_for(&p, self.transport(), self.clock.clone()),
self.clock.clone(),
)
}
#[must_use]
pub fn mode(&self) -> Mode {
self.mode
}
#[must_use]
pub fn options(&self) -> &Options {
&self.opts
}
/// What the shown map shows (`None` before its first framing / scene).
#[must_use]
pub fn current_view(&self) -> Option<MapView> {
match self.mode {
Mode::TwoD => self.map2d.as_ref()?.current_view(),
Mode::ThreeD => self.map3d.as_ref()?.current_view(),
}
}
/// The marked place, if any.
#[must_use]
pub fn marked(&self) -> Option<&Marked> {
self.marked.as_ref()
}
/// The last search's hits.
#[must_use]
pub fn hits(&self) -> &[Address] {
&self.hits
}
/// Is anything still on its way: a map request, a reply being decoded, a scene
/// being baked, a search or a nearest-address request?
#[must_use]
pub fn busy(&self) -> bool {
let map = match self.mode {
Mode::TwoD => self.map2d.as_ref().is_none_or(|m| {
m.feed().busy() || m.feed().decoding() || m.baking() || m.current_view().is_none()
}),
Mode::ThreeD => self.map3d.as_ref().is_none_or(|m| {
m.feed().busy() || m.feed().decoding() || m.building() || m.current_view().is_none()
}),
};
map || self.transport.in_flight() > 0
}
/// **Switch 2D ↔ 3D, keeping the place**: the other viewer opens (or moves) on the
/// point and zoom this one shows.
pub fn set_mode(&mut self, mode: Mode) {
if mode == self.mode {
return;
}
let at = self.current_view().map(|v| ViewAsk::At {
lon: v.center[0],
lat: v.center[1],
zoom: v.zoom,
});
self.mode = mode;
let at3 = at.map(|a| match a {
ViewAsk::At { lon, lat, zoom } => [lon, lat, zoom],
ViewAsk::Bbox(_) => unreachable!("built as At"),
});
match mode {
Mode::TwoD => match &mut self.map2d {
None => self.map2d = Some(self.build_2d(at3)),
Some(m) => {
if at.is_some() {
// `None` first: an ask equal to the last one is otherwise a no-op.
m.ask_view(None);
m.ask_view(at);
}
}
},
Mode::ThreeD => match &mut self.map3d {
None => self.map3d = Some(self.build_3d(at3)),
Some(m) => {
if at.is_some() {
m.ask_view(None);
m.ask_view(at);
}
}
},
}
}
/// Move the shown map to `(lon, lat)` at `zoom`.
pub fn go_to(&mut self, lon: f64, lat: f64, zoom: f64) {
let ask = Some(ViewAsk::At { lon, lat, zoom });
match self.mode {
Mode::TwoD => {
if let Some(m) = &mut self.map2d {
m.ask_view(None);
m.ask_view(ask);
}
}
Mode::ThreeD => {
if let Some(m) = &mut self.map3d {
m.ask_view(None);
m.ask_view(ask);
}
}
}
}
/// **Search for an address** (`/v1/geocode`); the hits land in a later frame.
pub fn search(&mut self, text: &str) {
let text = text.trim();
if text.is_empty() {
return;
}
self.search = text.to_string();
self.search_seq += 1;
let seq = self.search_seq;
let landed = self.landed.clone();
let url = geocode::geocode_url(&self.opts.server, &self.opts.region, text, MAX_HITS);
if let Some(p) = self.search_pending.take() {
p.cancel();
}
self.search_note = Some("söker …".into());
self.search_pending = Some(self.transport.get(
&url,
Box::new(move |o: Outcome| {
landed.borrow_mut().push(Landed::Search(
seq,
geocode::read_geocode(o).map_err(|e| e.to_string()),
));
}),
));
}
/// **The address nearest `(lon, lat)`** (`/v1/revgeocode`); it is marked when it lands.
pub fn nearest(&mut self, lon: f64, lat: f64) {
self.nearest_seq += 1;
let seq = self.nearest_seq;
let landed = self.landed.clone();
let url = geocode::revgeocode_url(&self.opts.server, &self.opts.region, lon, lat);
if let Some(p) = self.nearest_pending.take() {
p.cancel();
}
self.nearest_pending = Some(self.transport.get(
&url,
Box::new(move |o: Outcome| {
landed.borrow_mut().push(Landed::Nearest(
seq,
(lon, lat),
geocode::read_revgeocode(o).map_err(|e| e.to_string()),
));
}),
));
}
/// Show search hit `i`: mark it and move there.
pub fn pick_hit(&mut self, i: usize) {
let Some(h) = self.hits.get(i).cloned() else {
return;
};
self.show_hits = false;
self.marked = Some(Marked {
lonlat: (h.lon, h.lat),
label: h.label(),
note: "sökträff".into(),
});
self.go_to(h.lon, h.lat, ADDRESS_ZOOM);
}
/// Hand landed replies (map and own) to their owners.
fn take_replies(&mut self) {
self.transport.pump();
let landed: Vec<Landed> = std::mem::take(&mut *self.landed.borrow_mut());
for l in landed {
match l {
Landed::Search(seq, r) if seq == self.search_seq => {
self.search_pending = None;
match r {
Ok(g) if g.hits.is_empty() => {
self.hits.clear();
self.search_note = Some(format!("inga träffar för {:?}", g.query));
}
Ok(g) => {
self.hits = g.hits;
self.search_note = None;
self.show_hits = true;
self.pick_hit(0);
self.show_hits = self.hits.len() > 1;
}
Err(e) => {
self.hits.clear();
self.search_note = Some(e);
}
}
}
Landed::Nearest(seq, (lon, lat), r) if seq == self.nearest_seq => {
self.nearest_pending = None;
self.marked = Some(match r {
Ok(g) => match g.hit {
Some(h) => Marked {
lonlat: (h.lon, h.lat),
label: h.label(),
note: format!("närmast klicket, {:.0} m bort", g.distance_m),
},
None => Marked {
lonlat: (lon, lat),
label: "ingen adress".into(),
note: String::new(),
},
},
Err(e) => Marked {
lonlat: (lon, lat),
label: format!("{lat:.5}, {lon:.5}"),
note: e,
},
});
}
_ => {}
}
}
}
/// A new click the shown viewer reported → ask for the nearest address.
fn read_click(&mut self) {
let (v, slot) = match self.mode {
Mode::TwoD => (self.map2d.as_ref().map(Facet::host_value), 0),
Mode::ThreeD => (self.map3d.as_ref().map(Facet::host_value), 1),
};
let Some(c) = v
.as_ref()
.and_then(|v| v.get("clicked"))
.filter(|c| !c.is_null())
else {
return;
};
let (Some(lon), Some(lat), Some(seq)) =
(c["lon"].as_f64(), c["lat"].as_f64(), c["seq"].as_u64())
else {
return;
};
if seq != self.seen_click[slot] {
self.seen_click[slot] = seq;
self.show_hits = false;
self.nearest(lon, lat);
}
}
/// The marked place's pin, over the map.
fn paint_mark(&self, ui: &egui::Ui) {
let Some(m) = &self.marked else {
return;
};
let at: Option<Pos2> = match self.mode {
Mode::TwoD => self.map2d.as_ref().and_then(|v| {
let pane = v.view().pane_rect();
v.current_view()?;
let (x, y) = v.view().frame().project(m.lonlat.0, m.lonlat.1);
Some(Pos2::new(pane.min.x + x, pane.min.y + y)).filter(|p| pane.contains(*p))
}),
Mode::ThreeD => self.map3d.as_ref().and_then(|v| {
let map = v.map();
let r = map.painted_rect()?;
let [x, z] = map.design_from_lonlat(m.lonlat.0, m.lonlat.1)?;
let c = r.center();
let p = map.render_camera().project(
facett_map3d::V3::new(x, 0.0, z),
(c.x, c.y),
r.height() * 0.5,
);
Some(Pos2::new(p.x, p.y)).filter(|q| p.visible && r.contains(*q))
}),
};
let Some(p) = at else {
return;
};
let painter = ui.painter();
let red = Color32::from_rgb(220, 40, 40);
painter.line_segment([p, p - egui::vec2(0.0, 22.0)], Stroke::new(3.0, red));
painter.circle(
p - egui::vec2(0.0, 26.0),
8.0,
red,
Stroke::new(2.0, Color32::WHITE),
);
let font = FontId::proportional(15.0);
let text_pos = p + egui::vec2(12.0, -26.0);
let galley = painter.layout_no_wrap(m.label.clone(), font, Color32::WHITE);
let bg = egui::Rect::from_min_size(
text_pos - egui::vec2(4.0, galley.size().y * 0.5 + 3.0),
galley.size() + egui::vec2(8.0, 6.0),
);
painter.rect_filled(bg, 4.0, Color32::from_black_alpha(190));
painter.galley(bg.min + egui::vec2(4.0, 3.0), galley, Color32::WHITE);
}
/// The bar on top: name, 2D/3D, the address search.
fn top_bar(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
ui.heading("Sverigekartan");
ui.separator();
let mut mode = self.mode;
ui.selectable_value(&mut mode, Mode::TwoD, "2D");
ui.selectable_value(&mut mode, Mode::ThreeD, "3D");
if mode != self.mode {
self.set_mode(mode);
}
ui.separator();
let edit = ui.add(
egui::TextEdit::singleline(&mut self.search)
.hint_text("Sök adress, t.ex. Sveavägen 44 Stockholm")
.desired_width(320.0),
);
self.search_rect = edit.rect;
let enter = edit.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
if ui.button("Sök").clicked() || enter {
let text = self.search.clone();
self.search(&text);
}
if !self.hits.is_empty()
&& ui
.selectable_label(self.show_hits, format!("{} träffar", self.hits.len()))
.clicked()
{
self.show_hits = !self.show_hits;
}
if let Some(n) = &self.search_note {
ui.weak(n);
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.weak(&self.opts.server);
});
});
}
/// The bar at the bottom: the marked place.
fn bottom_bar(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| match &self.marked {
Some(m) => {
ui.strong(&m.label);
if !m.note.is_empty() {
ui.weak(&m.note);
}
ui.weak(format!("{:.5}, {:.5}", m.lonlat.1, m.lonlat.0));
if ui.small_button("Rensa").clicked() {
self.marked = None;
}
}
None => {
ui.weak("Klicka på kartan för närmaste adress");
}
});
}
fn hit_list(&mut self, ui: &egui::Ui) {
if !self.show_hits || self.hits.is_empty() {
return;
}
let mut pick = None;
egui::Area::new(egui::Id::unique("sverigekartan-hits"))
.fixed_pos(self.search_rect.left_bottom() + egui::vec2(0.0, 4.0))
.show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
for (i, h) in self.hits.iter().enumerate() {
// An address with no town says where it is.
let text = if h.city.is_empty() && h.postcode.is_empty() {
format!("{} ({:.3}, {:.3})", h.label(), h.lat, h.lon)
} else {
h.label()
};
if ui.selectable_label(false, text).clicked() {
pick = Some(i);
}
}
});
});
if let Some(i) = pick {
self.pick_hit(i);
}
}
/// **One frame.**
pub fn ui(&mut self, ui: &mut egui::Ui) {
self.take_replies();
egui::Panel::top("sverigekartan-top").show(ui, |ui| self.top_bar(ui));
egui::Panel::bottom("sverigekartan-bottom").show(ui, |ui| self.bottom_bar(ui));
egui::CentralPanel::no_frame().show(ui, |ui| {
match self.mode {
Mode::TwoD => {
if let Some(m) = &mut self.map2d {
Facet::ui(m, ui);
}
}
Mode::ThreeD => {
if let Some(m) = &mut self.map3d {
Facet::ui(m, ui);
}
}
}
self.read_click();
self.paint_mark(ui);
});
self.hit_list(ui);
if self.transport.in_flight() > 0 {
ui.ctx()
.request_repaint_after(std::time::Duration::from_millis(100));
}
}
}
/// Install facett's GPU render paths for both viewers on the device eframe (or a headless
/// harness) renders with. Without them the viewers draw on the CPU painter.
pub fn install_gpu(rs: &egui_wgpu::RenderState) {
facett_map::gpu::install_renderer(rs);
facett_map3d::gpu::install_renderer(rs);
}
#[cfg(test)]
mod tests {
use super::*;
fn args(a: &[&str]) -> Result<Cli, String> {
parse_args(a.iter().map(|s| s.to_string()))
}
#[test]
fn the_command_line_reads_server_region_mode_and_place() {
assert_eq!(args(&[]).unwrap(), Cli::Run(Options::default()));
let Cli::Run(o) = args(&[
"--server",
"http://127.0.0.1:8765",
"--region=se",
"--3d",
"--at",
"18.07,59.33,13",
])
.unwrap() else {
panic!("run");
};
assert_eq!(o.server, "http://127.0.0.1:8765");
assert_eq!(o.region, "se");
assert!(o.start_3d);
assert_eq!(o.at, Some([18.07, 59.33, 13.0]));
assert!(matches!(args(&["--help"]).unwrap(), Cli::Print(t) if t.contains("--server")));
assert!(args(&["--server", "karta.gunnar.rs"]).is_err());
assert!(args(&["--at", "18,59"]).is_err());
assert!(args(&["--bogus"]).is_err());
assert!(args(&["--server"]).is_err());
}
}