use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Weak};
use geojson::{GeoJson, GeometryValue};
use mln_style::expression::Functions;
use mln_style::image::Impl as StyleImage;
use mln_style::source_type::{SourceData, StyleSourceType};
use mln_style::sources::custom_geometry_source::{self, TileOptions};
use mln_style::sources::geojson::{GeoJSONData, GeoJSONDataBuilder};
use mln_style::sources::image::ImageSourceOptions;
use mln_style::sources::{
CustomGeometrySourceHandle, CustomGeometrySourceType, CustomVectorSourceHandle, CustomVectorSourceType,
GeoJSONOptions, GeoJsonSourceType, ImageSourceType, RasterDemSourceType, RasterSourceType, TileDataFormat,
VectorSourceType, custom_vector_source, geojson_source,
};
use mln_style::{Edit, Source, SourceInstance, TransitionOptions};
use mln_tile_id::CanonicalTileID;
use mln_util::error::Error;
use mln_util::geo::{LatLng, LatLngBounds};
use mln_util::hash::HashMap;
use mln_util::image::PremultipliedImage;
use mln_util::pool::Pool;
use mln_util::range::Range;
use mln_util::tileset::{RasterEncoding, Scheme, VectorEncoding};
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, Copy, Debug, PartialEq, Eq)]
pub enum SourceKind {
Vector,
Raster,
RasterDem,
GeoJson,
Image,
CustomGeometry,
CustomVector,
}
#[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_conversion::Error::default();
let options = mln_style::conversion::convert_geojson_options(
&mln_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 kind: SourceKind,
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,
}
pub struct CustomSourceCallbacks {
pub fetch_tile: Box<dyn Fn(CanonicalTileID) + Send + Sync>,
pub cancel_tile: Option<Box<dyn Fn(CanonicalTileID) + Send + Sync>>,
}
impl std::fmt::Debug for CustomSourceCallbacks {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CustomSourceCallbacks")
.field("cancel_tile", &self.cancel_tile.is_some())
.finish_non_exhaustive()
}
}
fn tile_functions(
callbacks: &Arc<CustomSourceCallbacks>,
) -> (Option<mln_style::custom_tile_loader::TileFunction>, Option<mln_style::custom_tile_loader::TileFunction>) {
let fetch: Weak<CustomSourceCallbacks> = Arc::downgrade(callbacks);
let fetch = Arc::new(move |tile: &CanonicalTileID| {
if let Some(callbacks) = fetch.upgrade() {
(callbacks.fetch_tile)(*tile);
}
});
let cancel = callbacks.cancel_tile.as_ref().map(|_| {
let cancel = Arc::downgrade(callbacks);
let cancel: mln_style::custom_tile_loader::TileFunction = Arc::new(move |tile: &CanonicalTileID| {
if let Some(callback) = cancel.upgrade().as_ref().and_then(|callbacks| callbacks.cancel_tile.as_ref()) {
callback(*tile);
}
});
cancel
});
(Some(fetch), cancel)
}
struct CallbackSource {
id: String,
instance: SourceInstance,
_callbacks: Arc<CustomSourceCallbacks>,
}
#[derive(Default)]
pub(crate) struct CallbackSources(Vec<CallbackSource>);
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;
let present = |id: &str, instance: SourceInstance| map.source(id).is_some_and(|found| found.instance() == instance);
let (kept, gone): (Vec<_>, Vec<_>) =
std::mem::take(&mut entry.callback_sources.0).into_iter().partition(|held| present(&held.id, held.instance));
entry.callback_sources.0 = kept;
if !gone.is_empty() {
outbox.push(move || drop(gone));
}
entry.geojson_updates.0.retain(|id, update| {
if present(id, 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) {
let held = std::mem::take(&mut entry.callback_sources.0);
if !held.is_empty() {
outbox.push(move || drop(held));
}
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_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_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_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_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_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(())
}
impl SourceKind {
fn of(source: &Source) -> Option<SourceKind> {
let name = source.info().name;
[
(VectorSourceType::INFO, SourceKind::Vector),
(RasterSourceType::INFO, SourceKind::Raster),
(RasterDemSourceType::INFO, SourceKind::RasterDem),
(GeoJsonSourceType::INFO, SourceKind::GeoJson),
(ImageSourceType::INFO, SourceKind::Image),
(CustomGeometrySourceType::INFO, SourceKind::CustomGeometry),
(CustomVectorSourceType::INFO, SourceKind::CustomVector),
]
.into_iter()
.find_map(|(info, kind)| (info.name == name).then_some(kind))
}
}
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 = feature::Value::Array(vec![reduce.serialize(), map.serialize()]);
(key.clone(), mln_conversion::value_to_json(&pair))
})
.collect::<serde_json::Map<_, _>>();
Some(serde_json::Value::Object(members).to_string())
}
fn source_info(source: &Source) -> Option<SourceInfo> {
let kind = SourceKind::of(source)?;
let summary = source.data().summary();
Some(SourceInfo {
id: source.id().to_owned(),
kind,
is_volatile: source.common().volatile,
attribution: source.data().attribution().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.get_id().to_owned(),
layer_type: layer.info().name,
source_id: Some(layer.get_source_id()).filter(|id| !id.is_empty()).map(str::to_owned),
source_layer: Some(layer.get_source_layer()).filter(|id| !id.is_empty()).map(str::to_owned),
min_zoom: Some(f64::from(layer.get_min_zoom())).filter(|zoom| zoom.is_finite()),
max_zoom: Some(f64::from(layer.get_max_zoom())).filter(|zoom| zoom.is_finite()),
visible: layer.get_visibility() != mln_style_types::VisibilityType::None,
}
}
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) -> 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}"
)));
}
};
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())
))),
}
}
fn feature_collection(geojson: GeoJson) -> GeoJson {
match geojson {
GeoJson::FeatureCollection(_) => geojson,
GeoJson::Feature(feature) => GeoJson::from(vec![feature]),
GeoJson::Geometry(geometry) => GeoJson::from(vec![geojson::Feature::from(geometry)]),
}
}
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).and_then(source_info)))
}
pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
self.query(|map| Ok(map.sources().filter_map(source_info).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 add_custom_geometry_source(
&self,
source_id: impl Into<String>,
callbacks: CustomSourceCallbacks,
zoom_range: Range<u8>,
tile_options: TileOptions,
) -> Result<Completion<Applied>, Error> {
let (source_id, callbacks) = (source_id.into(), Arc::new(callbacks));
self.send(
move |entry, outbox| {
add_callback_source(entry, outbox, source_id, callbacks, |id, callbacks, pool| {
let (fetch_tile_function, cancel_tile_function) = tile_functions(callbacks);
let options = custom_geometry_source::Options {
fetch_tile_function,
cancel_tile_function,
zoom_range,
tile_options,
};
custom_geometry_source::create(&id, options, pool)
.map_err(|error| Error::invalid_argument(error.to_string()))
})
},
|(), entry| entry.applied(),
)
}
pub fn add_custom_vector_source(
&self,
source_id: impl Into<String>,
callbacks: CustomSourceCallbacks,
zoom_range: Range<u8>,
) -> Result<Completion<Applied>, Error> {
let (source_id, callbacks) = (source_id.into(), Arc::new(callbacks));
self.send(
move |entry, outbox| {
add_callback_source(entry, outbox, source_id, callbacks, |id, callbacks, pool| {
let (fetch_tile_function, cancel_tile_function) = tile_functions(callbacks);
let options =
custom_vector_source::Options { fetch_tile_function, cancel_tile_function, zoom_range };
Ok(custom_vector_source::create(&id, options, pool))
})
},
|(), entry| entry.applied(),
)
}
pub fn set_custom_geometry_source_tile_data(
&self,
source_id: impl Into<String>,
tile_id: CanonicalTileID,
json: impl Into<String>,
) -> Result<Completion<Applied>, Error> {
let (source_id, json) = (source_id.into(), json.into());
self.command(move |map| {
let geojson = feature_collection(parse_geojson(&json)?);
custom_geometry(map, &source_id)?.set_tile_data(tile_id, geojson);
Ok(())
})
}
pub fn set_custom_geometry_source_tile_error(
&self,
source_id: impl Into<String>,
tile_id: CanonicalTileID,
message: impl Into<String>,
) -> Result<Completion<Applied>, Error> {
let (source_id, message) = (source_id.into(), message.into());
self.command(move |map| {
custom_geometry(map, &source_id)?.set_tile_error(tile_id, Error::native(message));
Ok(())
})
}
pub fn invalidate_custom_geometry_source_tile(
&self,
source_id: impl Into<String>,
tile_id: CanonicalTileID,
) -> Result<Completion<Applied>, Error> {
let source_id = source_id.into();
self.command(move |map| {
custom_geometry(map, &source_id)?.invalidate_tile(tile_id);
Ok(())
})
}
pub fn invalidate_custom_geometry_source_region(
&self,
source_id: impl Into<String>,
bounds: LatLngBounds,
) -> Result<Completion<Applied>, Error> {
let source_id = source_id.into();
self.command(move |map| {
custom_geometry(map, &source_id)?.invalidate_region(bounds);
Ok(())
})
}
pub fn set_custom_vector_source_tile_data(
&self,
source_id: impl Into<String>,
tile_id: CanonicalTileID,
data: Option<Vec<u8>>,
format: TileDataFormat,
) -> Result<Completion<Applied>, Error> {
let source_id = source_id.into();
self.command(move |map| {
custom_vector(map, &source_id)?.set_tile_data(tile_id, data.map(Arc::new), format);
Ok(())
})
}
pub fn set_custom_vector_source_tile_error(
&self,
source_id: impl Into<String>,
tile_id: CanonicalTileID,
message: impl Into<String>,
) -> Result<Completion<Applied>, Error> {
let (source_id, message) = (source_id.into(), message.into());
self.command(move |map| {
custom_vector(map, &source_id)?.set_tile_error(tile_id, Error::native(message));
Ok(())
})
}
pub fn invalidate_custom_vector_source_tile(
&self,
source_id: impl Into<String>,
tile_id: CanonicalTileID,
) -> Result<Completion<Applied>, Error> {
let source_id = source_id.into();
self.command(move |map| {
custom_vector(map, &source_id)?.invalidate_tile(tile_id);
Ok(())
})
}
pub fn invalidate_custom_vector_source_region(
&self,
source_id: impl Into<String>,
bounds: LatLngBounds,
) -> Result<Completion<Applied>, Error> {
let source_id = source_id.into();
self.command(move |map| {
custom_vector(map, &source_id)?.invalidate_region(bounds);
Ok(())
})
}
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.get_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().get_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(ImageSourceType::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().get_layer(&layer_id).map(layer_info)))
}
pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
self.query(|map| Ok(map.style().get_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().get_transition_options()))
}
}
fn add_callback_source(
entry: &mut MapEntry,
outbox: &mut Outbox,
id: String,
callbacks: Arc<CustomSourceCallbacks>,
make: impl FnOnce(String, &Arc<CustomSourceCallbacks>, &Pool) -> Result<Source, Error>,
) -> Result<(), Error> {
let map = &mut entry.core;
let pool = map.pool().clone();
let added = require_new_source(map, &id).and_then(|()| {
let source = make(id.clone(), &callbacks, &pool)?;
let instance = source.instance();
map.add_source(source)?;
Ok(instance)
});
match added {
Ok(instance) => {
entry.callback_sources.0.push(CallbackSource { id, instance, _callbacks: callbacks });
Ok(())
}
Err(error) => {
outbox.push(move || drop(callbacks));
Err(error)
}
}
}
fn custom_geometry(map: &mln_map::Map, id: &str) -> Result<CustomGeometrySourceHandle, Error> {
CustomGeometrySourceHandle::of(find_source(map, id)?).ok_or_else(|| not_a(id, "a custom geometry source"))
}
fn custom_vector(map: &mln_map::Map, id: &str) -> Result<CustomVectorSourceHandle, Error> {
CustomVectorSourceHandle::of(find_source(map, id)?).ok_or_else(|| not_a(id, "a custom vector source"))
}
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)?;
}
let instance = find_source(&entry.core, source_id)?.instance();
Ok((instance, data.load, data.options.data_builder(), data.options.synchronous_update, geojson))
})();
let (instance, load, builder, synchronous, geojson) = match found {
Ok(found) => found,
Err(error) => return Err((error, resolver)),
};
if synchronous {
return match builder.build(geojson) {
Ok(data) => {
let edit = GeoJsonSourceType::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(), (builder, 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)
}
fn start_geojson(
update: &mut GeoJsonUpdate,
map_id: MapId,
source_id: String,
(builder, load): (GeoJSONDataBuilder, 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 = builder.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_map::Map, id: &str, instance: SourceInstance) -> Option<(GeoJSONDataBuilder, u64)> {
let source = map.source(id).filter(|source| source.instance() == instance)?;
let data = SourceData::<GeoJsonSourceType>::recover(source)?;
Some((data.options.data_builder(), 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 = GeoJsonSourceType::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()));
}