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, set_data};
11use mln_builtins::sources::image::set_image;
12use mln_style::bitmap::PremultipliedImage;
13use mln_style::error::Error;
14use mln_style::expression::Functions;
15use mln_style::geo::{LatLng, LatLngBounds};
16use mln_style::hash::HashMap;
17use mln_style::image::Impl as StyleImage;
18use mln_style::range::Range;
19use mln_style::source::SourceData;
20use mln_style::sources::image::ImageSourceOptions;
21use mln_style::sources::{GeoJSONOptions, GeoJsonSourceType, ImageSourceType, geojson_source};
22use mln_style::tileset::{RasterEncoding, Scheme, VectorEncoding};
23use mln_style::{Edit, Source, SourceInstance, TransitionOptions};
24
25use crate::completion::{Completion, Resolver};
26use crate::map::{Applied, Map, MapEntry, MapId, apply_command, flush, missing_map, style_not_loaded};
27use crate::runtime::{Background, Outbox, RuntimeCore, post};
28
29#[derive(Clone, Debug, PartialEq)]
31pub struct SourceTiles {
32 pub urls: Vec<String>,
33 pub zoom_range: Range<u8>,
34 pub scheme: Scheme,
35 pub bounds: Option<LatLngBounds>,
36 pub vector_encoding: Option<VectorEncoding>,
37 pub raster_encoding: Option<RasterEncoding>,
38}
39
40#[derive(Clone, Debug, PartialEq)]
43pub struct GeoJsonSourceOptions {
44 pub min_zoom: u8,
46 pub max_zoom: u8,
48 pub tolerance: f64,
50 pub buffer: u16,
52 pub line_metrics: bool,
54 pub cluster: bool,
56 pub cluster_radius: u16,
58 pub cluster_max_zoom: u8,
60 pub cluster_min_points: usize,
62 pub cluster_properties: Option<String>,
66 pub attribution: Option<String>,
67}
68
69impl Default for GeoJsonSourceOptions {
70 fn default() -> Self {
71 GeoJsonSourceOptions::from_core(&GeoJSONOptions::default())
72 }
73}
74
75impl GeoJsonSourceOptions {
76 fn from_core(options: &GeoJSONOptions) -> Self {
77 GeoJsonSourceOptions {
78 min_zoom: options.minzoom,
79 max_zoom: options.maxzoom,
80 tolerance: options.tolerance,
81 buffer: options.buffer,
82 line_metrics: options.line_metrics,
83 cluster: options.cluster,
84 cluster_radius: options.cluster_radius,
85 cluster_max_zoom: options.cluster_max_zoom,
86 cluster_min_points: options.cluster_min_points,
87 cluster_properties: cluster_properties_json(options),
88 attribution: options.attribution.clone(),
89 }
90 }
91
92 fn check(&self) -> Result<(), Error> {
95 if self.max_zoom > 24 {
98 return Err(Error::invalid_argument("max_zoom must be an integer within [0, 24]"));
99 }
100 if self.cluster_max_zoom > 30 {
101 return Err(Error::invalid_argument("cluster_max_zoom must be an integer within [0, 30]"));
102 }
103 if self.min_zoom > self.max_zoom {
104 return Err(Error::invalid_argument("min_zoom must be less than or equal to max_zoom"));
105 }
106 if !self.tolerance.is_finite() || self.tolerance < 0.0 {
107 return Err(Error::invalid_argument("tolerance must be finite and non-negative"));
108 }
109 if self.buffer > 512 {
110 return Err(Error::invalid_argument("buffer must be at most 512"));
111 }
112 if self.cluster_radius > 4095 {
113 return Err(Error::invalid_argument("cluster_radius must be at most 4095"));
114 }
115 Ok(())
116 }
117
118 pub fn check_cluster_properties(&self, functions: &Arc<Functions>) -> Result<(), Error> {
124 self.cluster_properties.as_deref().map_or(Ok(()), |json| parse_cluster_properties(json, functions).map(drop))
125 }
126
127 fn into_core(self, functions: &Arc<Functions>) -> Result<GeoJSONOptions, Error> {
130 let cluster_properties = match &self.cluster_properties {
131 Some(json) => parse_cluster_properties(json, functions)?,
132 None => mln_style::sources::geojson::ClusterProperties::default(),
133 };
134 Ok(GeoJSONOptions {
135 minzoom: self.min_zoom,
136 maxzoom: self.max_zoom,
137 tolerance: self.tolerance,
138 buffer: self.buffer,
139 line_metrics: self.line_metrics,
140 cluster: self.cluster,
141 cluster_radius: self.cluster_radius,
142 cluster_max_zoom: self.cluster_max_zoom,
143 cluster_min_points: self.cluster_min_points,
144 cluster_properties,
145 attribution: self.attribution,
146 ..GeoJSONOptions::default()
147 })
148 }
149}
150
151fn parse_cluster_properties(
156 json: &str,
157 functions: &Arc<Functions>,
158) -> Result<mln_style::sources::geojson::ClusterProperties, Error> {
159 let value: serde_json::Value = serde_json::from_str(json)
160 .map_err(|error| Error::invalid_argument(format!("cluster_properties is not valid JSON: {error}")))?;
161 if !value.is_object() {
162 return Err(Error::invalid_argument("cluster_properties must contain a JSON object"));
163 }
164 let wrapper = serde_json::json!({ "clusterProperties": value });
165 let mut error = mln_style::conversion::Error::default();
166 let options = mln_style::conversion::convert_geojson_options(
167 &mln_style::conversion::Convertible::from(&wrapper),
168 functions,
169 &mut error,
170 )
171 .ok_or_else(|| Error::invalid_argument(format!("GeoJSON source options: {}", error.message)))?;
172 Ok(options.cluster_properties)
173}
174
175#[derive(Clone, Debug)]
177pub struct SourceInfo {
178 pub id: String,
179 pub source_type: &'static str,
182 pub is_volatile: bool,
183 pub attribution: Option<String>,
186 pub url: Option<String>,
187 pub tiles: Option<SourceTiles>,
189 pub tile_size: Option<u16>,
191 pub vector_encoding: Option<VectorEncoding>,
193 pub geojson: Option<GeoJsonSourceOptions>,
194}
195
196#[derive(Clone, Debug, PartialEq)]
198pub struct LayerInfo {
199 pub id: String,
200 pub layer_type: &'static str,
203 pub source_id: Option<String>,
205 pub source_layer: Option<String>,
207 pub min_zoom: Option<f64>,
208 pub max_zoom: Option<f64>,
209 pub visible: bool,
210}
211
212struct HeldSource {
215 id: String,
216 instance: SourceInstance,
217 held: Box<dyn Any + Send>,
218}
219
220#[derive(Default)]
223pub(crate) struct HeldSources(Vec<HeldSource>);
224
225#[derive(Clone, Copy, Debug, PartialEq, Eq)]
227pub enum HeldSourceError {
228 NoSource,
230 NotHeld,
232}
233
234impl HeldSourceError {
235 #[must_use]
239 pub fn into_error(self, id: &str) -> Error {
240 match self {
241 HeldSourceError::NoSource => source_not_found(id),
242 HeldSourceError::NotHeld => Error::invalid_argument(format!("source {} holds no such value", quote(id))),
243 }
244 }
245}
246
247struct GeoJsonUpdate {
250 instance: SourceInstance,
253 building: Option<(u64, Resolver<Applied>)>,
257 waiting: Option<(GeoJson, Resolver<Applied>)>,
258}
259
260#[derive(Default)]
262pub(crate) struct GeoJsonUpdates(HashMap<String, GeoJsonUpdate>);
263
264pub(crate) fn reconcile(entry: &mut MapEntry, outbox: &mut Outbox) {
269 let map = &entry.core;
270 let present = |id: &str, instance: SourceInstance| map.source(id).is_some_and(|found| found.instance() == instance);
271 let (kept, gone): (Vec<_>, Vec<_>) =
272 std::mem::take(&mut entry.held_sources.0).into_iter().partition(|held| present(&held.id, held.instance));
273 entry.held_sources.0 = kept;
274 if !gone.is_empty() {
275 outbox.push(move || drop(gone));
276 }
277 entry.geojson_updates.0.retain(|id, update| {
278 if present(id, update.instance) {
279 return true;
280 }
281 let cancelled = || Err(Error::cancelled("the source left the style before its data was ready"));
282 if let Some((_, resolver)) = update.building.take() {
283 outbox.resolve(resolver, cancelled());
284 }
285 if let Some((_, resolver)) = update.waiting.take() {
286 outbox.resolve(resolver, cancelled());
287 }
288 false
289 });
290}
291
292pub(crate) fn release(entry: &mut MapEntry, outbox: &mut Outbox) {
295 let held = std::mem::take(&mut entry.held_sources.0);
296 if !held.is_empty() {
297 outbox.push(move || drop(held));
298 }
299 for (_, mut update) in entry.geojson_updates.0.drain() {
300 let cancelled = || Err(Error::cancelled("the map was released before the data was ready"));
301 if let Some((_, resolver)) = update.building.take() {
302 outbox.resolve(resolver, cancelled());
303 }
304 if let Some((_, resolver)) = update.waiting.take() {
305 outbox.resolve(resolver, cancelled());
306 }
307 }
308}
309
310fn quote(id: &str) -> String {
311 format!("\"{id}\"")
312}
313
314fn require_loaded(map: &mln_engine::map::Map) -> Result<(), Error> {
315 if map.style_document_loaded() { Ok(()) } else { Err(style_not_loaded()) }
316}
317
318fn source_not_found(id: &str) -> Error {
319 Error::not_found(format!("source {} does not exist", quote(id)))
320}
321
322fn find_source<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a Source, Error> {
323 map.source(id).ok_or_else(|| source_not_found(id))
324}
325
326fn not_a(id: &str, kind: &str) -> Error {
329 Error::invalid_argument(format!("source {} is not {kind}", quote(id)))
330}
331
332fn geojson_data<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a SourceData<GeoJsonSourceType>, Error> {
334 SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "a GeoJSON source"))
335}
336
337fn image_data<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a SourceData<ImageSourceType>, Error> {
339 SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "an image source"))
340}
341
342fn require_new_source(map: &mln_engine::map::Map, id: &str) -> Result<(), Error> {
343 require_loaded(map)?;
344 if map.source(id).is_some() {
345 return Err(Error::already_exists(format!("source {} already exists", quote(id))));
346 }
347 Ok(())
348}
349
350fn cluster_properties_json(options: &GeoJSONOptions) -> Option<String> {
352 if options.cluster_properties.is_empty() {
353 return None;
354 }
355 let members = options
356 .cluster_properties
357 .iter()
358 .map(|(key, (map, reduce))| {
359 let pair = mln_style::feature::Value::Array(vec![reduce.serialize(), map.serialize()]);
360 (key.clone(), mln_style::conversion::value_to_json(&pair))
361 })
362 .collect::<serde_json::Map<_, _>>();
363 Some(serde_json::Value::Object(members).to_string())
364}
365
366fn source_info(registry: &mln_engine::Registry, source: &Source) -> SourceInfo {
368 let summary = registry.source_summary(source);
369 SourceInfo {
370 id: source.id().to_owned(),
371 source_type: source.info().name,
372 is_volatile: source.common().volatile,
373 attribution: registry.source_attribution(source).filter(|attribution| !attribution.is_empty()),
374 url: summary.url,
375 tiles: summary.inline_tileset.map(|tileset| SourceTiles {
376 urls: tileset.tiles,
377 zoom_range: tileset.zoom_range,
378 scheme: tileset.scheme,
379 bounds: tileset.bounds,
380 vector_encoding: tileset.vector_encoding,
381 raster_encoding: tileset.raster_encoding,
382 }),
383 tile_size: summary.tile_size,
384 vector_encoding: summary.vector_encoding,
385 geojson: summary.geojson.map(|options| GeoJsonSourceOptions::from_core(&options)),
386 }
387}
388
389fn layer_info(layer: &mln_style::Layer) -> LayerInfo {
390 LayerInfo {
391 id: layer.get_id().to_owned(),
392 layer_type: layer.info().name,
393 source_id: Some(layer.get_source_id()).filter(|id| !id.is_empty()).map(str::to_owned),
394 source_layer: Some(layer.get_source_layer()).filter(|id| !id.is_empty()).map(str::to_owned),
395 min_zoom: Some(f64::from(layer.get_min_zoom())).filter(|zoom| zoom.is_finite()),
396 max_zoom: Some(f64::from(layer.get_max_zoom())).filter(|zoom| zoom.is_finite()),
397 visible: layer.get_visibility() != mln_style::types::VisibilityType::None,
398 }
399}
400
401pub(crate) fn parse_geojson(json: &str) -> Result<GeoJson, Error> {
403 serde_json::from_str(json).map_err(|error| {
404 let what = if error.is_data() { "invalid" } else { "not valid JSON" };
405 Error::invalid_argument(format!("GeoJSON data is {what}: {error}"))
406 })
407}
408
409fn check_clusterable(geojson: &GeoJson) -> Result<(), Error> {
413 let features = match geojson {
414 GeoJson::FeatureCollection(collection) => &collection.features,
415 other => {
416 let found = if matches!(other, GeoJson::Feature(_)) { "a single feature" } else { "a bare geometry" };
417 return Err(Error::invalid_argument(format!(
418 "clustered GeoJSON data requires a feature collection; the data is {found}"
419 )));
420 }
421 };
422 let point = |feature: &geojson::Feature| matches!(&feature.geometry, Some(g) if matches!(g.value, GeometryValue::Point { .. }));
423 match features.iter().position(|feature| !point(feature)) {
424 None => Ok(()),
425 Some(index) => Err(Error::invalid_argument(format!(
426 "clustered GeoJSON data requires point geometry on every feature; feature {index} has {} geometry",
427 features[index].geometry.as_ref().map_or("no", |g| g.value.type_name())
428 ))),
429 }
430}
431
432impl Map {
433 pub fn set_global_state_property(
438 &self,
439 name: impl Into<String>,
440 json: impl Into<String>,
441 ) -> Result<Completion<Applied>, Error> {
442 let (name, json) = (name.into(), json.into());
443 self.command(move |map| map.edit_loaded_style(|style| style.set_global_state_property_json(&name, &json)))
444 }
445
446 pub fn global_state(&self) -> Result<Completion<String>, Error> {
448 self.query(|map| Ok(map.style().global_state_json()))
449 }
450
451 pub fn style_source(&self, source_id: impl Into<String>) -> Result<Completion<Option<SourceInfo>>, Error> {
455 let source_id = source_id.into();
456 self.query(move |map| Ok(map.source(&source_id).map(|source| source_info(map.registry(), source))))
457 }
458
459 pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
461 self.query(|map| Ok(map.sources().map(|source| source_info(map.registry(), source)).collect()))
462 }
463
464 pub fn set_style_source_volatile(
466 &self,
467 source_id: impl Into<String>,
468 is_volatile: bool,
469 ) -> Result<Completion<Applied>, Error> {
470 let source_id = source_id.into();
471 self.command(move |map| {
472 require_loaded(map)?;
473 let mut common = *find_source(map, &source_id)?.common();
474 common.volatile = is_volatile;
475 map.edit_style(|style| style.apply(Edit::SetSourceCommon { id: source_id, common }))
476 })
477 }
478
479 pub fn add_geojson_source(
488 &self,
489 source_id: impl Into<String>,
490 options: GeoJsonSourceOptions,
491 ) -> Result<Completion<Applied>, Error> {
492 options.check()?;
493 let source_id = source_id.into();
494 self.command(move |map| {
495 let functions = Arc::clone(map.style().registry().functions());
496 let options = options.into_core(&functions)?;
497 require_new_source(map, &source_id)?;
498 map.add_source(geojson_source(&source_id, Arc::new(options)))
499 })
500 }
501
502 pub fn set_geojson_source_url(
506 &self,
507 source_id: impl Into<String>,
508 url: impl Into<String>,
509 ) -> Result<Completion<Applied>, Error> {
510 let (source_id, url) = (source_id.into(), url.into());
511 self.send(
512 move |entry, outbox| {
513 require_loaded(&entry.core)?;
514 let edit = GeoJsonSourceType::set_url(source_id.clone(), url);
515 entry.core.edit_style(|style| style.apply(edit))?;
516 if let Some((_, resolver)) =
517 entry.geojson_updates.0.get_mut(&source_id).and_then(|update| update.waiting.take())
518 {
519 outbox.resolve(resolver, Err(Error::cancelled("the source's URL replaced its data")));
520 }
521 Ok(())
522 },
523 |(), entry| entry.applied(),
524 )
525 }
526
527 pub fn set_geojson_source_data(
545 &self,
546 source_id: impl Into<String>,
547 json: impl Into<String>,
548 ) -> Result<Completion<Applied>, Error> {
549 let (source_id, json) = (source_id.into(), json.into());
550 self.post(move |core, outbox, id, sequence, resolver| {
551 if !core.maps.contains_key(&id) {
552 return outbox.resolve(resolver, Err(missing_map()));
553 }
554 let background = core.background();
555 apply_command(
556 core,
557 id,
558 sequence,
559 outbox,
560 move |entry, outbox| match queue_geojson(entry, id, &source_id, &json, resolver, background, outbox) {
561 Ok(installed) => installed,
562 Err((error, resolver)) => {
563 outbox.resolve(resolver, Err(error));
564 None
565 }
566 },
567 |_, installed, applied, outbox| {
568 if let Some(resolver) = installed {
569 outbox.resolve(resolver, Ok(applied));
570 }
571 },
572 );
573 })
574 }
575
576 pub fn set_geojson_source_synchronous_tiling(
579 &self,
580 source_id: impl Into<String>,
581 enabled: bool,
582 ) -> Result<Completion<Applied>, Error> {
583 let source_id = source_id.into();
584 self.command(move |map| {
585 require_loaded(map)?;
586 map.edit_style(|style| style.apply(GeoJsonSourceType::set_synchronous(source_id, enabled)))
587 })
588 }
589
590 pub fn add_source_holding(&self, source: Source, held: Box<dyn Any + Send>) -> Result<Completion<Applied>, Error> {
603 self.send(
604 move |entry, outbox| {
605 let map = &mut entry.core;
606 let (id, instance) = (source.id().to_owned(), source.instance());
607 match require_new_source(map, &id).and_then(|()| map.add_source(source)) {
608 Ok(()) => {
609 entry.held_sources.0.push(HeldSource { id, instance, held });
610 Ok(())
611 }
612 Err(error) => {
613 outbox.push(move || drop(held));
614 Err(error)
615 }
616 }
617 },
618 |(), entry| entry.applied(),
619 )
620 }
621
622 pub fn with_held_source<T: Any + Send>(
626 &self,
627 source_id: impl Into<String>,
628 apply: impl FnOnce(Result<&mut T, HeldSourceError>) -> Result<(), Error> + Send + 'static,
629 ) -> Result<Completion<Applied>, Error> {
630 let source_id = source_id.into();
631 self.send(
632 move |entry, _| {
633 let held = match entry.core.source(&source_id) {
634 None => Err(HeldSourceError::NoSource),
635 Some(source) => {
636 let instance = source.instance();
637 entry
638 .held_sources
639 .0
640 .iter_mut()
641 .find(|held| held.id == source_id && held.instance == instance)
642 .and_then(|held| held.held.downcast_mut::<T>())
643 .ok_or(HeldSourceError::NotHeld)
644 }
645 };
646 apply(held)
647 },
648 |(), entry| entry.applied(),
649 )
650 }
651
652 pub fn set_style_image(&self, image: StyleImage) -> Result<Completion<Applied>, Error> {
656 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::AddImage(Arc::new(image)))))
657 }
658
659 pub fn remove_style_image(&self, image_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
663 let image_id = image_id.into();
664 self.command(move |map| {
665 map.edit_loaded_style(|style| {
666 if style.get_image(&image_id).is_none() {
667 return Err(Error::not_found(format!("style image {} does not exist", quote(&image_id))));
668 }
669 style.apply(Edit::RemoveImage(image_id))
670 })
671 })
672 }
673
674 pub fn style_image(&self, image_id: impl Into<String>) -> Result<Completion<Option<Arc<StyleImage>>>, Error> {
676 let image_id = image_id.into();
677 self.query(move |map| Ok(map.style().get_image(&image_id).cloned()))
678 }
679
680 pub fn add_image_source(
685 &self,
686 source_id: impl Into<String>,
687 coordinates: [LatLng; 4],
688 image: PremultipliedImage,
689 ) -> Result<Completion<Applied>, Error> {
690 let source_id = source_id.into();
691 self.command(move |map| {
692 require_new_source(map, &source_id)?;
693 let options = ImageSourceOptions { url: None, coordinates };
694 let data = SourceData::<ImageSourceType>::with_description(options, Arc::new(image));
695 map.add_source(Source::new(&source_id, data))
696 })
697 }
698
699 pub fn set_image_source_url(
701 &self,
702 source_id: impl Into<String>,
703 url: impl Into<String>,
704 ) -> Result<Completion<Applied>, Error> {
705 let (source_id, url) = (source_id.into(), url.into());
706 self.command(move |map| {
707 require_loaded(map)?;
708 map.edit_style(|style| style.apply(ImageSourceType::set_url(source_id, url)))
709 })
710 }
711
712 pub fn set_image_source_image(
714 &self,
715 source_id: impl Into<String>,
716 image: PremultipliedImage,
717 ) -> Result<Completion<Applied>, Error> {
718 let source_id = source_id.into();
719 self.command(move |map| {
720 require_loaded(map)?;
721 map.edit_style(|style| style.apply(set_image(source_id, image)))
722 })
723 }
724
725 pub fn set_image_source_coordinates(
728 &self,
729 source_id: impl Into<String>,
730 coordinates: [LatLng; 4],
731 ) -> Result<Completion<Applied>, Error> {
732 let source_id = source_id.into();
733 self.command(move |map| {
734 require_loaded(map)?;
735 map.edit_style(|style| style.apply(ImageSourceType::set_coordinates(source_id, coordinates)))
736 })
737 }
738
739 pub fn image_source_coordinates(&self, source_id: impl Into<String>) -> Result<Completion<[LatLng; 4]>, Error> {
741 let source_id = source_id.into();
742 self.query(move |map| Ok(image_data(map, &source_id)?.options.coordinates))
743 }
744
745 pub fn style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Option<LayerInfo>>, Error> {
749 let layer_id = layer_id.into();
750 self.query(move |map| Ok(map.style().get_layer(&layer_id).map(layer_info)))
751 }
752
753 pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
755 self.query(|map| Ok(map.style().get_layers().map(layer_info).collect()))
756 }
757
758 pub fn move_style_layer(
761 &self,
762 layer_id: impl Into<String>,
763 before_layer_id: Option<String>,
764 ) -> Result<Completion<Applied>, Error> {
765 let layer_id = layer_id.into();
766 self.command(move |map| map.edit_loaded_style(|style| style.move_layer(&layer_id, before_layer_id.as_deref())))
767 }
768
769 pub fn set_style_transition_options(&self, options: TransitionOptions) -> Result<Completion<Applied>, Error> {
773 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::SetTransition(options))))
774 }
775
776 pub fn style_transition_options(&self) -> Result<Completion<TransitionOptions>, Error> {
778 self.query(|map| Ok(map.style().get_transition_options()))
779 }
780}
781
782fn queue_geojson(
787 entry: &mut MapEntry,
788 map_id: MapId,
789 source_id: &str,
790 json: &str,
791 resolver: Resolver<Applied>,
792 background: Background,
793 outbox: &mut Outbox,
794) -> Result<Option<Resolver<Applied>>, (Error, Resolver<Applied>)> {
795 let found = (|| {
796 require_loaded(&entry.core)?;
797 let data = geojson_data(&entry.core, source_id)?;
798 let geojson = parse_geojson(json)?;
799 if data.options.options.cluster {
800 check_clusterable(&geojson)?;
801 }
802 let instance = find_source(&entry.core, source_id)?.instance();
803 Ok((instance, data.load, Arc::clone(&data.options.options), data.options.synchronous_update, geojson))
804 })();
805 let (instance, load, options, synchronous, geojson) = match found {
806 Ok(found) => found,
807 Err(error) => return Err((error, resolver)),
808 };
809 if synchronous {
810 return match create_geojson_data(geojson, &options) {
811 Ok(data) => {
812 let edit = set_data(source_id, Some(data));
813 match entry.core.edit_style(|style| style.apply(edit)) {
814 Ok(()) => Ok(Some(resolver)),
815 Err(error) => Err((error, resolver)),
816 }
817 }
818 Err(error) => Err((error, resolver)),
819 };
820 }
821 let update = entry.geojson_updates.0.entry(source_id.to_owned()).or_insert_with(|| GeoJsonUpdate {
822 instance,
823 building: None,
824 waiting: None,
825 });
826 if update.building.is_none() {
827 update.instance = instance;
828 start_geojson(update, map_id, source_id.to_owned(), (options, load), geojson, resolver, background);
829 } else if let Some((_, replaced)) = update.waiting.replace((geojson, resolver)) {
830 outbox.resolve(replaced, Err(Error::cancelled("newer data for the source replaced it")));
831 }
832 Ok(None)
833}
834
835fn start_geojson(
839 update: &mut GeoJsonUpdate,
840 map_id: MapId,
841 source_id: String,
842 (options, load): (Arc<GeoJSONOptions>, u64),
843 geojson: GeoJson,
844 resolver: Resolver<Applied>,
845 background: Background,
846) {
847 static BUILDS: AtomicU64 = AtomicU64::new(0);
850 let build = BUILDS.fetch_add(1, Ordering::Relaxed);
851 update.building = Some((build, resolver));
852 let next = background.clone();
853 background.pool.spawn(move || {
854 let data = create_geojson_data(geojson, &options);
855 post(&background.queue, move |core, outbox| {
856 install_geojson(core, map_id, &source_id, (build, load), data, next, outbox);
857 });
858 });
859}
860
861fn current_geojson(
864 map: &mln_engine::map::Map,
865 id: &str,
866 instance: SourceInstance,
867) -> Option<(Arc<GeoJSONOptions>, u64)> {
868 let source = map.source(id).filter(|source| source.instance() == instance)?;
869 let data = SourceData::<GeoJsonSourceType>::recover(source)?;
870 Some((Arc::clone(&data.options.options), data.load))
871}
872
873fn install_geojson(
876 core: &mut RuntimeCore,
877 map_id: MapId,
878 source_id: &str,
879 (build, load): (u64, u64),
880 data: Result<Arc<dyn GeoJSONData>, Error>,
881 background: Background,
882 outbox: &mut Outbox,
883) {
884 flush(core, map_id, outbox);
885 let Some(entry) = core.maps.get_mut(&map_id) else { return };
886 let Some(update) = entry.geojson_updates.0.get_mut(source_id) else { return };
887 let Some((_, resolver)) = update.building.take_if(|(building, _)| *building == build) else { return };
888 let current = current_geojson(&entry.core, source_id, update.instance);
889 let installed = match data {
890 Err(error) => Err(error),
891 Ok(_) if current.as_ref().is_none_or(|(_, current_load)| *current_load != load) => {
892 Err(Error::cancelled("the source's data was replaced before this data was ready"))
893 }
894 Ok(data) => {
895 let edit = set_data(source_id, Some(data));
896 entry.core.edit_style(|style| style.apply(edit))
897 }
898 };
899 match (update.waiting.take(), current_geojson(&entry.core, source_id, update.instance)) {
900 (Some((geojson, next)), Some(current)) => {
901 start_geojson(update, map_id, source_id.to_owned(), current, geojson, next, background);
902 }
903 (Some((_, next)), None) => outbox.resolve(next, Err(Error::cancelled("the source left the style"))),
904 (None, _) => {
905 entry.geojson_updates.0.remove(source_id);
906 }
907 }
908 flush(core, map_id, outbox);
909 let Some(entry) = core.maps.get(&map_id) else { return };
910 outbox.resolve(resolver, installed.map(|()| entry.applied()));
911}