1use std::sync::Arc;
5use std::sync::atomic::{AtomicU64, Ordering};
6
7use geojson::{GeoJson, GeometryValue};
8use mln_builtins::sources::geojson::{GeoJSONData, create_geojson_data_in, set_data};
9use mln_builtins::sources::image::set_image;
10use mln_style::bitmap::PremultipliedImage;
11use mln_style::crs::WorldMapping;
12use mln_style::error::Error;
13use mln_style::expression::Functions;
14use mln_style::geo::{LatLng, LatLngBounds};
15use mln_style::hash::HashMap;
16use mln_style::image::StyleImage;
17use mln_style::range::Range;
18use mln_style::source::SourceData;
19use mln_style::sources::image::ImageSourceOptions;
20use mln_style::sources::{GeoJSONOptions, GeoJsonSourceType, ImageSourceType, geojson_source};
21use mln_style::tileset::{RasterEncoding, Scheme, VectorEncoding};
22use mln_style::{Edit, Source, SourceInstance, TransitionOptions};
23
24use crate::completion::{Completion, Resolver};
25use crate::map::{Applied, Map, MapEntry, MapId, apply_command, flush, missing_map, style_not_loaded};
26use crate::runtime::{Background, Outbox, RuntimeCore, post};
27
28#[derive(Clone, Debug, PartialEq)]
30pub struct SourceTiles {
31 pub urls: Vec<String>,
32 pub zoom_range: Range<u8>,
33 pub scheme: Scheme,
34 pub bounds: Option<LatLngBounds>,
35 pub vector_encoding: Option<VectorEncoding>,
36 pub raster_encoding: Option<RasterEncoding>,
37}
38
39#[derive(Clone, Debug, PartialEq)]
42pub struct GeoJsonSourceOptions {
43 pub min_zoom: u8,
45 pub max_zoom: u8,
47 pub tolerance: f64,
49 pub buffer: u16,
51 pub line_metrics: bool,
53 pub cluster: bool,
55 pub cluster_radius: u16,
57 pub cluster_max_zoom: u8,
59 pub cluster_min_points: usize,
61 pub cluster_properties: Option<String>,
65 pub attribution: Option<String>,
66}
67
68impl Default for GeoJsonSourceOptions {
69 fn default() -> Self {
70 GeoJsonSourceOptions::from_core(&GeoJSONOptions::default())
71 }
72}
73
74impl GeoJsonSourceOptions {
75 fn from_core(options: &GeoJSONOptions) -> Self {
76 GeoJsonSourceOptions {
77 min_zoom: options.minzoom,
78 max_zoom: options.maxzoom,
79 tolerance: options.tolerance,
80 buffer: options.buffer,
81 line_metrics: options.line_metrics,
82 cluster: options.cluster,
83 cluster_radius: options.cluster_radius,
84 cluster_max_zoom: options.cluster_max_zoom,
85 cluster_min_points: options.cluster_min_points,
86 cluster_properties: cluster_properties_json(options),
87 attribution: options.attribution.clone(),
88 }
89 }
90
91 fn check(&self) -> Result<(), Error> {
94 if self.max_zoom > 24 {
97 return Err(Error::invalid_argument("max_zoom must be an integer within [0, 24]"));
98 }
99 if self.cluster_max_zoom > 30 {
100 return Err(Error::invalid_argument("cluster_max_zoom must be an integer within [0, 30]"));
101 }
102 if self.min_zoom > self.max_zoom {
103 return Err(Error::invalid_argument("min_zoom must be less than or equal to max_zoom"));
104 }
105 if !self.tolerance.is_finite() || self.tolerance < 0.0 {
106 return Err(Error::invalid_argument("tolerance must be finite and non-negative"));
107 }
108 if self.buffer > 512 {
109 return Err(Error::invalid_argument("buffer must be at most 512"));
110 }
111 if self.cluster_radius > 4095 {
112 return Err(Error::invalid_argument("cluster_radius must be at most 4095"));
113 }
114 Ok(())
115 }
116
117 pub fn check_cluster_properties(&self, functions: &Arc<Functions>) -> Result<(), Error> {
123 self.cluster_properties.as_deref().map_or(Ok(()), |json| parse_cluster_properties(json, functions).map(drop))
124 }
125
126 fn into_core(self, functions: &Arc<Functions>) -> Result<GeoJSONOptions, Error> {
129 let cluster_properties = match &self.cluster_properties {
130 Some(json) => parse_cluster_properties(json, functions)?,
131 None => mln_style::sources::geojson::ClusterProperties::default(),
132 };
133 Ok(GeoJSONOptions {
134 minzoom: self.min_zoom,
135 maxzoom: self.max_zoom,
136 tolerance: self.tolerance,
137 buffer: self.buffer,
138 line_metrics: self.line_metrics,
139 cluster: self.cluster,
140 cluster_radius: self.cluster_radius,
141 cluster_max_zoom: self.cluster_max_zoom,
142 cluster_min_points: self.cluster_min_points,
143 cluster_properties,
144 attribution: self.attribution,
145 ..GeoJSONOptions::default()
146 })
147 }
148}
149
150fn parse_cluster_properties(
155 json: &str,
156 functions: &Arc<Functions>,
157) -> Result<mln_style::sources::geojson::ClusterProperties, Error> {
158 let value: serde_json::Value = serde_json::from_str(json)
159 .map_err(|error| Error::invalid_argument(format!("cluster_properties is not valid JSON: {error}")))?;
160 if !value.is_object() {
161 return Err(Error::invalid_argument("cluster_properties must contain a JSON object"));
162 }
163 let wrapper = serde_json::json!({ "clusterProperties": value });
164 let mut error = mln_style::conversion::Error::default();
165 let options = mln_style::conversion::convert_geojson_options(
166 &mln_style::conversion::Convertible::from(&wrapper),
167 functions,
168 &mut error,
169 )
170 .ok_or_else(|| Error::invalid_argument(format!("GeoJSON source options: {}", error.message)))?;
171 Ok(options.cluster_properties)
172}
173
174#[derive(Clone, Debug)]
176pub struct SourceInfo {
177 pub id: String,
178 pub source_type: &'static str,
181 pub is_volatile: bool,
182 pub attribution: Option<String>,
185 pub url: Option<String>,
186 pub tiles: Option<SourceTiles>,
188 pub tile_size: Option<u16>,
190 pub vector_encoding: Option<VectorEncoding>,
192 pub geojson: Option<GeoJsonSourceOptions>,
193}
194
195#[derive(Clone, Debug, PartialEq)]
197pub struct LayerInfo {
198 pub id: String,
199 pub layer_type: &'static str,
202 pub source_id: Option<String>,
204 pub source_layer: Option<String>,
206 pub min_zoom: Option<f64>,
207 pub max_zoom: Option<f64>,
208 pub visible: bool,
209}
210
211struct GeoJsonUpdate {
214 instance: SourceInstance,
217 building: Option<(u64, Resolver<Applied>)>,
221 waiting: Option<(GeoJson, Resolver<Applied>)>,
222}
223
224#[derive(Default)]
226pub(crate) struct GeoJsonUpdates(HashMap<String, GeoJsonUpdate>);
227
228pub(crate) fn reconcile(entry: &mut MapEntry, outbox: &mut Outbox) {
230 let map = &entry.core;
231 entry.geojson_updates.0.retain(|id, update| {
232 if map.source(id).is_some_and(|found| found.instance() == update.instance) {
233 return true;
234 }
235 let cancelled = || Err(Error::cancelled("the source left the style before its data was ready"));
236 if let Some((_, resolver)) = update.building.take() {
237 outbox.resolve(resolver, cancelled());
238 }
239 if let Some((_, resolver)) = update.waiting.take() {
240 outbox.resolve(resolver, cancelled());
241 }
242 false
243 });
244}
245
246pub(crate) fn release(entry: &mut MapEntry, outbox: &mut Outbox) {
249 for (_, mut update) in entry.geojson_updates.0.drain() {
250 let cancelled = || Err(Error::cancelled("the map was released before the data was ready"));
251 if let Some((_, resolver)) = update.building.take() {
252 outbox.resolve(resolver, cancelled());
253 }
254 if let Some((_, resolver)) = update.waiting.take() {
255 outbox.resolve(resolver, cancelled());
256 }
257 }
258}
259
260fn quote(id: &str) -> String {
261 format!("\"{id}\"")
262}
263
264fn require_loaded(map: &mln_engine::map::Map) -> Result<(), Error> {
265 if map.style_document_loaded() { Ok(()) } else { Err(style_not_loaded()) }
266}
267
268fn source_not_found(id: &str) -> Error {
269 Error::not_found(format!("source {} does not exist", quote(id)))
270}
271
272fn find_source<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a Source, Error> {
273 map.source(id).ok_or_else(|| source_not_found(id))
274}
275
276fn not_a(id: &str, kind: &str) -> Error {
279 Error::invalid_argument(format!("source {} is not {kind}", quote(id)))
280}
281
282fn geojson_data<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a SourceData<GeoJsonSourceType>, Error> {
284 SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "a GeoJSON source"))
285}
286
287fn image_data<'a>(map: &'a mln_engine::map::Map, id: &str) -> Result<&'a SourceData<ImageSourceType>, Error> {
289 SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "an image source"))
290}
291
292fn require_new_source(map: &mln_engine::map::Map, id: &str) -> Result<(), Error> {
293 require_loaded(map)?;
294 if map.source(id).is_some() {
295 return Err(Error::already_exists(format!("source {} already exists", quote(id))));
296 }
297 Ok(())
298}
299
300fn cluster_properties_json(options: &GeoJSONOptions) -> Option<String> {
302 if options.cluster_properties.is_empty() {
303 return None;
304 }
305 let members = options
306 .cluster_properties
307 .iter()
308 .map(|(key, (map, reduce))| {
309 let pair = mln_style::feature::Value::Array(vec![reduce.serialize(), map.serialize()]);
310 (key.clone(), mln_style::conversion::value_to_json(&pair))
311 })
312 .collect::<serde_json::Map<_, _>>();
313 Some(serde_json::Value::Object(members).to_string())
314}
315
316fn source_info(registry: &mln_engine::Registry, source: &Source) -> SourceInfo {
318 let summary = registry.source_summary(source);
319 SourceInfo {
320 id: source.id().to_owned(),
321 source_type: source.info().name,
322 is_volatile: source.common().volatile,
323 attribution: registry.source_attribution(source).filter(|attribution| !attribution.is_empty()),
324 url: summary.url,
325 tiles: summary.inline_tileset.map(|tileset| SourceTiles {
326 urls: tileset.tiles,
327 zoom_range: tileset.zoom_range,
328 scheme: tileset.scheme,
329 bounds: tileset.bounds,
330 vector_encoding: tileset.vector_encoding,
331 raster_encoding: tileset.raster_encoding,
332 }),
333 tile_size: summary.tile_size,
334 vector_encoding: summary.vector_encoding,
335 geojson: summary.geojson.map(|options| GeoJsonSourceOptions::from_core(&options)),
336 }
337}
338
339fn layer_info(layer: &mln_style::Layer) -> LayerInfo {
340 LayerInfo {
341 id: layer.id().to_owned(),
342 layer_type: layer.info().name,
343 source_id: Some(layer.source_id()).filter(|id| !id.is_empty()).map(str::to_owned),
344 source_layer: Some(layer.source_layer()).filter(|id| !id.is_empty()).map(str::to_owned),
345 min_zoom: Some(layer.min_zoom()).filter(|zoom| zoom.is_finite()),
346 max_zoom: Some(layer.max_zoom()).filter(|zoom| zoom.is_finite()),
347 visible: layer.visibility() != mln_style::types::VisibilityType::None,
348 }
349}
350
351pub(crate) fn parse_geojson(json: &str) -> Result<GeoJson, Error> {
353 serde_json::from_str(json).map_err(|error| {
354 let what = if error.is_data() { "invalid" } else { "not valid JSON" };
355 Error::invalid_argument(format!("GeoJSON data is {what}: {error}"))
356 })
357}
358
359fn check_clusterable(geojson: &GeoJson, filtered: bool) -> Result<(), Error> {
364 let features = match geojson {
365 GeoJson::FeatureCollection(collection) => &collection.features,
366 other => {
367 let found = if matches!(other, GeoJson::Feature(_)) { "a single feature" } else { "a bare geometry" };
368 return Err(Error::invalid_argument(format!(
369 "clustered GeoJSON data requires a feature collection; the data is {found}"
370 )));
371 }
372 };
373 if filtered {
374 return Ok(());
375 }
376 let point = |feature: &geojson::Feature| matches!(&feature.geometry, Some(g) if matches!(g.value, GeometryValue::Point { .. }));
377 match features.iter().position(|feature| !point(feature)) {
378 None => Ok(()),
379 Some(index) => Err(Error::invalid_argument(format!(
380 "clustered GeoJSON data requires point geometry on every feature; feature {index} has {} geometry",
381 features[index].geometry.as_ref().map_or("no", |g| g.value.type_name())
382 ))),
383 }
384}
385
386impl Map {
387 pub fn set_global_state_property(
392 &self,
393 name: impl Into<String>,
394 json: impl Into<String>,
395 ) -> Result<Completion<Applied>, Error> {
396 let (name, json) = (name.into(), json.into());
397 self.command(move |map| map.edit_loaded_style(|style| style.set_global_state_property_json(&name, &json)))
398 }
399
400 pub fn global_state(&self) -> Result<Completion<String>, Error> {
402 self.query(|map| Ok(map.style().global_state_json()))
403 }
404
405 pub fn invalidate_expression_functions(&self, names: Vec<String>) -> Result<Completion<Applied>, Error> {
409 self.command(move |map| {
410 if names.is_empty() {
411 map.invalidate_expression_functions(None);
412 } else {
413 let refs: Vec<&str> = names.iter().map(String::as_str).collect();
414 map.invalidate_expression_functions(Some(&refs));
415 }
416 Ok(())
417 })
418 }
419
420 pub fn style_source(&self, source_id: impl Into<String>) -> Result<Completion<Option<SourceInfo>>, Error> {
424 let source_id = source_id.into();
425 self.query(move |map| Ok(map.source(&source_id).map(|source| source_info(map.registry(), source))))
426 }
427
428 pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
430 self.query(|map| Ok(map.sources().map(|source| source_info(map.registry(), source)).collect()))
431 }
432
433 pub fn set_style_source_volatile(
435 &self,
436 source_id: impl Into<String>,
437 is_volatile: bool,
438 ) -> Result<Completion<Applied>, Error> {
439 let source_id = source_id.into();
440 self.command(move |map| {
441 require_loaded(map)?;
442 let mut common = *find_source(map, &source_id)?.common();
443 common.volatile = is_volatile;
444 map.edit_style(|style| style.apply(Edit::SetSourceCommon { id: source_id, common }))
445 })
446 }
447
448 pub fn add_geojson_source(
457 &self,
458 source_id: impl Into<String>,
459 options: GeoJsonSourceOptions,
460 ) -> Result<Completion<Applied>, Error> {
461 options.check()?;
462 let source_id = source_id.into();
463 self.command(move |map| {
464 let functions = Arc::clone(map.style().registry().functions());
465 let options = options.into_core(&functions)?;
466 require_new_source(map, &source_id)?;
467 map.add_source(geojson_source(&source_id, Arc::new(options)))
468 })
469 }
470
471 pub fn set_geojson_source_url(
475 &self,
476 source_id: impl Into<String>,
477 url: impl Into<String>,
478 ) -> Result<Completion<Applied>, Error> {
479 let (source_id, url) = (source_id.into(), url.into());
480 self.send(
481 move |entry, outbox| {
482 require_loaded(&entry.core)?;
483 let edit = GeoJsonSourceType::set_url(source_id.clone(), url);
484 entry.core.edit_style(|style| style.apply(edit))?;
485 if let Some((_, resolver)) =
486 entry.geojson_updates.0.get_mut(&source_id).and_then(|update| update.waiting.take())
487 {
488 outbox.resolve(resolver, Err(Error::cancelled("the source's URL replaced its data")));
489 }
490 Ok(())
491 },
492 |(), entry| entry.applied(),
493 )
494 }
495
496 pub fn set_geojson_source_data(
514 &self,
515 source_id: impl Into<String>,
516 json: impl Into<String>,
517 ) -> Result<Completion<Applied>, Error> {
518 let (source_id, json) = (source_id.into(), json.into());
519 self.post(move |core, outbox, id, sequence, resolver| {
520 if !core.maps.contains_key(&id) {
521 return outbox.resolve(resolver, Err(missing_map()));
522 }
523 let background = core.background();
524 apply_command(
525 core,
526 id,
527 sequence,
528 outbox,
529 move |entry, outbox| match queue_geojson(entry, id, &source_id, &json, resolver, background, outbox) {
530 Ok(installed) => installed,
531 Err((error, resolver)) => {
532 outbox.resolve(resolver, Err(error));
533 None
534 }
535 },
536 |_, installed, applied, outbox| {
537 if let Some(resolver) = installed {
538 outbox.resolve(resolver, Ok(applied));
539 }
540 },
541 );
542 })
543 }
544
545 pub fn set_geojson_source_synchronous_tiling(
548 &self,
549 source_id: impl Into<String>,
550 enabled: bool,
551 ) -> Result<Completion<Applied>, Error> {
552 let source_id = source_id.into();
553 self.command(move |map| {
554 require_loaded(map)?;
555 map.edit_style(|style| style.apply(GeoJsonSourceType::set_synchronous(source_id, enabled)))
556 })
557 }
558
559 pub fn set_style_image(&self, image: StyleImage) -> Result<Completion<Applied>, Error> {
563 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::AddImage(Arc::new(image)))))
564 }
565
566 pub fn remove_style_image(&self, image_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
570 let image_id = image_id.into();
571 self.command(move |map| {
572 map.edit_loaded_style(|style| {
573 if style.image(&image_id).is_none() {
574 return Err(Error::not_found(format!("style image {} does not exist", quote(&image_id))));
575 }
576 style.apply(Edit::RemoveImage(image_id))
577 })
578 })
579 }
580
581 pub fn style_image(&self, image_id: impl Into<String>) -> Result<Completion<Option<Arc<StyleImage>>>, Error> {
583 let image_id = image_id.into();
584 self.query(move |map| Ok(map.style().image(&image_id).cloned()))
585 }
586
587 pub fn add_image_source(
592 &self,
593 source_id: impl Into<String>,
594 coordinates: [LatLng; 4],
595 image: PremultipliedImage,
596 ) -> Result<Completion<Applied>, Error> {
597 let source_id = source_id.into();
598 self.command(move |map| {
599 require_new_source(map, &source_id)?;
600 let options = ImageSourceOptions { url: None, coordinates };
601 let data = SourceData::<ImageSourceType>::with_description(options, Arc::new(image));
602 map.add_source(Source::new(&source_id, data))
603 })
604 }
605
606 pub fn set_image_source_url(
608 &self,
609 source_id: impl Into<String>,
610 url: impl Into<String>,
611 ) -> Result<Completion<Applied>, Error> {
612 let (source_id, url) = (source_id.into(), url.into());
613 self.command(move |map| {
614 require_loaded(map)?;
615 map.edit_style(|style| style.apply(ImageSourceType::set_url(source_id, url)))
616 })
617 }
618
619 pub fn set_image_source_image(
621 &self,
622 source_id: impl Into<String>,
623 image: PremultipliedImage,
624 ) -> Result<Completion<Applied>, Error> {
625 let source_id = source_id.into();
626 self.command(move |map| {
627 require_loaded(map)?;
628 map.edit_style(|style| style.apply(set_image(source_id, image)))
629 })
630 }
631
632 pub fn set_image_source_coordinates(
635 &self,
636 source_id: impl Into<String>,
637 coordinates: [LatLng; 4],
638 ) -> Result<Completion<Applied>, Error> {
639 let source_id = source_id.into();
640 self.command(move |map| {
641 require_loaded(map)?;
642 map.edit_style(|style| style.apply(ImageSourceType::set_coordinates(source_id, coordinates)))
643 })
644 }
645
646 pub fn image_source_coordinates(&self, source_id: impl Into<String>) -> Result<Completion<[LatLng; 4]>, Error> {
648 let source_id = source_id.into();
649 self.query(move |map| Ok(image_data(map, &source_id)?.options.coordinates))
650 }
651
652 pub fn style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Option<LayerInfo>>, Error> {
656 let layer_id = layer_id.into();
657 self.query(move |map| Ok(map.style().layer(&layer_id).map(layer_info)))
658 }
659
660 pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
662 self.query(|map| Ok(map.style().layers().map(layer_info).collect()))
663 }
664
665 pub fn move_style_layer(
668 &self,
669 layer_id: impl Into<String>,
670 before_layer_id: Option<String>,
671 ) -> Result<Completion<Applied>, Error> {
672 let layer_id = layer_id.into();
673 self.command(move |map| map.edit_loaded_style(|style| style.move_layer(&layer_id, before_layer_id.as_deref())))
674 }
675
676 pub fn set_style_transition_options(&self, options: TransitionOptions) -> Result<Completion<Applied>, Error> {
680 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::SetTransition(options))))
681 }
682
683 pub fn style_transition_options(&self) -> Result<Completion<TransitionOptions>, Error> {
685 self.query(|map| Ok(map.style().transition_options()))
686 }
687}
688
689fn queue_geojson(
694 entry: &mut MapEntry,
695 map_id: MapId,
696 source_id: &str,
697 json: &str,
698 resolver: Resolver<Applied>,
699 background: Background,
700 outbox: &mut Outbox,
701) -> Result<Option<Resolver<Applied>>, (Error, Resolver<Applied>)> {
702 let found = (|| {
703 require_loaded(&entry.core)?;
704 let data = geojson_data(&entry.core, source_id)?;
705 let geojson = parse_geojson(json)?;
706 if data.options.options.cluster {
707 check_clusterable(&geojson, data.options.options.filter.is_some())?;
708 }
709 let instance = find_source(&entry.core, source_id)?.instance();
710 let building = BuildFor::new(&entry.core, &data.options.options);
711 Ok((instance, data.load, building, data.options.synchronous_update, geojson))
712 })();
713 let (instance, load, building, synchronous, geojson) = match found {
714 Ok(found) => found,
715 Err(error) => return Err((error, resolver)),
716 };
717 if synchronous {
718 return match building.build(geojson) {
719 Ok(data) => {
720 let edit = set_data(source_id, Some(data));
721 match entry.core.edit_style(|style| style.apply(edit)) {
722 Ok(()) => Ok(Some(resolver)),
723 Err(error) => Err((error, resolver)),
724 }
725 }
726 Err(error) => Err((error, resolver)),
727 };
728 }
729 let update = entry.geojson_updates.0.entry(source_id.to_owned()).or_insert_with(|| GeoJsonUpdate {
730 instance,
731 building: None,
732 waiting: None,
733 });
734 if update.building.is_none() {
735 update.instance = instance;
736 start_geojson(update, map_id, source_id.to_owned(), (building, load), geojson, resolver, background);
737 } else if let Some((_, replaced)) = update.waiting.replace((geojson, resolver)) {
738 outbox.resolve(replaced, Err(Error::cancelled("newer data for the source replaced it")));
739 }
740 Ok(None)
741}
742
743struct BuildFor {
746 options: Arc<GeoJSONOptions>,
747 world: WorldMapping,
748}
749
750impl BuildFor {
751 fn new(map: &mln_engine::map::Map, options: &Arc<GeoJSONOptions>) -> Self {
753 BuildFor { options: Arc::clone(options), world: map.transform_state().view().world().clone() }
754 }
755
756 fn build(&self, geojson: GeoJson) -> Result<Arc<dyn GeoJSONData>, Error> {
758 create_geojson_data_in(geojson, &self.options, &self.world)
759 }
760}
761
762fn start_geojson(
766 update: &mut GeoJsonUpdate,
767 map_id: MapId,
768 source_id: String,
769 (building, load): (BuildFor, u64),
770 geojson: GeoJson,
771 resolver: Resolver<Applied>,
772 background: Background,
773) {
774 static BUILDS: AtomicU64 = AtomicU64::new(0);
777 let build = BUILDS.fetch_add(1, Ordering::Relaxed);
778 update.building = Some((build, resolver));
779 let next = background.clone();
780 background.pool.spawn(move || {
781 let data = building.build(geojson);
782 post(&background.queue, move |core, outbox| {
783 install_geojson(core, map_id, &source_id, (build, load), data, next, outbox);
784 });
785 });
786}
787
788fn current_geojson(map: &mln_engine::map::Map, id: &str, instance: SourceInstance) -> Option<(BuildFor, u64)> {
791 let source = map.source(id).filter(|source| source.instance() == instance)?;
792 let data = SourceData::<GeoJsonSourceType>::recover(source)?;
793 Some((BuildFor::new(map, &data.options.options), data.load))
794}
795
796fn install_geojson(
799 core: &mut RuntimeCore,
800 map_id: MapId,
801 source_id: &str,
802 (build, load): (u64, u64),
803 data: Result<Arc<dyn GeoJSONData>, Error>,
804 background: Background,
805 outbox: &mut Outbox,
806) {
807 flush(core, map_id, outbox);
808 let Some(entry) = core.maps.get_mut(&map_id) else { return };
809 let Some(update) = entry.geojson_updates.0.get_mut(source_id) else { return };
810 let Some((_, resolver)) = update.building.take_if(|(building, _)| *building == build) else { return };
811 let current = current_geojson(&entry.core, source_id, update.instance);
812 let installed = match data {
813 Err(error) => Err(error),
814 Ok(_) if current.as_ref().is_none_or(|(_, current_load)| *current_load != load) => {
815 Err(Error::cancelled("the source's data was replaced before this data was ready"))
816 }
817 Ok(data) => {
818 let edit = set_data(source_id, Some(data));
819 entry.core.edit_style(|style| style.apply(edit))
820 }
821 };
822 match (update.waiting.take(), current_geojson(&entry.core, source_id, update.instance)) {
823 (Some((geojson, next)), Some(current)) => {
824 start_geojson(update, map_id, source_id.to_owned(), current, geojson, next, background);
825 }
826 (Some((_, next)), None) => outbox.resolve(next, Err(Error::cancelled("the source left the style"))),
827 (None, _) => {
828 entry.geojson_updates.0.remove(source_id);
829 }
830 }
831 flush(core, map_id, outbox);
832 let Some(entry) = core.maps.get(&map_id) else { return };
833 outbox.resolve(resolver, installed.map(|()| entry.applied()));
834}