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 style_source(&self, source_id: impl Into<String>) -> Result<Completion<Option<SourceInfo>>, Error> {
409 let source_id = source_id.into();
410 self.query(move |map| Ok(map.source(&source_id).map(|source| source_info(map.registry(), source))))
411 }
412
413 pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
415 self.query(|map| Ok(map.sources().map(|source| source_info(map.registry(), source)).collect()))
416 }
417
418 pub fn set_style_source_volatile(
420 &self,
421 source_id: impl Into<String>,
422 is_volatile: bool,
423 ) -> Result<Completion<Applied>, Error> {
424 let source_id = source_id.into();
425 self.command(move |map| {
426 require_loaded(map)?;
427 let mut common = *find_source(map, &source_id)?.common();
428 common.volatile = is_volatile;
429 map.edit_style(|style| style.apply(Edit::SetSourceCommon { id: source_id, common }))
430 })
431 }
432
433 pub fn add_geojson_source(
442 &self,
443 source_id: impl Into<String>,
444 options: GeoJsonSourceOptions,
445 ) -> Result<Completion<Applied>, Error> {
446 options.check()?;
447 let source_id = source_id.into();
448 self.command(move |map| {
449 let functions = Arc::clone(map.style().registry().functions());
450 let options = options.into_core(&functions)?;
451 require_new_source(map, &source_id)?;
452 map.add_source(geojson_source(&source_id, Arc::new(options)))
453 })
454 }
455
456 pub fn set_geojson_source_url(
460 &self,
461 source_id: impl Into<String>,
462 url: impl Into<String>,
463 ) -> Result<Completion<Applied>, Error> {
464 let (source_id, url) = (source_id.into(), url.into());
465 self.send(
466 move |entry, outbox| {
467 require_loaded(&entry.core)?;
468 let edit = GeoJsonSourceType::set_url(source_id.clone(), url);
469 entry.core.edit_style(|style| style.apply(edit))?;
470 if let Some((_, resolver)) =
471 entry.geojson_updates.0.get_mut(&source_id).and_then(|update| update.waiting.take())
472 {
473 outbox.resolve(resolver, Err(Error::cancelled("the source's URL replaced its data")));
474 }
475 Ok(())
476 },
477 |(), entry| entry.applied(),
478 )
479 }
480
481 pub fn set_geojson_source_data(
499 &self,
500 source_id: impl Into<String>,
501 json: impl Into<String>,
502 ) -> Result<Completion<Applied>, Error> {
503 let (source_id, json) = (source_id.into(), json.into());
504 self.post(move |core, outbox, id, sequence, resolver| {
505 if !core.maps.contains_key(&id) {
506 return outbox.resolve(resolver, Err(missing_map()));
507 }
508 let background = core.background();
509 apply_command(
510 core,
511 id,
512 sequence,
513 outbox,
514 move |entry, outbox| match queue_geojson(entry, id, &source_id, &json, resolver, background, outbox) {
515 Ok(installed) => installed,
516 Err((error, resolver)) => {
517 outbox.resolve(resolver, Err(error));
518 None
519 }
520 },
521 |_, installed, applied, outbox| {
522 if let Some(resolver) = installed {
523 outbox.resolve(resolver, Ok(applied));
524 }
525 },
526 );
527 })
528 }
529
530 pub fn set_geojson_source_synchronous_tiling(
533 &self,
534 source_id: impl Into<String>,
535 enabled: bool,
536 ) -> Result<Completion<Applied>, Error> {
537 let source_id = source_id.into();
538 self.command(move |map| {
539 require_loaded(map)?;
540 map.edit_style(|style| style.apply(GeoJsonSourceType::set_synchronous(source_id, enabled)))
541 })
542 }
543
544 pub fn set_style_image(&self, image: StyleImage) -> Result<Completion<Applied>, Error> {
548 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::AddImage(Arc::new(image)))))
549 }
550
551 pub fn remove_style_image(&self, image_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
555 let image_id = image_id.into();
556 self.command(move |map| {
557 map.edit_loaded_style(|style| {
558 if style.image(&image_id).is_none() {
559 return Err(Error::not_found(format!("style image {} does not exist", quote(&image_id))));
560 }
561 style.apply(Edit::RemoveImage(image_id))
562 })
563 })
564 }
565
566 pub fn style_image(&self, image_id: impl Into<String>) -> Result<Completion<Option<Arc<StyleImage>>>, Error> {
568 let image_id = image_id.into();
569 self.query(move |map| Ok(map.style().image(&image_id).cloned()))
570 }
571
572 pub fn add_image_source(
577 &self,
578 source_id: impl Into<String>,
579 coordinates: [LatLng; 4],
580 image: PremultipliedImage,
581 ) -> Result<Completion<Applied>, Error> {
582 let source_id = source_id.into();
583 self.command(move |map| {
584 require_new_source(map, &source_id)?;
585 let options = ImageSourceOptions { url: None, coordinates };
586 let data = SourceData::<ImageSourceType>::with_description(options, Arc::new(image));
587 map.add_source(Source::new(&source_id, data))
588 })
589 }
590
591 pub fn set_image_source_url(
593 &self,
594 source_id: impl Into<String>,
595 url: impl Into<String>,
596 ) -> Result<Completion<Applied>, Error> {
597 let (source_id, url) = (source_id.into(), url.into());
598 self.command(move |map| {
599 require_loaded(map)?;
600 map.edit_style(|style| style.apply(ImageSourceType::set_url(source_id, url)))
601 })
602 }
603
604 pub fn set_image_source_image(
606 &self,
607 source_id: impl Into<String>,
608 image: PremultipliedImage,
609 ) -> Result<Completion<Applied>, Error> {
610 let source_id = source_id.into();
611 self.command(move |map| {
612 require_loaded(map)?;
613 map.edit_style(|style| style.apply(set_image(source_id, image)))
614 })
615 }
616
617 pub fn set_image_source_coordinates(
620 &self,
621 source_id: impl Into<String>,
622 coordinates: [LatLng; 4],
623 ) -> Result<Completion<Applied>, Error> {
624 let source_id = source_id.into();
625 self.command(move |map| {
626 require_loaded(map)?;
627 map.edit_style(|style| style.apply(ImageSourceType::set_coordinates(source_id, coordinates)))
628 })
629 }
630
631 pub fn image_source_coordinates(&self, source_id: impl Into<String>) -> Result<Completion<[LatLng; 4]>, Error> {
633 let source_id = source_id.into();
634 self.query(move |map| Ok(image_data(map, &source_id)?.options.coordinates))
635 }
636
637 pub fn style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Option<LayerInfo>>, Error> {
641 let layer_id = layer_id.into();
642 self.query(move |map| Ok(map.style().layer(&layer_id).map(layer_info)))
643 }
644
645 pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
647 self.query(|map| Ok(map.style().layers().map(layer_info).collect()))
648 }
649
650 pub fn move_style_layer(
653 &self,
654 layer_id: impl Into<String>,
655 before_layer_id: Option<String>,
656 ) -> Result<Completion<Applied>, Error> {
657 let layer_id = layer_id.into();
658 self.command(move |map| map.edit_loaded_style(|style| style.move_layer(&layer_id, before_layer_id.as_deref())))
659 }
660
661 pub fn set_style_transition_options(&self, options: TransitionOptions) -> Result<Completion<Applied>, Error> {
665 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::SetTransition(options))))
666 }
667
668 pub fn style_transition_options(&self) -> Result<Completion<TransitionOptions>, Error> {
670 self.query(|map| Ok(map.style().transition_options()))
671 }
672}
673
674fn queue_geojson(
679 entry: &mut MapEntry,
680 map_id: MapId,
681 source_id: &str,
682 json: &str,
683 resolver: Resolver<Applied>,
684 background: Background,
685 outbox: &mut Outbox,
686) -> Result<Option<Resolver<Applied>>, (Error, Resolver<Applied>)> {
687 let found = (|| {
688 require_loaded(&entry.core)?;
689 let data = geojson_data(&entry.core, source_id)?;
690 let geojson = parse_geojson(json)?;
691 if data.options.options.cluster {
692 check_clusterable(&geojson, data.options.options.filter.is_some())?;
693 }
694 let instance = find_source(&entry.core, source_id)?.instance();
695 let building = BuildFor::new(&entry.core, &data.options.options);
696 Ok((instance, data.load, building, data.options.synchronous_update, geojson))
697 })();
698 let (instance, load, building, synchronous, geojson) = match found {
699 Ok(found) => found,
700 Err(error) => return Err((error, resolver)),
701 };
702 if synchronous {
703 return match building.build(geojson) {
704 Ok(data) => {
705 let edit = set_data(source_id, Some(data));
706 match entry.core.edit_style(|style| style.apply(edit)) {
707 Ok(()) => Ok(Some(resolver)),
708 Err(error) => Err((error, resolver)),
709 }
710 }
711 Err(error) => Err((error, resolver)),
712 };
713 }
714 let update = entry.geojson_updates.0.entry(source_id.to_owned()).or_insert_with(|| GeoJsonUpdate {
715 instance,
716 building: None,
717 waiting: None,
718 });
719 if update.building.is_none() {
720 update.instance = instance;
721 start_geojson(update, map_id, source_id.to_owned(), (building, load), geojson, resolver, background);
722 } else if let Some((_, replaced)) = update.waiting.replace((geojson, resolver)) {
723 outbox.resolve(replaced, Err(Error::cancelled("newer data for the source replaced it")));
724 }
725 Ok(None)
726}
727
728struct BuildFor {
731 options: Arc<GeoJSONOptions>,
732 world: WorldMapping,
733}
734
735impl BuildFor {
736 fn new(map: &mln_engine::map::Map, options: &Arc<GeoJSONOptions>) -> Self {
738 BuildFor { options: Arc::clone(options), world: map.transform_state().view().world().clone() }
739 }
740
741 fn build(&self, geojson: GeoJson) -> Result<Arc<dyn GeoJSONData>, Error> {
743 create_geojson_data_in(geojson, &self.options, &self.world)
744 }
745}
746
747fn start_geojson(
751 update: &mut GeoJsonUpdate,
752 map_id: MapId,
753 source_id: String,
754 (building, load): (BuildFor, u64),
755 geojson: GeoJson,
756 resolver: Resolver<Applied>,
757 background: Background,
758) {
759 static BUILDS: AtomicU64 = AtomicU64::new(0);
762 let build = BUILDS.fetch_add(1, Ordering::Relaxed);
763 update.building = Some((build, resolver));
764 let next = background.clone();
765 background.pool.spawn(move || {
766 let data = building.build(geojson);
767 post(&background.queue, move |core, outbox| {
768 install_geojson(core, map_id, &source_id, (build, load), data, next, outbox);
769 });
770 });
771}
772
773fn current_geojson(map: &mln_engine::map::Map, id: &str, instance: SourceInstance) -> Option<(BuildFor, u64)> {
776 let source = map.source(id).filter(|source| source.instance() == instance)?;
777 let data = SourceData::<GeoJsonSourceType>::recover(source)?;
778 Some((BuildFor::new(map, &data.options.options), data.load))
779}
780
781fn install_geojson(
784 core: &mut RuntimeCore,
785 map_id: MapId,
786 source_id: &str,
787 (build, load): (u64, u64),
788 data: Result<Arc<dyn GeoJSONData>, Error>,
789 background: Background,
790 outbox: &mut Outbox,
791) {
792 flush(core, map_id, outbox);
793 let Some(entry) = core.maps.get_mut(&map_id) else { return };
794 let Some(update) = entry.geojson_updates.0.get_mut(source_id) else { return };
795 let Some((_, resolver)) = update.building.take_if(|(building, _)| *building == build) else { return };
796 let current = current_geojson(&entry.core, source_id, update.instance);
797 let installed = match data {
798 Err(error) => Err(error),
799 Ok(_) if current.as_ref().is_none_or(|(_, current_load)| *current_load != load) => {
800 Err(Error::cancelled("the source's data was replaced before this data was ready"))
801 }
802 Ok(data) => {
803 let edit = set_data(source_id, Some(data));
804 entry.core.edit_style(|style| style.apply(edit))
805 }
806 };
807 match (update.waiting.take(), current_geojson(&entry.core, source_id, update.instance)) {
808 (Some((geojson, next)), Some(current)) => {
809 start_geojson(update, map_id, source_id.to_owned(), current, geojson, next, background);
810 }
811 (Some((_, next)), None) => outbox.resolve(next, Err(Error::cancelled("the source left the style"))),
812 (None, _) => {
813 entry.geojson_updates.0.remove(source_id);
814 }
815 }
816 flush(core, map_id, outbox);
817 let Some(entry) = core.maps.get(&map_id) else { return };
818 outbox.resolve(resolver, installed.map(|()| entry.applied()));
819}