1use std::any::Any;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use geojson::{GeoJson, GeometryValue};
10use mln_builtins::sources::geojson::{GeoJSONData, create_geojson_data_in, set_data};
11use mln_builtins::sources::image::set_image;
12use mln_style::bitmap::PremultipliedImage;
13use mln_style::crs::WorldMapping;
14use mln_style::error::Error;
15use mln_style::expression::Functions;
16use mln_style::geo::{LatLng, LatLngBounds};
17use mln_style::hash::HashMap;
18use mln_style::image::StyleImage;
19use mln_style::range::Range;
20use mln_style::source::SourceData;
21use mln_style::sources::image::ImageSourceOptions;
22use mln_style::sources::{GeoJSONOptions, GeoJsonSourceType, ImageSourceType, geojson_source};
23use mln_style::tileset::{RasterEncoding, Scheme, VectorEncoding};
24use mln_style::{Edit, Source, SourceInstance, TransitionOptions};
25
26use crate::completion::{Completion, Resolver};
27use crate::map::{Applied, Map, MapEntry, MapId, apply_command, flush, missing_map, style_not_loaded};
28use crate::runtime::{Background, Outbox, RuntimeCore, post};
29
30#[derive(Clone, Debug, PartialEq)]
32pub struct SourceTiles {
33 pub urls: Vec<String>,
34 pub zoom_range: Range<u8>,
35 pub scheme: Scheme,
36 pub bounds: Option<LatLngBounds>,
37 pub vector_encoding: Option<VectorEncoding>,
38 pub raster_encoding: Option<RasterEncoding>,
39}
40
41#[derive(Clone, Debug, PartialEq)]
44pub struct GeoJsonSourceOptions {
45 pub min_zoom: u8,
47 pub max_zoom: u8,
49 pub tolerance: f64,
51 pub buffer: u16,
53 pub line_metrics: bool,
55 pub cluster: bool,
57 pub cluster_radius: u16,
59 pub cluster_max_zoom: u8,
61 pub cluster_min_points: usize,
63 pub cluster_properties: Option<String>,
67 pub attribution: Option<String>,
68}
69
70impl Default for GeoJsonSourceOptions {
71 fn default() -> Self {
72 GeoJsonSourceOptions::from_core(&GeoJSONOptions::default())
73 }
74}
75
76impl GeoJsonSourceOptions {
77 fn from_core(options: &GeoJSONOptions) -> Self {
78 GeoJsonSourceOptions {
79 min_zoom: options.minzoom,
80 max_zoom: options.maxzoom,
81 tolerance: options.tolerance,
82 buffer: options.buffer,
83 line_metrics: options.line_metrics,
84 cluster: options.cluster,
85 cluster_radius: options.cluster_radius,
86 cluster_max_zoom: options.cluster_max_zoom,
87 cluster_min_points: options.cluster_min_points,
88 cluster_properties: cluster_properties_json(options),
89 attribution: options.attribution.clone(),
90 }
91 }
92
93 fn check(&self) -> Result<(), Error> {
96 if self.max_zoom > 24 {
99 return Err(Error::invalid_argument("max_zoom must be an integer within [0, 24]"));
100 }
101 if self.cluster_max_zoom > 30 {
102 return Err(Error::invalid_argument("cluster_max_zoom must be an integer within [0, 30]"));
103 }
104 if self.min_zoom > self.max_zoom {
105 return Err(Error::invalid_argument("min_zoom must be less than or equal to max_zoom"));
106 }
107 if !self.tolerance.is_finite() || self.tolerance < 0.0 {
108 return Err(Error::invalid_argument("tolerance must be finite and non-negative"));
109 }
110 if self.buffer > 512 {
111 return Err(Error::invalid_argument("buffer must be at most 512"));
112 }
113 if self.cluster_radius > 4095 {
114 return Err(Error::invalid_argument("cluster_radius must be at most 4095"));
115 }
116 Ok(())
117 }
118
119 pub fn check_cluster_properties(&self, functions: &Arc<Functions>) -> Result<(), Error> {
125 self.cluster_properties.as_deref().map_or(Ok(()), |json| parse_cluster_properties(json, functions).map(drop))
126 }
127
128 fn into_core(self, functions: &Arc<Functions>) -> Result<GeoJSONOptions, Error> {
131 let cluster_properties = match &self.cluster_properties {
132 Some(json) => parse_cluster_properties(json, functions)?,
133 None => mln_style::sources::geojson::ClusterProperties::default(),
134 };
135 Ok(GeoJSONOptions {
136 minzoom: self.min_zoom,
137 maxzoom: self.max_zoom,
138 tolerance: self.tolerance,
139 buffer: self.buffer,
140 line_metrics: self.line_metrics,
141 cluster: self.cluster,
142 cluster_radius: self.cluster_radius,
143 cluster_max_zoom: self.cluster_max_zoom,
144 cluster_min_points: self.cluster_min_points,
145 cluster_properties,
146 attribution: self.attribution,
147 ..GeoJSONOptions::default()
148 })
149 }
150}
151
152fn parse_cluster_properties(
157 json: &str,
158 functions: &Arc<Functions>,
159) -> Result<mln_style::sources::geojson::ClusterProperties, Error> {
160 let value: serde_json::Value = serde_json::from_str(json)
161 .map_err(|error| Error::invalid_argument(format!("cluster_properties is not valid JSON: {error}")))?;
162 if !value.is_object() {
163 return Err(Error::invalid_argument("cluster_properties must contain a JSON object"));
164 }
165 let wrapper = serde_json::json!({ "clusterProperties": value });
166 let mut error = mln_style::conversion::Error::default();
167 let options = mln_style::conversion::convert_geojson_options(
168 &mln_style::conversion::Convertible::from(&wrapper),
169 functions,
170 &mut error,
171 )
172 .ok_or_else(|| Error::invalid_argument(format!("GeoJSON source options: {}", error.message)))?;
173 Ok(options.cluster_properties)
174}
175
176#[derive(Clone, Debug)]
178pub struct SourceInfo {
179 pub id: String,
180 pub source_type: &'static str,
183 pub is_volatile: bool,
184 pub attribution: Option<String>,
187 pub url: Option<String>,
188 pub tiles: Option<SourceTiles>,
190 pub tile_size: Option<u16>,
192 pub vector_encoding: Option<VectorEncoding>,
194 pub geojson: Option<GeoJsonSourceOptions>,
195}
196
197#[derive(Clone, Debug, PartialEq)]
199pub struct LayerInfo {
200 pub id: String,
201 pub layer_type: &'static str,
204 pub source_id: Option<String>,
206 pub source_layer: Option<String>,
208 pub min_zoom: Option<f64>,
209 pub max_zoom: Option<f64>,
210 pub visible: bool,
211}
212
213struct HeldSource {
216 id: String,
217 instance: SourceInstance,
218 held: Box<dyn Any + Send>,
219}
220
221#[derive(Default)]
224pub(crate) struct HeldSources(Vec<HeldSource>);
225
226#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228pub enum HeldSourceError {
229 NoSource,
231 NotHeld,
233}
234
235impl HeldSourceError {
236 #[must_use]
240 pub fn into_error(self, id: &str) -> Error {
241 match self {
242 HeldSourceError::NoSource => source_not_found(id),
243 HeldSourceError::NotHeld => Error::invalid_argument(format!("source {} holds no such value", quote(id))),
244 }
245 }
246}
247
248struct GeoJsonUpdate {
251 instance: SourceInstance,
254 building: Option<(u64, Resolver<Applied>)>,
258 waiting: Option<(GeoJson, Resolver<Applied>)>,
259}
260
261#[derive(Default)]
263pub(crate) struct GeoJsonUpdates(HashMap<String, GeoJsonUpdate>);
264
265pub(crate) fn reconcile(entry: &mut MapEntry, outbox: &mut Outbox) {
270 let map = &entry.core;
271 let present = |id: &str, instance: SourceInstance| map.source(id).is_some_and(|found| found.instance() == instance);
272 let (kept, gone): (Vec<_>, Vec<_>) =
273 std::mem::take(&mut entry.held_sources.0).into_iter().partition(|held| present(&held.id, held.instance));
274 entry.held_sources.0 = kept;
275 if !gone.is_empty() {
276 outbox.push(move || drop(gone));
277 }
278 entry.geojson_updates.0.retain(|id, update| {
279 if present(id, update.instance) {
280 return true;
281 }
282 let cancelled = || Err(Error::cancelled("the source left the style before its data was ready"));
283 if let Some((_, resolver)) = update.building.take() {
284 outbox.resolve(resolver, cancelled());
285 }
286 if let Some((_, resolver)) = update.waiting.take() {
287 outbox.resolve(resolver, cancelled());
288 }
289 false
290 });
291}
292
293pub(crate) fn release(entry: &mut MapEntry, outbox: &mut Outbox) {
296 let held = std::mem::take(&mut entry.held_sources.0);
297 if !held.is_empty() {
298 outbox.push(move || drop(held));
299 }
300 for (_, mut update) in entry.geojson_updates.0.drain() {
301 let cancelled = || Err(Error::cancelled("the map was released before the data was ready"));
302 if let Some((_, resolver)) = update.building.take() {
303 outbox.resolve(resolver, cancelled());
304 }
305 if let Some((_, resolver)) = update.waiting.take() {
306 outbox.resolve(resolver, cancelled());
307 }
308 }
309}
310
311fn quote(id: &str) -> String {
312 format!("\"{id}\"")
313}
314
315fn require_loaded(map: &mln_engine::map::Map) -> Result<(), Error> {
316 if map.style_document_loaded() { Ok(()) } else { Err(style_not_loaded()) }
317}
318
319fn source_not_found(id: &str) -> Error {
320 Error::not_found(format!("source {} does not exist", quote(id)))
321}
322
323fn find_source<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a Source, Error> {
324 map.source(id).ok_or_else(|| source_not_found(id))
325}
326
327fn not_a(id: &str, kind: &str) -> Error {
330 Error::invalid_argument(format!("source {} is not {kind}", quote(id)))
331}
332
333fn geojson_data<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a SourceData<GeoJsonSourceType>, Error> {
335 SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "a GeoJSON source"))
336}
337
338fn image_data<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a SourceData<ImageSourceType>, Error> {
340 SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "an image source"))
341}
342
343fn require_new_source(map: &mln_engine::map::Map, id: &str) -> Result<(), Error> {
344 require_loaded(map)?;
345 if map.source(id).is_some() {
346 return Err(Error::already_exists(format!("source {} already exists", quote(id))));
347 }
348 Ok(())
349}
350
351fn cluster_properties_json(options: &GeoJSONOptions) -> Option<String> {
353 if options.cluster_properties.is_empty() {
354 return None;
355 }
356 let members = options
357 .cluster_properties
358 .iter()
359 .map(|(key, (map, reduce))| {
360 let pair = mln_style::feature::Value::Array(vec![reduce.serialize(), map.serialize()]);
361 (key.clone(), mln_style::conversion::value_to_json(&pair))
362 })
363 .collect::<serde_json::Map<_, _>>();
364 Some(serde_json::Value::Object(members).to_string())
365}
366
367fn source_info(registry: &mln_engine::Registry, source: &Source) -> SourceInfo {
369 let summary = registry.source_summary(source);
370 SourceInfo {
371 id: source.id().to_owned(),
372 source_type: source.info().name,
373 is_volatile: source.common().volatile,
374 attribution: registry.source_attribution(source).filter(|attribution| !attribution.is_empty()),
375 url: summary.url,
376 tiles: summary.inline_tileset.map(|tileset| SourceTiles {
377 urls: tileset.tiles,
378 zoom_range: tileset.zoom_range,
379 scheme: tileset.scheme,
380 bounds: tileset.bounds,
381 vector_encoding: tileset.vector_encoding,
382 raster_encoding: tileset.raster_encoding,
383 }),
384 tile_size: summary.tile_size,
385 vector_encoding: summary.vector_encoding,
386 geojson: summary.geojson.map(|options| GeoJsonSourceOptions::from_core(&options)),
387 }
388}
389
390fn layer_info(layer: &mln_style::Layer) -> LayerInfo {
391 LayerInfo {
392 id: layer.id().to_owned(),
393 layer_type: layer.info().name,
394 source_id: Some(layer.source_id()).filter(|id| !id.is_empty()).map(str::to_owned),
395 source_layer: Some(layer.source_layer()).filter(|id| !id.is_empty()).map(str::to_owned),
396 min_zoom: Some(layer.min_zoom()).filter(|zoom| zoom.is_finite()),
397 max_zoom: Some(layer.max_zoom()).filter(|zoom| zoom.is_finite()),
398 visible: layer.visibility() != mln_style::types::VisibilityType::None,
399 }
400}
401
402pub(crate) fn parse_geojson(json: &str) -> Result<GeoJson, Error> {
404 serde_json::from_str(json).map_err(|error| {
405 let what = if error.is_data() { "invalid" } else { "not valid JSON" };
406 Error::invalid_argument(format!("GeoJSON data is {what}: {error}"))
407 })
408}
409
410fn check_clusterable(geojson: &GeoJson, filtered: bool) -> Result<(), Error> {
415 let features = match geojson {
416 GeoJson::FeatureCollection(collection) => &collection.features,
417 other => {
418 let found = if matches!(other, GeoJson::Feature(_)) { "a single feature" } else { "a bare geometry" };
419 return Err(Error::invalid_argument(format!(
420 "clustered GeoJSON data requires a feature collection; the data is {found}"
421 )));
422 }
423 };
424 if filtered {
425 return Ok(());
426 }
427 let point = |feature: &geojson::Feature| matches!(&feature.geometry, Some(g) if matches!(g.value, GeometryValue::Point { .. }));
428 match features.iter().position(|feature| !point(feature)) {
429 None => Ok(()),
430 Some(index) => Err(Error::invalid_argument(format!(
431 "clustered GeoJSON data requires point geometry on every feature; feature {index} has {} geometry",
432 features[index].geometry.as_ref().map_or("no", |g| g.value.type_name())
433 ))),
434 }
435}
436
437impl Map {
438 pub fn set_global_state_property(
443 &self,
444 name: impl Into<String>,
445 json: impl Into<String>,
446 ) -> Result<Completion<Applied>, Error> {
447 let (name, json) = (name.into(), json.into());
448 self.command(move |map| map.edit_loaded_style(|style| style.set_global_state_property_json(&name, &json)))
449 }
450
451 pub fn global_state(&self) -> Result<Completion<String>, Error> {
453 self.query(|map| Ok(map.style().global_state_json()))
454 }
455
456 pub fn style_source(&self, source_id: impl Into<String>) -> Result<Completion<Option<SourceInfo>>, Error> {
460 let source_id = source_id.into();
461 self.query(move |map| Ok(map.source(&source_id).map(|source| source_info(map.registry(), source))))
462 }
463
464 pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
466 self.query(|map| Ok(map.sources().map(|source| source_info(map.registry(), source)).collect()))
467 }
468
469 pub fn set_style_source_volatile(
471 &self,
472 source_id: impl Into<String>,
473 is_volatile: bool,
474 ) -> Result<Completion<Applied>, Error> {
475 let source_id = source_id.into();
476 self.command(move |map| {
477 require_loaded(map)?;
478 let mut common = *find_source(map, &source_id)?.common();
479 common.volatile = is_volatile;
480 map.edit_style(|style| style.apply(Edit::SetSourceCommon { id: source_id, common }))
481 })
482 }
483
484 pub fn add_geojson_source(
493 &self,
494 source_id: impl Into<String>,
495 options: GeoJsonSourceOptions,
496 ) -> Result<Completion<Applied>, Error> {
497 options.check()?;
498 let source_id = source_id.into();
499 self.command(move |map| {
500 let functions = Arc::clone(map.style().registry().functions());
501 let options = options.into_core(&functions)?;
502 require_new_source(map, &source_id)?;
503 map.add_source(geojson_source(&source_id, Arc::new(options)))
504 })
505 }
506
507 pub fn set_geojson_source_url(
511 &self,
512 source_id: impl Into<String>,
513 url: impl Into<String>,
514 ) -> Result<Completion<Applied>, Error> {
515 let (source_id, url) = (source_id.into(), url.into());
516 self.send(
517 move |entry, outbox| {
518 require_loaded(&entry.core)?;
519 let edit = GeoJsonSourceType::set_url(source_id.clone(), url);
520 entry.core.edit_style(|style| style.apply(edit))?;
521 if let Some((_, resolver)) =
522 entry.geojson_updates.0.get_mut(&source_id).and_then(|update| update.waiting.take())
523 {
524 outbox.resolve(resolver, Err(Error::cancelled("the source's URL replaced its data")));
525 }
526 Ok(())
527 },
528 |(), entry| entry.applied(),
529 )
530 }
531
532 pub fn set_geojson_source_data(
550 &self,
551 source_id: impl Into<String>,
552 json: impl Into<String>,
553 ) -> Result<Completion<Applied>, Error> {
554 let (source_id, json) = (source_id.into(), json.into());
555 self.post(move |core, outbox, id, sequence, resolver| {
556 if !core.maps.contains_key(&id) {
557 return outbox.resolve(resolver, Err(missing_map()));
558 }
559 let background = core.background();
560 apply_command(
561 core,
562 id,
563 sequence,
564 outbox,
565 move |entry, outbox| match queue_geojson(entry, id, &source_id, &json, resolver, background, outbox) {
566 Ok(installed) => installed,
567 Err((error, resolver)) => {
568 outbox.resolve(resolver, Err(error));
569 None
570 }
571 },
572 |_, installed, applied, outbox| {
573 if let Some(resolver) = installed {
574 outbox.resolve(resolver, Ok(applied));
575 }
576 },
577 );
578 })
579 }
580
581 pub fn set_geojson_source_synchronous_tiling(
584 &self,
585 source_id: impl Into<String>,
586 enabled: bool,
587 ) -> Result<Completion<Applied>, Error> {
588 let source_id = source_id.into();
589 self.command(move |map| {
590 require_loaded(map)?;
591 map.edit_style(|style| style.apply(GeoJsonSourceType::set_synchronous(source_id, enabled)))
592 })
593 }
594
595 pub fn add_source_holding(&self, source: Source, held: Box<dyn Any + Send>) -> Result<Completion<Applied>, Error> {
608 self.send(
609 move |entry, outbox| {
610 let map = &mut entry.core;
611 let (id, instance) = (source.id().to_owned(), source.instance());
612 match require_new_source(map, &id).and_then(|()| map.add_source(source)) {
613 Ok(()) => {
614 entry.held_sources.0.push(HeldSource { id, instance, held });
615 Ok(())
616 }
617 Err(error) => {
618 outbox.push(move || drop(held));
619 Err(error)
620 }
621 }
622 },
623 |(), entry| entry.applied(),
624 )
625 }
626
627 pub fn with_held_source<T: Any + Send>(
631 &self,
632 source_id: impl Into<String>,
633 apply: impl FnOnce(Result<&mut T, HeldSourceError>) -> Result<(), Error> + Send + 'static,
634 ) -> Result<Completion<Applied>, Error> {
635 let source_id = source_id.into();
636 self.send(
637 move |entry, _| {
638 let held = match entry.core.source(&source_id) {
639 None => Err(HeldSourceError::NoSource),
640 Some(source) => {
641 let instance = source.instance();
642 entry
643 .held_sources
644 .0
645 .iter_mut()
646 .find(|held| held.id == source_id && held.instance == instance)
647 .and_then(|held| held.held.downcast_mut::<T>())
648 .ok_or(HeldSourceError::NotHeld)
649 }
650 };
651 apply(held)
652 },
653 |(), entry| entry.applied(),
654 )
655 }
656
657 pub fn set_style_image(&self, image: StyleImage) -> Result<Completion<Applied>, Error> {
661 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::AddImage(Arc::new(image)))))
662 }
663
664 pub fn remove_style_image(&self, image_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
668 let image_id = image_id.into();
669 self.command(move |map| {
670 map.edit_loaded_style(|style| {
671 if style.image(&image_id).is_none() {
672 return Err(Error::not_found(format!("style image {} does not exist", quote(&image_id))));
673 }
674 style.apply(Edit::RemoveImage(image_id))
675 })
676 })
677 }
678
679 pub fn style_image(&self, image_id: impl Into<String>) -> Result<Completion<Option<Arc<StyleImage>>>, Error> {
681 let image_id = image_id.into();
682 self.query(move |map| Ok(map.style().image(&image_id).cloned()))
683 }
684
685 pub fn add_image_source(
690 &self,
691 source_id: impl Into<String>,
692 coordinates: [LatLng; 4],
693 image: PremultipliedImage,
694 ) -> Result<Completion<Applied>, Error> {
695 let source_id = source_id.into();
696 self.command(move |map| {
697 require_new_source(map, &source_id)?;
698 let options = ImageSourceOptions { url: None, coordinates };
699 let data = SourceData::<ImageSourceType>::with_description(options, Arc::new(image));
700 map.add_source(Source::new(&source_id, data))
701 })
702 }
703
704 pub fn set_image_source_url(
706 &self,
707 source_id: impl Into<String>,
708 url: impl Into<String>,
709 ) -> Result<Completion<Applied>, Error> {
710 let (source_id, url) = (source_id.into(), url.into());
711 self.command(move |map| {
712 require_loaded(map)?;
713 map.edit_style(|style| style.apply(ImageSourceType::set_url(source_id, url)))
714 })
715 }
716
717 pub fn set_image_source_image(
719 &self,
720 source_id: impl Into<String>,
721 image: PremultipliedImage,
722 ) -> Result<Completion<Applied>, Error> {
723 let source_id = source_id.into();
724 self.command(move |map| {
725 require_loaded(map)?;
726 map.edit_style(|style| style.apply(set_image(source_id, image)))
727 })
728 }
729
730 pub fn set_image_source_coordinates(
733 &self,
734 source_id: impl Into<String>,
735 coordinates: [LatLng; 4],
736 ) -> Result<Completion<Applied>, Error> {
737 let source_id = source_id.into();
738 self.command(move |map| {
739 require_loaded(map)?;
740 map.edit_style(|style| style.apply(ImageSourceType::set_coordinates(source_id, coordinates)))
741 })
742 }
743
744 pub fn image_source_coordinates(&self, source_id: impl Into<String>) -> Result<Completion<[LatLng; 4]>, Error> {
746 let source_id = source_id.into();
747 self.query(move |map| Ok(image_data(map, &source_id)?.options.coordinates))
748 }
749
750 pub fn style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Option<LayerInfo>>, Error> {
754 let layer_id = layer_id.into();
755 self.query(move |map| Ok(map.style().layer(&layer_id).map(layer_info)))
756 }
757
758 pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
760 self.query(|map| Ok(map.style().layers().map(layer_info).collect()))
761 }
762
763 pub fn move_style_layer(
766 &self,
767 layer_id: impl Into<String>,
768 before_layer_id: Option<String>,
769 ) -> Result<Completion<Applied>, Error> {
770 let layer_id = layer_id.into();
771 self.command(move |map| map.edit_loaded_style(|style| style.move_layer(&layer_id, before_layer_id.as_deref())))
772 }
773
774 pub fn set_style_transition_options(&self, options: TransitionOptions) -> Result<Completion<Applied>, Error> {
778 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::SetTransition(options))))
779 }
780
781 pub fn style_transition_options(&self) -> Result<Completion<TransitionOptions>, Error> {
783 self.query(|map| Ok(map.style().transition_options()))
784 }
785}
786
787fn queue_geojson(
792 entry: &mut MapEntry,
793 map_id: MapId,
794 source_id: &str,
795 json: &str,
796 resolver: Resolver<Applied>,
797 background: Background,
798 outbox: &mut Outbox,
799) -> Result<Option<Resolver<Applied>>, (Error, Resolver<Applied>)> {
800 let found = (|| {
801 require_loaded(&entry.core)?;
802 let data = geojson_data(&entry.core, source_id)?;
803 let geojson = parse_geojson(json)?;
804 if data.options.options.cluster {
805 check_clusterable(&geojson, data.options.options.filter.is_some())?;
806 }
807 let instance = find_source(&entry.core, source_id)?.instance();
808 let building = BuildFor::new(&entry.core, &data.options.options);
809 Ok((instance, data.load, building, data.options.synchronous_update, geojson))
810 })();
811 let (instance, load, building, synchronous, geojson) = match found {
812 Ok(found) => found,
813 Err(error) => return Err((error, resolver)),
814 };
815 if synchronous {
816 return match building.build(geojson) {
817 Ok(data) => {
818 let edit = set_data(source_id, Some(data));
819 match entry.core.edit_style(|style| style.apply(edit)) {
820 Ok(()) => Ok(Some(resolver)),
821 Err(error) => Err((error, resolver)),
822 }
823 }
824 Err(error) => Err((error, resolver)),
825 };
826 }
827 let update = entry.geojson_updates.0.entry(source_id.to_owned()).or_insert_with(|| GeoJsonUpdate {
828 instance,
829 building: None,
830 waiting: None,
831 });
832 if update.building.is_none() {
833 update.instance = instance;
834 start_geojson(update, map_id, source_id.to_owned(), (building, load), geojson, resolver, background);
835 } else if let Some((_, replaced)) = update.waiting.replace((geojson, resolver)) {
836 outbox.resolve(replaced, Err(Error::cancelled("newer data for the source replaced it")));
837 }
838 Ok(None)
839}
840
841struct BuildFor {
844 options: Arc<GeoJSONOptions>,
845 world: WorldMapping,
846}
847
848impl BuildFor {
849 fn new(map: &mln_engine::map::Map, options: &Arc<GeoJSONOptions>) -> Self {
851 BuildFor { options: Arc::clone(options), world: map.transform_state().view().world().clone() }
852 }
853
854 fn build(&self, geojson: GeoJson) -> Result<Arc<dyn GeoJSONData>, Error> {
856 create_geojson_data_in(geojson, &self.options, &self.world)
857 }
858}
859
860fn start_geojson(
864 update: &mut GeoJsonUpdate,
865 map_id: MapId,
866 source_id: String,
867 (building, load): (BuildFor, u64),
868 geojson: GeoJson,
869 resolver: Resolver<Applied>,
870 background: Background,
871) {
872 static BUILDS: AtomicU64 = AtomicU64::new(0);
875 let build = BUILDS.fetch_add(1, Ordering::Relaxed);
876 update.building = Some((build, resolver));
877 let next = background.clone();
878 background.pool.spawn(move || {
879 let data = building.build(geojson);
880 post(&background.queue, move |core, outbox| {
881 install_geojson(core, map_id, &source_id, (build, load), data, next, outbox);
882 });
883 });
884}
885
886fn current_geojson(map: &mln_engine::map::Map, id: &str, instance: SourceInstance) -> Option<(BuildFor, u64)> {
889 let source = map.source(id).filter(|source| source.instance() == instance)?;
890 let data = SourceData::<GeoJsonSourceType>::recover(source)?;
891 Some((BuildFor::new(map, &data.options.options), data.load))
892}
893
894fn install_geojson(
897 core: &mut RuntimeCore,
898 map_id: MapId,
899 source_id: &str,
900 (build, load): (u64, u64),
901 data: Result<Arc<dyn GeoJSONData>, Error>,
902 background: Background,
903 outbox: &mut Outbox,
904) {
905 flush(core, map_id, outbox);
906 let Some(entry) = core.maps.get_mut(&map_id) else { return };
907 let Some(update) = entry.geojson_updates.0.get_mut(source_id) else { return };
908 let Some((_, resolver)) = update.building.take_if(|(building, _)| *building == build) else { return };
909 let current = current_geojson(&entry.core, source_id, update.instance);
910 let installed = match data {
911 Err(error) => Err(error),
912 Ok(_) if current.as_ref().is_none_or(|(_, current_load)| *current_load != load) => {
913 Err(Error::cancelled("the source's data was replaced before this data was ready"))
914 }
915 Ok(data) => {
916 let edit = set_data(source_id, Some(data));
917 entry.core.edit_style(|style| style.apply(edit))
918 }
919 };
920 match (update.waiting.take(), current_geojson(&entry.core, source_id, update.instance)) {
921 (Some((geojson, next)), Some(current)) => {
922 start_geojson(update, map_id, source_id.to_owned(), current, geojson, next, background);
923 }
924 (Some((_, next)), None) => outbox.resolve(next, Err(Error::cancelled("the source left the style"))),
925 (None, _) => {
926 entry.geojson_updates.0.remove(source_id);
927 }
928 }
929 flush(core, map_id, outbox);
930 let Some(entry) = core.maps.get(&map_id) else { return };
931 outbox.resolve(resolver, installed.map(|()| entry.applied()));
932}