1use std::collections::HashMap;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Weak};
7
8use geojson::GeoJSON;
9use mln_actor::scheduler;
10use mln_style::image::Impl as StyleImage;
11use mln_style::source::{Source, same_source, set_volatile};
12use mln_style::sources::custom_geometry_source::{self, TileOptions};
13use mln_style::sources::geojson_source::GeoJSONData;
14use mln_style::sources::image_source::ImageSource;
15use mln_style::sources::{
16 CustomGeometrySource, CustomVectorSource, GeoJSONOptions, GeoJSONSource, RasterDEMSource, RasterSource,
17 TileDataFormat, TileSource, UrlOrTileset, VectorSource, custom_vector_source,
18};
19use mln_style::{Style, TransitionOptions};
20use mln_tile_id::CanonicalTileID;
21use mln_util::error::Error;
22use mln_util::geo::{LatLng, LatLngBounds};
23use mln_util::image::PremultipliedImage;
24use mln_util::immutable::Immutable;
25use mln_util::range::Range;
26use mln_util::tileset::{RasterEncoding, Scheme, VectorEncoding};
27
28use crate::completion::{Completion, Resolver};
29use crate::map::{Applied, Map, MapEntry, MapId, apply_command, flush, missing_map, style_not_loaded};
30use crate::runtime::{Outbox, RuntimeCore, post};
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum SourceKind {
35 Vector,
36 Raster,
37 RasterDem,
38 GeoJson,
39 Image,
40 CustomGeometry,
41 CustomVector,
42}
43
44#[derive(Clone, Debug, PartialEq)]
46pub struct SourceTiles {
47 pub urls: Vec<String>,
48 pub zoom_range: Range<u8>,
49 pub scheme: Scheme,
50 pub bounds: Option<LatLngBounds>,
51 pub vector_encoding: Option<VectorEncoding>,
52 pub raster_encoding: Option<RasterEncoding>,
53}
54
55#[derive(Clone, Debug, PartialEq)]
58pub struct GeoJsonSourceOptions {
59 pub min_zoom: u8,
61 pub max_zoom: u8,
63 pub tolerance: f64,
65 pub buffer: u16,
67 pub line_metrics: bool,
69 pub cluster: bool,
71 pub cluster_radius: u16,
73 pub cluster_max_zoom: u8,
75 pub cluster_min_points: usize,
77 pub cluster_properties: Option<String>,
81 pub attribution: Option<String>,
82}
83
84impl Default for GeoJsonSourceOptions {
85 fn default() -> Self {
86 GeoJsonSourceOptions::from_core(&GeoJSONOptions::default())
87 }
88}
89
90impl GeoJsonSourceOptions {
91 fn from_core(options: &GeoJSONOptions) -> Self {
92 GeoJsonSourceOptions {
93 min_zoom: options.minzoom,
94 max_zoom: options.maxzoom,
95 tolerance: options.tolerance,
96 buffer: options.buffer,
97 line_metrics: options.line_metrics,
98 cluster: options.cluster,
99 cluster_radius: options.cluster_radius,
100 cluster_max_zoom: options.cluster_max_zoom,
101 cluster_min_points: options.cluster_min_points,
102 cluster_properties: cluster_properties_json(options),
103 attribution: options.attribution.clone(),
104 }
105 }
106
107 fn check(&self) -> Result<(), Error> {
110 if self.max_zoom > 24 {
113 return Err(Error::invalid_argument("max_zoom must be an integer within [0, 24]"));
114 }
115 if self.cluster_max_zoom > 30 {
116 return Err(Error::invalid_argument("cluster_max_zoom must be an integer within [0, 30]"));
117 }
118 if self.min_zoom > self.max_zoom {
119 return Err(Error::invalid_argument("min_zoom must be less than or equal to max_zoom"));
120 }
121 if !self.tolerance.is_finite() || self.tolerance < 0.0 {
122 return Err(Error::invalid_argument("tolerance must be finite and non-negative"));
123 }
124 if self.buffer > 512 {
125 return Err(Error::invalid_argument("buffer must be at most 512"));
126 }
127 if self.cluster_radius > 4095 {
128 return Err(Error::invalid_argument("cluster_radius must be at most 4095"));
129 }
130 Ok(())
131 }
132
133 pub fn check_cluster_properties(&self) -> Result<(), Error> {
139 self.cluster_properties.as_deref().map_or(Ok(()), |json| parse_cluster_properties(json).map(drop))
140 }
141
142 fn into_core(self) -> Result<GeoJSONOptions, Error> {
144 let cluster_properties = match &self.cluster_properties {
145 Some(json) => parse_cluster_properties(json)?,
146 None => mln_style::sources::geojson_source::ClusterProperties::default(),
147 };
148 Ok(GeoJSONOptions {
149 minzoom: self.min_zoom,
150 maxzoom: self.max_zoom,
151 tolerance: self.tolerance,
152 buffer: self.buffer,
153 line_metrics: self.line_metrics,
154 cluster: self.cluster,
155 cluster_radius: self.cluster_radius,
156 cluster_max_zoom: self.cluster_max_zoom,
157 cluster_min_points: self.cluster_min_points,
158 cluster_properties,
159 attribution: self.attribution,
160 ..GeoJSONOptions::default()
161 })
162 }
163}
164
165fn parse_cluster_properties(json: &str) -> Result<mln_style::sources::geojson_source::ClusterProperties, Error> {
170 let value: serde_json::Value = serde_json::from_str(json)
171 .map_err(|error| Error::invalid_argument(format!("cluster_properties is not valid JSON: {error}")))?;
172 if !value.is_object() {
173 return Err(Error::invalid_argument("cluster_properties must contain a JSON object"));
174 }
175 let wrapper = serde_json::json!({ "clusterProperties": value });
176 let mut error = mln_conversion::Error::default();
177 let options = <GeoJSONOptions as mln_style::conversion::Converter>::convert(
178 &mln_conversion::Convertible::from(&wrapper),
179 &mut error,
180 )
181 .ok_or_else(|| Error::invalid_argument(format!("GeoJSON source options: {}", error.message)))?;
182 Ok(options.cluster_properties)
183}
184
185#[derive(Clone, Debug)]
187pub struct SourceInfo {
188 pub id: String,
189 pub kind: SourceKind,
190 pub is_volatile: bool,
191 pub attribution: Option<String>,
194 pub url: Option<String>,
195 pub tiles: Option<SourceTiles>,
197 pub tile_size: Option<u16>,
199 pub vector_encoding: Option<VectorEncoding>,
201 pub geojson: Option<GeoJsonSourceOptions>,
202}
203
204#[derive(Clone, Debug, PartialEq)]
206pub struct LayerInfo {
207 pub id: String,
208 pub layer_type: &'static str,
211 pub source_id: Option<String>,
213 pub source_layer: Option<String>,
215 pub min_zoom: Option<f64>,
216 pub max_zoom: Option<f64>,
217 pub visible: bool,
218}
219
220pub struct CustomSourceCallbacks {
229 pub fetch_tile: Box<dyn Fn(CanonicalTileID) + Send + Sync>,
230 pub cancel_tile: Option<Box<dyn Fn(CanonicalTileID) + Send + Sync>>,
231}
232
233impl std::fmt::Debug for CustomSourceCallbacks {
234 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235 f.debug_struct("CustomSourceCallbacks")
236 .field("cancel_tile", &self.cancel_tile.is_some())
237 .finish_non_exhaustive()
238 }
239}
240
241fn tile_functions(
245 callbacks: &Arc<CustomSourceCallbacks>,
246) -> (Option<mln_style::custom_tile_loader::TileFunction>, Option<mln_style::custom_tile_loader::TileFunction>) {
247 let fetch: Weak<CustomSourceCallbacks> = Arc::downgrade(callbacks);
248 let fetch = Arc::new(move |tile: &CanonicalTileID| {
249 if let Some(callbacks) = fetch.upgrade() {
250 (callbacks.fetch_tile)(*tile);
251 }
252 });
253 let cancel = callbacks.cancel_tile.as_ref().map(|_| {
254 let cancel = Arc::downgrade(callbacks);
255 let cancel: mln_style::custom_tile_loader::TileFunction = Arc::new(move |tile: &CanonicalTileID| {
256 if let Some(callback) = cancel.upgrade().as_ref().and_then(|callbacks| callbacks.cancel_tile.as_ref()) {
257 callback(*tile);
258 }
259 });
260 cancel
261 });
262 (Some(fetch), cancel)
263}
264
265struct CallbackSource {
268 id: String,
269 source: Box<dyn Source>,
270 _callbacks: Arc<CustomSourceCallbacks>,
273}
274
275#[derive(Default)]
278pub(crate) struct CallbackSources(Vec<CallbackSource>);
279
280struct GeoJsonUpdate {
283 source: GeoJSONSource,
284 building: Option<(u64, Resolver<Applied>)>,
288 waiting: Option<(GeoJSON, Resolver<Applied>)>,
289}
290
291#[derive(Default)]
293pub(crate) struct GeoJsonUpdates(HashMap<String, GeoJsonUpdate>);
294
295pub(crate) fn reconcile(entry: &mut MapEntry, outbox: &mut Outbox) {
300 let style = entry.core.style();
301 let present = |id: &str, source: &dyn Source| style.get_source(id).is_some_and(|found| same_source(found, source));
302 let (kept, gone): (Vec<_>, Vec<_>) =
303 std::mem::take(&mut entry.callback_sources.0).into_iter().partition(|held| present(&held.id, &*held.source));
304 entry.callback_sources.0 = kept;
305 if !gone.is_empty() {
306 outbox.push(move || drop(gone));
307 }
308 entry.geojson_updates.0.retain(|id, update| {
309 if present(id, &update.source) {
310 return true;
311 }
312 let cancelled = || Err(Error::cancelled("the source left the style before its data was ready"));
313 if let Some((_, resolver)) = update.building.take() {
314 outbox.resolve(resolver, cancelled());
315 }
316 if let Some((_, resolver)) = update.waiting.take() {
317 outbox.resolve(resolver, cancelled());
318 }
319 false
320 });
321}
322
323pub(crate) fn release(entry: &mut MapEntry, outbox: &mut Outbox) {
326 let held = std::mem::take(&mut entry.callback_sources.0);
327 if !held.is_empty() {
328 outbox.push(move || drop(held));
329 }
330 for (_, mut update) in entry.geojson_updates.0.drain() {
331 let cancelled = || Err(Error::cancelled("the map was released before the data was ready"));
332 if let Some((_, resolver)) = update.building.take() {
333 outbox.resolve(resolver, cancelled());
334 }
335 if let Some((_, resolver)) = update.waiting.take() {
336 outbox.resolve(resolver, cancelled());
337 }
338 }
339}
340
341fn quote(id: &str) -> String {
342 format!("\"{id}\"")
343}
344
345fn require_loaded(style: &Style) -> Result<(), Error> {
346 if style.is_loaded() { Ok(()) } else { Err(style_not_loaded()) }
347}
348
349fn source_not_found(id: &str) -> Error {
350 Error::not_found(format!("source {} does not exist", quote(id)))
351}
352
353fn find_source<'a>(style: &'a Style, id: &str) -> Result<&'a dyn Source, Error> {
354 style.get_source(id).ok_or_else(|| source_not_found(id))
355}
356
357fn find_source_as<'a, T: 'static>(style: &'a Style, id: &str, kind: &str) -> Result<&'a T, Error> {
360 find_source(style, id)?
361 .as_any()
362 .downcast_ref::<T>()
363 .ok_or_else(|| Error::invalid_argument(format!("source {} is not {kind}", quote(id))))
364}
365
366fn require_new_source(style: &Style, id: &str) -> Result<(), Error> {
367 require_loaded(style)?;
368 if style.get_source(id).is_some() {
369 return Err(Error::already_exists(format!("source {} already exists", quote(id))));
370 }
371 Ok(())
372}
373
374fn tile_source(source: &dyn Source) -> Option<&TileSource> {
375 let any = source.as_any();
376 if let Some(vector) = any.downcast_ref::<VectorSource>() {
377 Some(vector.tile_source())
378 } else if let Some(raster) = any.downcast_ref::<RasterSource>() {
379 Some(raster.tile_source())
380 } else {
381 any.downcast_ref::<RasterDEMSource>().map(RasterDEMSource::tile_source)
382 }
383}
384
385fn source_kind(source: &dyn Source) -> Option<SourceKind> {
386 let any = source.as_any();
387 Some(if any.is::<VectorSource>() {
388 SourceKind::Vector
389 } else if any.is::<RasterSource>() {
390 SourceKind::Raster
391 } else if any.is::<RasterDEMSource>() {
392 SourceKind::RasterDem
393 } else if any.is::<GeoJSONSource>() {
394 SourceKind::GeoJson
395 } else if any.is::<ImageSource>() {
396 SourceKind::Image
397 } else if any.is::<CustomGeometrySource>() {
398 SourceKind::CustomGeometry
399 } else if any.is::<CustomVectorSource>() {
400 SourceKind::CustomVector
401 } else {
402 return None;
403 })
404}
405
406fn cluster_properties_json(options: &GeoJSONOptions) -> Option<String> {
408 if options.cluster_properties.is_empty() {
409 return None;
410 }
411 let members = options
412 .cluster_properties
413 .iter()
414 .map(|(key, (map, reduce))| {
415 let pair = feature::Value::Array(vec![reduce.serialize(), map.serialize()]);
416 (key.clone(), mln_conversion::value_to_json(&pair))
417 })
418 .collect::<serde_json::Map<_, _>>();
419 Some(serde_json::Value::Object(members).to_string())
420}
421
422fn source_info(source: &dyn Source) -> Option<SourceInfo> {
423 let kind = source_kind(source)?;
424 let any = source.as_any();
425 let url = if let Some(tiles) = tile_source(source) {
426 tiles.get_url()
427 } else if let Some(geojson) = any.downcast_ref::<GeoJSONSource>() {
428 geojson.get_url()
429 } else {
430 any.downcast_ref::<ImageSource>().and_then(ImageSource::get_url)
431 };
432 let geojson =
433 any.downcast_ref::<GeoJSONSource>().map(|geojson| GeoJsonSourceOptions::from_core(&geojson.get_options()));
434 let mut info = SourceInfo {
435 id: source.get_id(),
436 kind,
437 is_volatile: source.is_volatile(),
438 attribution: source.get_attribution().filter(|attribution| !attribution.is_empty()),
439 url,
440 tiles: None,
441 tile_size: None,
442 vector_encoding: None,
443 geojson,
444 };
445 if let Some(tile_source) = tile_source(source) {
446 info.tile_size = Some(tile_source.get_tile_size());
447 info.vector_encoding = any.downcast_ref::<VectorSource>().map(VectorSource::get_encoding);
448 if let UrlOrTileset::Tileset(tileset) = tile_source.get_url_or_tileset() {
449 info.vector_encoding = tileset.vector_encoding.or(info.vector_encoding);
450 info.tiles = Some(SourceTiles {
451 urls: tileset.tiles.clone(),
452 zoom_range: tileset.zoom_range,
453 scheme: tileset.scheme,
454 bounds: tileset.bounds,
455 vector_encoding: tileset.vector_encoding,
456 raster_encoding: tileset.raster_encoding,
457 });
458 }
459 }
460 Some(info)
461}
462
463fn layer_info(layer: &dyn mln_style::Layer) -> LayerInfo {
464 LayerInfo {
465 id: layer.get_id(),
466 layer_type: layer.get_type_info().type_,
467 source_id: Some(layer.get_source_id()).filter(|id| !id.is_empty()),
468 source_layer: Some(layer.get_source_layer()).filter(|id| !id.is_empty()),
469 min_zoom: Some(f64::from(layer.get_min_zoom())).filter(|zoom| zoom.is_finite()),
470 max_zoom: Some(f64::from(layer.get_max_zoom())).filter(|zoom| zoom.is_finite()),
471 visible: layer.get_visibility() != mln_style_types::VisibilityType::None,
472 }
473}
474
475fn parse_geojson(json: &str) -> Result<GeoJSON, Error> {
477 let document: serde_json::Value = serde_json::from_str(json)
478 .map_err(|error| Error::invalid_argument(format!("GeoJSON data is not valid JSON: {error}")))?;
479 let mut error = mln_conversion::Error::default();
480 mln_conversion::to_geojson(&mln_conversion::Convertible::from(&document), &mut error)
481 .ok_or_else(|| Error::invalid_argument(format!("GeoJSON data is invalid: {}", error.message)))
482}
483
484fn geometry_name(geometry: &geometry::Geometry<f64>) -> &'static str {
485 match geometry {
486 geometry::Geometry::Empty => "empty",
487 geometry::Geometry::Point(_) => "point",
488 geometry::Geometry::MultiPoint(_) => "multi-point",
489 geometry::Geometry::LineString(_) => "line string",
490 geometry::Geometry::MultiLineString(_) => "multi-line string",
491 geometry::Geometry::Polygon(_) => "polygon",
492 geometry::Geometry::MultiPolygon(_) => "multi-polygon",
493 geometry::Geometry::GeometryCollection(_) => "geometry collection",
494 }
495}
496
497fn check_clusterable(geojson: &GeoJSON) -> Result<(), Error> {
501 let features = match geojson {
502 GeoJSON::FeatureCollection(features) => features,
503 other => {
504 let found = if matches!(other, GeoJSON::Feature(_)) { "a single feature" } else { "a bare geometry" };
505 return Err(Error::invalid_argument(format!(
506 "clustered GeoJSON data requires a feature collection; the data is {found}"
507 )));
508 }
509 };
510 match features.iter().position(|feature| !matches!(feature.geometry, geometry::Geometry::Point(_))) {
511 None => Ok(()),
512 Some(index) => Err(Error::invalid_argument(format!(
513 "clustered GeoJSON data requires point geometry on every feature; feature {index} has {} geometry",
514 geometry_name(&features[index].geometry)
515 ))),
516 }
517}
518
519fn feature_collection(geojson: GeoJSON) -> GeoJSON {
522 match geojson {
523 GeoJSON::FeatureCollection(_) => geojson,
524 GeoJSON::Feature(feature) => GeoJSON::FeatureCollection(vec![feature]),
525 GeoJSON::Geometry(geometry) => GeoJSON::FeatureCollection(vec![feature::Feature::new(geometry)]),
526 }
527}
528
529impl Map {
530 pub fn set_global_state_property(
535 &self,
536 name: impl Into<String>,
537 json: impl Into<String>,
538 ) -> Result<Completion<Applied>, Error> {
539 let (name, json) = (name.into(), json.into());
540 self.command(move |map| map.style_mut().set_global_state_property_json(&name, &json))
541 }
542
543 pub fn global_state(&self) -> Result<Completion<String>, Error> {
545 self.query(|map| Ok(map.style().global_state_json()))
546 }
547
548 pub fn style_source(&self, source_id: impl Into<String>) -> Result<Completion<Option<SourceInfo>>, Error> {
552 let source_id = source_id.into();
553 self.query(move |map| Ok(map.style().get_source(&source_id).and_then(source_info)))
554 }
555
556 pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
558 self.query(|map| Ok(map.style().get_sources().into_iter().filter_map(source_info).collect()))
559 }
560
561 pub fn set_style_source_volatile(
563 &self,
564 source_id: impl Into<String>,
565 is_volatile: bool,
566 ) -> Result<Completion<Applied>, Error> {
567 let source_id = source_id.into();
568 self.command(move |map| {
569 let style = map.style_mut();
570 require_loaded(style)?;
571 set_volatile(find_source(style, &source_id)?, is_volatile);
572 Ok(())
573 })
574 }
575
576 pub fn add_geojson_source(
585 &self,
586 source_id: impl Into<String>,
587 options: GeoJsonSourceOptions,
588 ) -> Result<Completion<Applied>, Error> {
589 options.check()?;
590 let source_id = source_id.into();
591 self.command(move |map| {
592 let options = options.into_core()?;
593 let style = map.style_mut();
594 require_new_source(style, &source_id)?;
595 style.add_source(Box::new(GeoJSONSource::new(source_id, Arc::new(options))))
596 })
597 }
598
599 pub fn set_geojson_source_url(
603 &self,
604 source_id: impl Into<String>,
605 url: impl Into<String>,
606 ) -> Result<Completion<Applied>, Error> {
607 let (source_id, url) = (source_id.into(), url.into());
608 self.send(
609 move |entry, outbox| {
610 let style = entry.core.style();
611 require_loaded(style)?;
612 find_source_as::<GeoJSONSource>(style, &source_id, "a GeoJSON source")?.set_url(&url);
613 if let Some((_, resolver)) =
614 entry.geojson_updates.0.get_mut(&source_id).and_then(|update| update.waiting.take())
615 {
616 outbox.resolve(resolver, Err(Error::cancelled("the source's URL replaced its data")));
617 }
618 Ok(())
619 },
620 |(), entry| entry.applied(),
621 )
622 }
623
624 pub fn set_geojson_source_data(
642 &self,
643 source_id: impl Into<String>,
644 json: impl Into<String>,
645 ) -> Result<Completion<Applied>, Error> {
646 let (source_id, json) = (source_id.into(), json.into());
647 self.shared.send(move |core, outbox, id, sequence, resolver| {
648 if !core.maps.contains_key(&id) {
649 return outbox.resolve(resolver, Err(missing_map()));
650 }
651 let run_loop = core.run_loop.clone();
652 apply_command(
653 core,
654 id,
655 sequence,
656 outbox,
657 move |entry, outbox| match queue_geojson(entry, id, &source_id, &json, resolver, run_loop, outbox) {
658 Ok(installed) => installed,
659 Err((error, resolver)) => {
660 outbox.resolve(resolver, Err(error));
661 None
662 }
663 },
664 |_, installed, applied, outbox| {
665 if let Some(resolver) = installed {
666 outbox.resolve(resolver, Ok(applied));
667 }
668 },
669 );
670 })
671 }
672
673 pub fn set_geojson_source_synchronous_tiling(
676 &self,
677 source_id: impl Into<String>,
678 enabled: bool,
679 ) -> Result<Completion<Applied>, Error> {
680 let source_id = source_id.into();
681 self.command(move |map| {
682 let style = map.style_mut();
683 require_loaded(style)?;
684 find_source_as::<GeoJSONSource>(style, &source_id, "a GeoJSON source")?
685 .set_override_synchronous_update(enabled);
686 Ok(())
687 })
688 }
689
690 pub fn add_custom_geometry_source(
698 &self,
699 source_id: impl Into<String>,
700 callbacks: CustomSourceCallbacks,
701 zoom_range: Range<u8>,
702 tile_options: TileOptions,
703 ) -> Result<Completion<Applied>, Error> {
704 let (source_id, callbacks) = (source_id.into(), Arc::new(callbacks));
705 self.send(
706 move |entry, outbox| {
707 add_callback_source(entry, outbox, source_id, callbacks, |id, callbacks| {
708 let (fetch_tile_function, cancel_tile_function) = tile_functions(callbacks);
709 let options = custom_geometry_source::Options {
710 fetch_tile_function,
711 cancel_tile_function,
712 zoom_range,
713 tile_options,
714 };
715 let source = CustomGeometrySource::new(id, options)
716 .map_err(|error| Error::invalid_argument(error.to_string()))?;
717 Ok(Box::new(source))
718 })
719 },
720 |(), entry| entry.applied(),
721 )
722 }
723
724 pub fn add_custom_vector_source(
728 &self,
729 source_id: impl Into<String>,
730 callbacks: CustomSourceCallbacks,
731 zoom_range: Range<u8>,
732 ) -> Result<Completion<Applied>, Error> {
733 let (source_id, callbacks) = (source_id.into(), Arc::new(callbacks));
734 self.send(
735 move |entry, outbox| {
736 add_callback_source(entry, outbox, source_id, callbacks, |id, callbacks| {
737 let (fetch_tile_function, cancel_tile_function) = tile_functions(callbacks);
738 let options =
739 custom_vector_source::Options { fetch_tile_function, cancel_tile_function, zoom_range };
740 Ok(Box::new(CustomVectorSource::new(id, options)))
741 })
742 },
743 |(), entry| entry.applied(),
744 )
745 }
746
747 pub fn set_custom_geometry_source_tile_data(
751 &self,
752 source_id: impl Into<String>,
753 tile_id: CanonicalTileID,
754 json: impl Into<String>,
755 ) -> Result<Completion<Applied>, Error> {
756 let (source_id, json) = (source_id.into(), json.into());
757 self.command(move |map| {
758 let geojson = feature_collection(parse_geojson(&json)?);
759 custom_geometry(map.style(), &source_id)?.set_tile_data(tile_id, geojson);
760 Ok(())
761 })
762 }
763
764 pub fn set_custom_geometry_source_tile_error(
766 &self,
767 source_id: impl Into<String>,
768 tile_id: CanonicalTileID,
769 message: impl Into<String>,
770 ) -> Result<Completion<Applied>, Error> {
771 let (source_id, message) = (source_id.into(), message.into());
772 self.command(move |map| {
773 custom_geometry(map.style(), &source_id)?.set_tile_error(tile_id, Error::native(message));
774 Ok(())
775 })
776 }
777
778 pub fn invalidate_custom_geometry_source_tile(
781 &self,
782 source_id: impl Into<String>,
783 tile_id: CanonicalTileID,
784 ) -> Result<Completion<Applied>, Error> {
785 let source_id = source_id.into();
786 self.command(move |map| {
787 custom_geometry(map.style(), &source_id)?.invalidate_tile(tile_id);
788 Ok(())
789 })
790 }
791
792 pub fn invalidate_custom_geometry_source_region(
795 &self,
796 source_id: impl Into<String>,
797 bounds: LatLngBounds,
798 ) -> Result<Completion<Applied>, Error> {
799 let source_id = source_id.into();
800 self.command(move |map| {
801 custom_geometry(map.style(), &source_id)?.invalidate_region(bounds);
802 Ok(())
803 })
804 }
805
806 pub fn set_custom_vector_source_tile_data(
810 &self,
811 source_id: impl Into<String>,
812 tile_id: CanonicalTileID,
813 data: Option<Vec<u8>>,
814 format: TileDataFormat,
815 ) -> Result<Completion<Applied>, Error> {
816 let source_id = source_id.into();
817 self.command(move |map| {
818 custom_vector(map.style(), &source_id)?.set_tile_data(tile_id, data.map(Arc::new), format);
819 Ok(())
820 })
821 }
822
823 pub fn set_custom_vector_source_tile_error(
825 &self,
826 source_id: impl Into<String>,
827 tile_id: CanonicalTileID,
828 message: impl Into<String>,
829 ) -> Result<Completion<Applied>, Error> {
830 let (source_id, message) = (source_id.into(), message.into());
831 self.command(move |map| {
832 custom_vector(map.style(), &source_id)?.set_tile_error(tile_id, Error::native(message));
833 Ok(())
834 })
835 }
836
837 pub fn invalidate_custom_vector_source_tile(
840 &self,
841 source_id: impl Into<String>,
842 tile_id: CanonicalTileID,
843 ) -> Result<Completion<Applied>, Error> {
844 let source_id = source_id.into();
845 self.command(move |map| {
846 custom_vector(map.style(), &source_id)?.invalidate_tile(tile_id);
847 Ok(())
848 })
849 }
850
851 pub fn invalidate_custom_vector_source_region(
854 &self,
855 source_id: impl Into<String>,
856 bounds: LatLngBounds,
857 ) -> Result<Completion<Applied>, Error> {
858 let source_id = source_id.into();
859 self.command(move |map| {
860 custom_vector(map.style(), &source_id)?.invalidate_region(bounds);
861 Ok(())
862 })
863 }
864
865 pub fn set_style_image(&self, image: StyleImage) -> Result<Completion<Applied>, Error> {
869 self.command(move |map| {
870 let style = map.style_mut();
871 require_loaded(style)?;
872 style.add_image(Arc::new(image));
873 Ok(())
874 })
875 }
876
877 pub fn remove_style_image(&self, image_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
881 let image_id = image_id.into();
882 self.command(move |map| {
883 let style = map.style_mut();
884 require_loaded(style)?;
885 if style.get_image(&image_id).is_none() {
886 return Err(Error::not_found(format!("style image {} does not exist", quote(&image_id))));
887 }
888 style.remove_image(&image_id);
889 Ok(())
890 })
891 }
892
893 pub fn style_image(&self, image_id: impl Into<String>) -> Result<Completion<Option<Immutable<StyleImage>>>, Error> {
895 let image_id = image_id.into();
896 self.query(move |map| Ok(map.style().get_image(&image_id)))
897 }
898
899 pub fn add_image_source(
904 &self,
905 source_id: impl Into<String>,
906 coordinates: [LatLng; 4],
907 image: PremultipliedImage,
908 ) -> Result<Completion<Applied>, Error> {
909 let source_id = source_id.into();
910 self.command(move |map| {
911 let style = map.style_mut();
912 require_new_source(style, &source_id)?;
913 let source = ImageSource::new(source_id, coordinates);
914 source.set_image(image);
915 style.add_source(Box::new(source))
916 })
917 }
918
919 pub fn set_image_source_url(
921 &self,
922 source_id: impl Into<String>,
923 url: impl Into<String>,
924 ) -> Result<Completion<Applied>, Error> {
925 let (source_id, url) = (source_id.into(), url.into());
926 self.command(move |map| {
927 let style = map.style();
928 require_loaded(style)?;
929 find_source_as::<ImageSource>(style, &source_id, "an image source")?.set_url(&url);
930 Ok(())
931 })
932 }
933
934 pub fn set_image_source_image(
936 &self,
937 source_id: impl Into<String>,
938 image: PremultipliedImage,
939 ) -> Result<Completion<Applied>, Error> {
940 let source_id = source_id.into();
941 self.command(move |map| {
942 let style = map.style();
943 require_loaded(style)?;
944 find_source_as::<ImageSource>(style, &source_id, "an image source")?.set_image(image);
945 Ok(())
946 })
947 }
948
949 pub fn set_image_source_coordinates(
952 &self,
953 source_id: impl Into<String>,
954 coordinates: [LatLng; 4],
955 ) -> Result<Completion<Applied>, Error> {
956 let source_id = source_id.into();
957 self.command(move |map| {
958 let style = map.style();
959 require_loaded(style)?;
960 find_source_as::<ImageSource>(style, &source_id, "an image source")?.set_coordinates(coordinates);
961 Ok(())
962 })
963 }
964
965 pub fn image_source_coordinates(&self, source_id: impl Into<String>) -> Result<Completion<[LatLng; 4]>, Error> {
967 let source_id = source_id.into();
968 self.query(move |map| {
969 Ok(find_source_as::<ImageSource>(map.style(), &source_id, "an image source")?.get_coordinates())
970 })
971 }
972
973 pub fn style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Option<LayerInfo>>, Error> {
977 let layer_id = layer_id.into();
978 self.query(move |map| Ok(map.style().get_layer(&layer_id).map(layer_info)))
979 }
980
981 pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
983 self.query(|map| Ok(map.style().get_layers().into_iter().map(layer_info).collect()))
984 }
985
986 pub fn move_style_layer(
989 &self,
990 layer_id: impl Into<String>,
991 before_layer_id: Option<String>,
992 ) -> Result<Completion<Applied>, Error> {
993 let layer_id = layer_id.into();
994 self.command(move |map| map.style_mut().move_layer(&layer_id, before_layer_id.as_deref()))
995 }
996
997 pub fn set_style_transition_options(&self, options: TransitionOptions) -> Result<Completion<Applied>, Error> {
1001 self.command(move |map| {
1002 let style = map.style_mut();
1003 require_loaded(style)?;
1004 style.set_transition_options(&options);
1005 Ok(())
1006 })
1007 }
1008
1009 pub fn style_transition_options(&self) -> Result<Completion<TransitionOptions>, Error> {
1011 self.query(|map| Ok(map.style().get_transition_options()))
1012 }
1013}
1014
1015fn add_callback_source(
1019 entry: &mut MapEntry,
1020 outbox: &mut Outbox,
1021 id: String,
1022 callbacks: Arc<CustomSourceCallbacks>,
1023 make: impl FnOnce(String, &Arc<CustomSourceCallbacks>) -> Result<Box<dyn Source>, Error>,
1024) -> Result<(), Error> {
1025 let style = entry.core.style_mut();
1026 let added = require_new_source(style, &id).and_then(|()| {
1027 let source = make(id.clone(), &callbacks)?;
1028 let held = clone_source(&*source)?;
1031 style.add_source(source)?;
1032 Ok(held)
1033 });
1034 match added {
1035 Ok(source) => {
1036 entry.callback_sources.0.push(CallbackSource { id, source, _callbacks: callbacks });
1037 Ok(())
1038 }
1039 Err(error) => {
1040 outbox.push(move || drop(callbacks));
1041 Err(error)
1042 }
1043 }
1044}
1045
1046fn clone_source(source: &dyn Source) -> Result<Box<dyn Source>, Error> {
1048 let any = source.as_any();
1049 if let Some(geometry) = any.downcast_ref::<CustomGeometrySource>() {
1050 Ok(Box::new(geometry.clone()))
1051 } else if let Some(vector) = any.downcast_ref::<CustomVectorSource>() {
1052 Ok(Box::new(vector.clone()))
1053 } else {
1054 Err(Error::invalid_argument("not a custom source"))
1055 }
1056}
1057
1058fn custom_geometry<'a>(style: &'a Style, id: &str) -> Result<&'a CustomGeometrySource, Error> {
1059 find_source_as(style, id, "a custom geometry source")
1060}
1061
1062fn custom_vector<'a>(style: &'a Style, id: &str) -> Result<&'a CustomVectorSource, Error> {
1063 find_source_as(style, id, "a custom vector source")
1064}
1065
1066#[allow(clippy::too_many_arguments)]
1071fn queue_geojson(
1072 entry: &mut MapEntry,
1073 map_id: MapId,
1074 source_id: &str,
1075 json: &str,
1076 resolver: Resolver<Applied>,
1077 run_loop: mln_actor::RunLoopHandle,
1078 outbox: &mut Outbox,
1079) -> Result<Option<Resolver<Applied>>, (Error, Resolver<Applied>)> {
1080 let found = (|| {
1081 let style = entry.core.style();
1082 require_loaded(style)?;
1083 let source = find_source_as::<GeoJSONSource>(style, source_id, "a GeoJSON source")?.clone();
1084 let geojson = parse_geojson(json)?;
1085 if source.get_options().cluster {
1086 check_clusterable(&geojson)?;
1087 }
1088 Ok((source, geojson))
1089 })();
1090 let (source, geojson) = match found {
1091 Ok(found) => found,
1092 Err(error) => return Err((error, resolver)),
1093 };
1094 if source.is_update_synchronous() {
1095 return match source.data_builder().build(&geojson) {
1096 Ok(data) => {
1097 source.set_geojson_data(Some(data));
1098 Ok(Some(resolver))
1099 }
1100 Err(error) => Err((error, resolver)),
1101 };
1102 }
1103 let update = entry.geojson_updates.0.entry(source_id.to_owned()).or_insert_with(|| GeoJsonUpdate {
1104 source: source.clone(),
1105 building: None,
1106 waiting: None,
1107 });
1108 if update.building.is_none() {
1109 update.source = source;
1110 start_geojson(update, map_id, source_id.to_owned(), geojson, resolver, run_loop);
1111 } else if let Some((_, replaced)) = update.waiting.replace((geojson, resolver)) {
1112 outbox.resolve(replaced, Err(Error::cancelled("newer data for the source replaced it")));
1113 }
1114 Ok(None)
1115}
1116
1117fn start_geojson(
1120 update: &mut GeoJsonUpdate,
1121 map_id: MapId,
1122 source_id: String,
1123 geojson: GeoJSON,
1124 resolver: Resolver<Applied>,
1125 run_loop: mln_actor::RunLoopHandle,
1126) {
1127 static BUILDS: AtomicU64 = AtomicU64::new(0);
1130 let build = BUILDS.fetch_add(1, Ordering::Relaxed);
1131 update.building = Some((build, resolver));
1132 let builder = update.source.data_builder();
1133 let generation = update.source.data_generation();
1134 let next = run_loop.clone();
1135 scheduler::get_background().schedule(Box::new(move || {
1136 let data = builder.build(&geojson);
1137 post(&run_loop, move |core, outbox| {
1138 install_geojson(core, map_id, &source_id, (build, generation), data, next, outbox);
1139 });
1140 }));
1141}
1142
1143fn install_geojson(
1146 core: &mut RuntimeCore,
1147 map_id: MapId,
1148 source_id: &str,
1149 (build, generation): (u64, u64),
1150 data: Result<Arc<dyn GeoJSONData>, Error>,
1151 run_loop: mln_actor::RunLoopHandle,
1152 outbox: &mut Outbox,
1153) {
1154 flush(core, map_id, outbox);
1155 let Some(entry) = core.maps.get_mut(&map_id) else { return };
1156 let Some(update) = entry.geojson_updates.0.get_mut(source_id) else { return };
1157 let Some((_, resolver)) = update.building.take_if(|(building, _)| *building == build) else { return };
1158 let current = entry.core.style().get_source(source_id).is_some_and(|found| same_source(found, &update.source));
1159 let installed = match data {
1160 Err(error) => Err(error),
1161 Ok(_) if !current || update.source.data_generation() != generation => {
1162 Err(Error::cancelled("the source's data was replaced before this data was ready"))
1163 }
1164 Ok(data) => {
1165 update.source.set_geojson_data(Some(data));
1166 Ok(())
1167 }
1168 };
1169 match update.waiting.take() {
1170 Some((geojson, next)) if current => {
1171 start_geojson(update, map_id, source_id.to_owned(), geojson, next, run_loop);
1172 }
1173 Some((_, next)) => outbox.resolve(next, Err(Error::cancelled("the source left the style"))),
1174 None => {
1175 entry.geojson_updates.0.remove(source_id);
1176 }
1177 }
1178 flush(core, map_id, outbox);
1179 let Some(entry) = core.maps.get(&map_id) else { return };
1180 outbox.resolve(resolver, installed.map(|()| entry.applied()));
1181}