use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use geojson::{GeoJson, GeometryValue};
use mln_builtins::sources::geojson::{GeoJSONData, create_geojson_data_in, set_data};
use mln_builtins::sources::image::set_image;
use mln_style::bitmap::PremultipliedImage;
use mln_style::crs::WorldMapping;
use mln_style::error::Error;
use mln_style::expression::Functions;
use mln_style::geo::{LatLng, LatLngBounds};
use mln_style::hash::HashMap;
use mln_style::image::StyleImage;
use mln_style::range::Range;
use mln_style::source::SourceData;
use mln_style::sources::image::ImageSourceOptions;
use mln_style::sources::{GeoJSONOptions, GeoJsonSourceType, ImageSourceType, geojson_source};
use mln_style::tileset::{RasterEncoding, Scheme, VectorEncoding};
use mln_style::{Edit, Source, SourceInstance, TransitionOptions};
use crate::completion::{Completion, Resolver};
use crate::map::{Applied, Map, MapEntry, MapId, apply_command, flush, missing_map, style_not_loaded};
use crate::runtime::{Background, Outbox, RuntimeCore, post};
#[derive(Clone, Debug, PartialEq)]
pub struct SourceTiles {
pub urls: Vec<String>,
pub zoom_range: Range<u8>,
pub scheme: Scheme,
pub bounds: Option<LatLngBounds>,
pub vector_encoding: Option<VectorEncoding>,
pub raster_encoding: Option<RasterEncoding>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct GeoJsonSourceOptions {
pub min_zoom: u8,
pub max_zoom: u8,
pub tolerance: f64,
pub buffer: u16,
pub line_metrics: bool,
pub cluster: bool,
pub cluster_radius: u16,
pub cluster_max_zoom: u8,
pub cluster_min_points: usize,
pub cluster_properties: Option<String>,
pub attribution: Option<String>,
}
impl Default for GeoJsonSourceOptions {
fn default() -> Self {
GeoJsonSourceOptions::from_core(&GeoJSONOptions::default())
}
}
impl GeoJsonSourceOptions {
fn from_core(options: &GeoJSONOptions) -> Self {
GeoJsonSourceOptions {
min_zoom: options.minzoom,
max_zoom: options.maxzoom,
tolerance: options.tolerance,
buffer: options.buffer,
line_metrics: options.line_metrics,
cluster: options.cluster,
cluster_radius: options.cluster_radius,
cluster_max_zoom: options.cluster_max_zoom,
cluster_min_points: options.cluster_min_points,
cluster_properties: cluster_properties_json(options),
attribution: options.attribution.clone(),
}
}
fn check(&self) -> Result<(), Error> {
if self.max_zoom > 24 {
return Err(Error::invalid_argument("max_zoom must be an integer within [0, 24]"));
}
if self.cluster_max_zoom > 30 {
return Err(Error::invalid_argument("cluster_max_zoom must be an integer within [0, 30]"));
}
if self.min_zoom > self.max_zoom {
return Err(Error::invalid_argument("min_zoom must be less than or equal to max_zoom"));
}
if !self.tolerance.is_finite() || self.tolerance < 0.0 {
return Err(Error::invalid_argument("tolerance must be finite and non-negative"));
}
if self.buffer > 512 {
return Err(Error::invalid_argument("buffer must be at most 512"));
}
if self.cluster_radius > 4095 {
return Err(Error::invalid_argument("cluster_radius must be at most 4095"));
}
Ok(())
}
pub fn check_cluster_properties(&self, functions: &Arc<Functions>) -> Result<(), Error> {
self.cluster_properties.as_deref().map_or(Ok(()), |json| parse_cluster_properties(json, functions).map(drop))
}
fn into_core(self, functions: &Arc<Functions>) -> Result<GeoJSONOptions, Error> {
let cluster_properties = match &self.cluster_properties {
Some(json) => parse_cluster_properties(json, functions)?,
None => mln_style::sources::geojson::ClusterProperties::default(),
};
Ok(GeoJSONOptions {
minzoom: self.min_zoom,
maxzoom: self.max_zoom,
tolerance: self.tolerance,
buffer: self.buffer,
line_metrics: self.line_metrics,
cluster: self.cluster,
cluster_radius: self.cluster_radius,
cluster_max_zoom: self.cluster_max_zoom,
cluster_min_points: self.cluster_min_points,
cluster_properties,
attribution: self.attribution,
..GeoJSONOptions::default()
})
}
}
fn parse_cluster_properties(
json: &str,
functions: &Arc<Functions>,
) -> Result<mln_style::sources::geojson::ClusterProperties, Error> {
let value: serde_json::Value = serde_json::from_str(json)
.map_err(|error| Error::invalid_argument(format!("cluster_properties is not valid JSON: {error}")))?;
if !value.is_object() {
return Err(Error::invalid_argument("cluster_properties must contain a JSON object"));
}
let wrapper = serde_json::json!({ "clusterProperties": value });
let mut error = mln_style::conversion::Error::default();
let options = mln_style::conversion::convert_geojson_options(
&mln_style::conversion::Convertible::from(&wrapper),
functions,
&mut error,
)
.ok_or_else(|| Error::invalid_argument(format!("GeoJSON source options: {}", error.message)))?;
Ok(options.cluster_properties)
}
#[derive(Clone, Debug)]
pub struct SourceInfo {
pub id: String,
pub source_type: &'static str,
pub is_volatile: bool,
pub attribution: Option<String>,
pub url: Option<String>,
pub tiles: Option<SourceTiles>,
pub tile_size: Option<u16>,
pub vector_encoding: Option<VectorEncoding>,
pub geojson: Option<GeoJsonSourceOptions>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct LayerInfo {
pub id: String,
pub layer_type: &'static str,
pub source_id: Option<String>,
pub source_layer: Option<String>,
pub min_zoom: Option<f64>,
pub max_zoom: Option<f64>,
pub visible: bool,
}
struct GeoJsonUpdate {
instance: SourceInstance,
building: Option<(u64, Resolver<Applied>)>,
waiting: Option<(GeoJson, Resolver<Applied>)>,
}
#[derive(Default)]
pub(crate) struct GeoJsonUpdates(HashMap<String, GeoJsonUpdate>);
pub(crate) fn reconcile(entry: &mut MapEntry, outbox: &mut Outbox) {
let map = &entry.core;
entry.geojson_updates.0.retain(|id, update| {
if map.source(id).is_some_and(|found| found.instance() == update.instance) {
return true;
}
let cancelled = || Err(Error::cancelled("the source left the style before its data was ready"));
if let Some((_, resolver)) = update.building.take() {
outbox.resolve(resolver, cancelled());
}
if let Some((_, resolver)) = update.waiting.take() {
outbox.resolve(resolver, cancelled());
}
false
});
}
pub(crate) fn release(entry: &mut MapEntry, outbox: &mut Outbox) {
for (_, mut update) in entry.geojson_updates.0.drain() {
let cancelled = || Err(Error::cancelled("the map was released before the data was ready"));
if let Some((_, resolver)) = update.building.take() {
outbox.resolve(resolver, cancelled());
}
if let Some((_, resolver)) = update.waiting.take() {
outbox.resolve(resolver, cancelled());
}
}
}
fn quote(id: &str) -> String {
format!("\"{id}\"")
}
fn require_loaded(map: &mln_engine::map::Map) -> Result<(), Error> {
if map.style_document_loaded() { Ok(()) } else { Err(style_not_loaded()) }
}
fn source_not_found(id: &str) -> Error {
Error::not_found(format!("source {} does not exist", quote(id)))
}
fn find_source<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a Source, Error> {
map.source(id).ok_or_else(|| source_not_found(id))
}
fn not_a(id: &str, kind: &str) -> Error {
Error::invalid_argument(format!("source {} is not {kind}", quote(id)))
}
fn geojson_data<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a SourceData<GeoJsonSourceType>, Error> {
SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "a GeoJSON source"))
}
fn image_data<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a SourceData<ImageSourceType>, Error> {
SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "an image source"))
}
fn require_new_source(map: &mln_engine::map::Map, id: &str) -> Result<(), Error> {
require_loaded(map)?;
if map.source(id).is_some() {
return Err(Error::already_exists(format!("source {} already exists", quote(id))));
}
Ok(())
}
fn cluster_properties_json(options: &GeoJSONOptions) -> Option<String> {
if options.cluster_properties.is_empty() {
return None;
}
let members = options
.cluster_properties
.iter()
.map(|(key, (map, reduce))| {
let pair = mln_style::feature::Value::Array(vec![reduce.serialize(), map.serialize()]);
(key.clone(), mln_style::conversion::value_to_json(&pair))
})
.collect::<serde_json::Map<_, _>>();
Some(serde_json::Value::Object(members).to_string())
}
fn source_info(registry: &mln_engine::Registry, source: &Source) -> SourceInfo {
let summary = registry.source_summary(source);
SourceInfo {
id: source.id().to_owned(),
source_type: source.info().name,
is_volatile: source.common().volatile,
attribution: registry.source_attribution(source).filter(|attribution| !attribution.is_empty()),
url: summary.url,
tiles: summary.inline_tileset.map(|tileset| SourceTiles {
urls: tileset.tiles,
zoom_range: tileset.zoom_range,
scheme: tileset.scheme,
bounds: tileset.bounds,
vector_encoding: tileset.vector_encoding,
raster_encoding: tileset.raster_encoding,
}),
tile_size: summary.tile_size,
vector_encoding: summary.vector_encoding,
geojson: summary.geojson.map(|options| GeoJsonSourceOptions::from_core(&options)),
}
}
fn layer_info(layer: &mln_style::Layer) -> LayerInfo {
LayerInfo {
id: layer.id().to_owned(),
layer_type: layer.info().name,
source_id: Some(layer.source_id()).filter(|id| !id.is_empty()).map(str::to_owned),
source_layer: Some(layer.source_layer()).filter(|id| !id.is_empty()).map(str::to_owned),
min_zoom: Some(layer.min_zoom()).filter(|zoom| zoom.is_finite()),
max_zoom: Some(layer.max_zoom()).filter(|zoom| zoom.is_finite()),
visible: layer.visibility() != mln_style::types::VisibilityType::None,
}
}
pub(crate) fn parse_geojson(json: &str) -> Result<GeoJson, Error> {
serde_json::from_str(json).map_err(|error| {
let what = if error.is_data() { "invalid" } else { "not valid JSON" };
Error::invalid_argument(format!("GeoJSON data is {what}: {error}"))
})
}
fn check_clusterable(geojson: &GeoJson, filtered: bool) -> Result<(), Error> {
let features = match geojson {
GeoJson::FeatureCollection(collection) => &collection.features,
other => {
let found = if matches!(other, GeoJson::Feature(_)) { "a single feature" } else { "a bare geometry" };
return Err(Error::invalid_argument(format!(
"clustered GeoJSON data requires a feature collection; the data is {found}"
)));
}
};
if filtered {
return Ok(());
}
let point = |feature: &geojson::Feature| matches!(&feature.geometry, Some(g) if matches!(g.value, GeometryValue::Point { .. }));
match features.iter().position(|feature| !point(feature)) {
None => Ok(()),
Some(index) => Err(Error::invalid_argument(format!(
"clustered GeoJSON data requires point geometry on every feature; feature {index} has {} geometry",
features[index].geometry.as_ref().map_or("no", |g| g.value.type_name())
))),
}
}
impl Map {
pub fn set_global_state_property(
&self,
name: impl Into<String>,
json: impl Into<String>,
) -> Result<Completion<Applied>, Error> {
let (name, json) = (name.into(), json.into());
self.command(move |map| map.edit_loaded_style(|style| style.set_global_state_property_json(&name, &json)))
}
pub fn global_state(&self) -> Result<Completion<String>, Error> {
self.query(|map| Ok(map.style().global_state_json()))
}
pub fn style_source(&self, source_id: impl Into<String>) -> Result<Completion<Option<SourceInfo>>, Error> {
let source_id = source_id.into();
self.query(move |map| Ok(map.source(&source_id).map(|source| source_info(map.registry(), source))))
}
pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
self.query(|map| Ok(map.sources().map(|source| source_info(map.registry(), source)).collect()))
}
pub fn set_style_source_volatile(
&self,
source_id: impl Into<String>,
is_volatile: bool,
) -> Result<Completion<Applied>, Error> {
let source_id = source_id.into();
self.command(move |map| {
require_loaded(map)?;
let mut common = *find_source(map, &source_id)?.common();
common.volatile = is_volatile;
map.edit_style(|style| style.apply(Edit::SetSourceCommon { id: source_id, common }))
})
}
pub fn add_geojson_source(
&self,
source_id: impl Into<String>,
options: GeoJsonSourceOptions,
) -> Result<Completion<Applied>, Error> {
options.check()?;
let source_id = source_id.into();
self.command(move |map| {
let functions = Arc::clone(map.style().registry().functions());
let options = options.into_core(&functions)?;
require_new_source(map, &source_id)?;
map.add_source(geojson_source(&source_id, Arc::new(options)))
})
}
pub fn set_geojson_source_url(
&self,
source_id: impl Into<String>,
url: impl Into<String>,
) -> Result<Completion<Applied>, Error> {
let (source_id, url) = (source_id.into(), url.into());
self.send(
move |entry, outbox| {
require_loaded(&entry.core)?;
let edit = GeoJsonSourceType::set_url(source_id.clone(), url);
entry.core.edit_style(|style| style.apply(edit))?;
if let Some((_, resolver)) =
entry.geojson_updates.0.get_mut(&source_id).and_then(|update| update.waiting.take())
{
outbox.resolve(resolver, Err(Error::cancelled("the source's URL replaced its data")));
}
Ok(())
},
|(), entry| entry.applied(),
)
}
pub fn set_geojson_source_data(
&self,
source_id: impl Into<String>,
json: impl Into<String>,
) -> Result<Completion<Applied>, Error> {
let (source_id, json) = (source_id.into(), json.into());
self.post(move |core, outbox, id, sequence, resolver| {
if !core.maps.contains_key(&id) {
return outbox.resolve(resolver, Err(missing_map()));
}
let background = core.background();
apply_command(
core,
id,
sequence,
outbox,
move |entry, outbox| match queue_geojson(entry, id, &source_id, &json, resolver, background, outbox) {
Ok(installed) => installed,
Err((error, resolver)) => {
outbox.resolve(resolver, Err(error));
None
}
},
|_, installed, applied, outbox| {
if let Some(resolver) = installed {
outbox.resolve(resolver, Ok(applied));
}
},
);
})
}
pub fn set_geojson_source_synchronous_tiling(
&self,
source_id: impl Into<String>,
enabled: bool,
) -> Result<Completion<Applied>, Error> {
let source_id = source_id.into();
self.command(move |map| {
require_loaded(map)?;
map.edit_style(|style| style.apply(GeoJsonSourceType::set_synchronous(source_id, enabled)))
})
}
pub fn set_style_image(&self, image: StyleImage) -> Result<Completion<Applied>, Error> {
self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::AddImage(Arc::new(image)))))
}
pub fn remove_style_image(&self, image_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
let image_id = image_id.into();
self.command(move |map| {
map.edit_loaded_style(|style| {
if style.image(&image_id).is_none() {
return Err(Error::not_found(format!("style image {} does not exist", quote(&image_id))));
}
style.apply(Edit::RemoveImage(image_id))
})
})
}
pub fn style_image(&self, image_id: impl Into<String>) -> Result<Completion<Option<Arc<StyleImage>>>, Error> {
let image_id = image_id.into();
self.query(move |map| Ok(map.style().image(&image_id).cloned()))
}
pub fn add_image_source(
&self,
source_id: impl Into<String>,
coordinates: [LatLng; 4],
image: PremultipliedImage,
) -> Result<Completion<Applied>, Error> {
let source_id = source_id.into();
self.command(move |map| {
require_new_source(map, &source_id)?;
let options = ImageSourceOptions { url: None, coordinates };
let data = SourceData::<ImageSourceType>::with_description(options, Arc::new(image));
map.add_source(Source::new(&source_id, data))
})
}
pub fn set_image_source_url(
&self,
source_id: impl Into<String>,
url: impl Into<String>,
) -> Result<Completion<Applied>, Error> {
let (source_id, url) = (source_id.into(), url.into());
self.command(move |map| {
require_loaded(map)?;
map.edit_style(|style| style.apply(ImageSourceType::set_url(source_id, url)))
})
}
pub fn set_image_source_image(
&self,
source_id: impl Into<String>,
image: PremultipliedImage,
) -> Result<Completion<Applied>, Error> {
let source_id = source_id.into();
self.command(move |map| {
require_loaded(map)?;
map.edit_style(|style| style.apply(set_image(source_id, image)))
})
}
pub fn set_image_source_coordinates(
&self,
source_id: impl Into<String>,
coordinates: [LatLng; 4],
) -> Result<Completion<Applied>, Error> {
let source_id = source_id.into();
self.command(move |map| {
require_loaded(map)?;
map.edit_style(|style| style.apply(ImageSourceType::set_coordinates(source_id, coordinates)))
})
}
pub fn image_source_coordinates(&self, source_id: impl Into<String>) -> Result<Completion<[LatLng; 4]>, Error> {
let source_id = source_id.into();
self.query(move |map| Ok(image_data(map, &source_id)?.options.coordinates))
}
pub fn style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Option<LayerInfo>>, Error> {
let layer_id = layer_id.into();
self.query(move |map| Ok(map.style().layer(&layer_id).map(layer_info)))
}
pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
self.query(|map| Ok(map.style().layers().map(layer_info).collect()))
}
pub fn move_style_layer(
&self,
layer_id: impl Into<String>,
before_layer_id: Option<String>,
) -> Result<Completion<Applied>, Error> {
let layer_id = layer_id.into();
self.command(move |map| map.edit_loaded_style(|style| style.move_layer(&layer_id, before_layer_id.as_deref())))
}
pub fn set_style_transition_options(&self, options: TransitionOptions) -> Result<Completion<Applied>, Error> {
self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::SetTransition(options))))
}
pub fn style_transition_options(&self) -> Result<Completion<TransitionOptions>, Error> {
self.query(|map| Ok(map.style().transition_options()))
}
}
fn queue_geojson(
entry: &mut MapEntry,
map_id: MapId,
source_id: &str,
json: &str,
resolver: Resolver<Applied>,
background: Background,
outbox: &mut Outbox,
) -> Result<Option<Resolver<Applied>>, (Error, Resolver<Applied>)> {
let found = (|| {
require_loaded(&entry.core)?;
let data = geojson_data(&entry.core, source_id)?;
let geojson = parse_geojson(json)?;
if data.options.options.cluster {
check_clusterable(&geojson, data.options.options.filter.is_some())?;
}
let instance = find_source(&entry.core, source_id)?.instance();
let building = BuildFor::new(&entry.core, &data.options.options);
Ok((instance, data.load, building, data.options.synchronous_update, geojson))
})();
let (instance, load, building, synchronous, geojson) = match found {
Ok(found) => found,
Err(error) => return Err((error, resolver)),
};
if synchronous {
return match building.build(geojson) {
Ok(data) => {
let edit = set_data(source_id, Some(data));
match entry.core.edit_style(|style| style.apply(edit)) {
Ok(()) => Ok(Some(resolver)),
Err(error) => Err((error, resolver)),
}
}
Err(error) => Err((error, resolver)),
};
}
let update = entry.geojson_updates.0.entry(source_id.to_owned()).or_insert_with(|| GeoJsonUpdate {
instance,
building: None,
waiting: None,
});
if update.building.is_none() {
update.instance = instance;
start_geojson(update, map_id, source_id.to_owned(), (building, load), geojson, resolver, background);
} else if let Some((_, replaced)) = update.waiting.replace((geojson, resolver)) {
outbox.resolve(replaced, Err(Error::cancelled("newer data for the source replaced it")));
}
Ok(None)
}
struct BuildFor {
options: Arc<GeoJSONOptions>,
world: WorldMapping,
}
impl BuildFor {
fn new(map: &mln_engine::map::Map, options: &Arc<GeoJSONOptions>) -> Self {
BuildFor { options: Arc::clone(options), world: map.transform_state().view().world().clone() }
}
fn build(&self, geojson: GeoJson) -> Result<Arc<dyn GeoJSONData>, Error> {
create_geojson_data_in(geojson, &self.options, &self.world)
}
}
fn start_geojson(
update: &mut GeoJsonUpdate,
map_id: MapId,
source_id: String,
(building, load): (BuildFor, u64),
geojson: GeoJson,
resolver: Resolver<Applied>,
background: Background,
) {
static BUILDS: AtomicU64 = AtomicU64::new(0);
let build = BUILDS.fetch_add(1, Ordering::Relaxed);
update.building = Some((build, resolver));
let next = background.clone();
background.pool.spawn(move || {
let data = building.build(geojson);
post(&background.queue, move |core, outbox| {
install_geojson(core, map_id, &source_id, (build, load), data, next, outbox);
});
});
}
fn current_geojson(map: &mln_engine::map::Map, id: &str, instance: SourceInstance) -> Option<(BuildFor, u64)> {
let source = map.source(id).filter(|source| source.instance() == instance)?;
let data = SourceData::<GeoJsonSourceType>::recover(source)?;
Some((BuildFor::new(map, &data.options.options), data.load))
}
fn install_geojson(
core: &mut RuntimeCore,
map_id: MapId,
source_id: &str,
(build, load): (u64, u64),
data: Result<Arc<dyn GeoJSONData>, Error>,
background: Background,
outbox: &mut Outbox,
) {
flush(core, map_id, outbox);
let Some(entry) = core.maps.get_mut(&map_id) else { return };
let Some(update) = entry.geojson_updates.0.get_mut(source_id) else { return };
let Some((_, resolver)) = update.building.take_if(|(building, _)| *building == build) else { return };
let current = current_geojson(&entry.core, source_id, update.instance);
let installed = match data {
Err(error) => Err(error),
Ok(_) if current.as_ref().is_none_or(|(_, current_load)| *current_load != load) => {
Err(Error::cancelled("the source's data was replaced before this data was ready"))
}
Ok(data) => {
let edit = set_data(source_id, Some(data));
entry.core.edit_style(|style| style.apply(edit))
}
};
match (update.waiting.take(), current_geojson(&entry.core, source_id, update.instance)) {
(Some((geojson, next)), Some(current)) => {
start_geojson(update, map_id, source_id.to_owned(), current, geojson, next, background);
}
(Some((_, next)), None) => outbox.resolve(next, Err(Error::cancelled("the source left the style"))),
(None, _) => {
entry.geojson_updates.0.remove(source_id);
}
}
flush(core, map_id, outbox);
let Some(entry) = core.maps.get(&map_id) else { return };
outbox.resolve(resolver, installed.map(|()| entry.applied()));
}