1use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::{Arc, Weak};
6
7use geojson::{GeoJson, GeometryValue};
8use mln_style::expression::Functions;
9use mln_style::image::Impl as StyleImage;
10use mln_style::source_type::{SourceData, StyleSourceType};
11use mln_style::sources::custom_geometry_source::{self, TileOptions};
12use mln_style::sources::geojson::{GeoJSONData, GeoJSONDataBuilder};
13use mln_style::sources::image::ImageSourceOptions;
14use mln_style::sources::{
15 CustomGeometrySourceHandle, CustomGeometrySourceType, CustomVectorSourceHandle, CustomVectorSourceType,
16 GeoJSONOptions, GeoJsonSourceType, ImageSourceType, RasterDemSourceType, RasterSourceType, TileDataFormat,
17 VectorSourceType, custom_vector_source, geojson_source,
18};
19use mln_style::{Edit, Source, SourceInstance, TransitionOptions};
20use mln_tile_id::CanonicalTileID;
21use mln_util::error::Error;
22use mln_util::geo::{LatLng, LatLngBounds};
23use mln_util::hash::HashMap;
24use mln_util::image::PremultipliedImage;
25use mln_util::pool::Pool;
26use mln_util::range::Range;
27use mln_util::tileset::{RasterEncoding, Scheme, VectorEncoding};
28
29use crate::completion::{Completion, Resolver};
30use crate::map::{Applied, Map, MapEntry, MapId, apply_command, flush, missing_map, style_not_loaded};
31use crate::runtime::{Background, Outbox, RuntimeCore, post};
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum SourceKind {
36 Vector,
37 Raster,
38 RasterDem,
39 GeoJson,
40 Image,
41 CustomGeometry,
42 CustomVector,
43}
44
45#[derive(Clone, Debug, PartialEq)]
47pub struct SourceTiles {
48 pub urls: Vec<String>,
49 pub zoom_range: Range<u8>,
50 pub scheme: Scheme,
51 pub bounds: Option<LatLngBounds>,
52 pub vector_encoding: Option<VectorEncoding>,
53 pub raster_encoding: Option<RasterEncoding>,
54}
55
56#[derive(Clone, Debug, PartialEq)]
59pub struct GeoJsonSourceOptions {
60 pub min_zoom: u8,
62 pub max_zoom: u8,
64 pub tolerance: f64,
66 pub buffer: u16,
68 pub line_metrics: bool,
70 pub cluster: bool,
72 pub cluster_radius: u16,
74 pub cluster_max_zoom: u8,
76 pub cluster_min_points: usize,
78 pub cluster_properties: Option<String>,
82 pub attribution: Option<String>,
83}
84
85impl Default for GeoJsonSourceOptions {
86 fn default() -> Self {
87 GeoJsonSourceOptions::from_core(&GeoJSONOptions::default())
88 }
89}
90
91impl GeoJsonSourceOptions {
92 fn from_core(options: &GeoJSONOptions) -> Self {
93 GeoJsonSourceOptions {
94 min_zoom: options.minzoom,
95 max_zoom: options.maxzoom,
96 tolerance: options.tolerance,
97 buffer: options.buffer,
98 line_metrics: options.line_metrics,
99 cluster: options.cluster,
100 cluster_radius: options.cluster_radius,
101 cluster_max_zoom: options.cluster_max_zoom,
102 cluster_min_points: options.cluster_min_points,
103 cluster_properties: cluster_properties_json(options),
104 attribution: options.attribution.clone(),
105 }
106 }
107
108 fn check(&self) -> Result<(), Error> {
111 if self.max_zoom > 24 {
114 return Err(Error::invalid_argument("max_zoom must be an integer within [0, 24]"));
115 }
116 if self.cluster_max_zoom > 30 {
117 return Err(Error::invalid_argument("cluster_max_zoom must be an integer within [0, 30]"));
118 }
119 if self.min_zoom > self.max_zoom {
120 return Err(Error::invalid_argument("min_zoom must be less than or equal to max_zoom"));
121 }
122 if !self.tolerance.is_finite() || self.tolerance < 0.0 {
123 return Err(Error::invalid_argument("tolerance must be finite and non-negative"));
124 }
125 if self.buffer > 512 {
126 return Err(Error::invalid_argument("buffer must be at most 512"));
127 }
128 if self.cluster_radius > 4095 {
129 return Err(Error::invalid_argument("cluster_radius must be at most 4095"));
130 }
131 Ok(())
132 }
133
134 pub fn check_cluster_properties(&self, functions: &Arc<Functions>) -> Result<(), Error> {
140 self.cluster_properties.as_deref().map_or(Ok(()), |json| parse_cluster_properties(json, functions).map(drop))
141 }
142
143 fn into_core(self, functions: &Arc<Functions>) -> Result<GeoJSONOptions, Error> {
146 let cluster_properties = match &self.cluster_properties {
147 Some(json) => parse_cluster_properties(json, functions)?,
148 None => mln_style::sources::geojson::ClusterProperties::default(),
149 };
150 Ok(GeoJSONOptions {
151 minzoom: self.min_zoom,
152 maxzoom: self.max_zoom,
153 tolerance: self.tolerance,
154 buffer: self.buffer,
155 line_metrics: self.line_metrics,
156 cluster: self.cluster,
157 cluster_radius: self.cluster_radius,
158 cluster_max_zoom: self.cluster_max_zoom,
159 cluster_min_points: self.cluster_min_points,
160 cluster_properties,
161 attribution: self.attribution,
162 ..GeoJSONOptions::default()
163 })
164 }
165}
166
167fn parse_cluster_properties(
172 json: &str,
173 functions: &Arc<Functions>,
174) -> Result<mln_style::sources::geojson::ClusterProperties, Error> {
175 let value: serde_json::Value = serde_json::from_str(json)
176 .map_err(|error| Error::invalid_argument(format!("cluster_properties is not valid JSON: {error}")))?;
177 if !value.is_object() {
178 return Err(Error::invalid_argument("cluster_properties must contain a JSON object"));
179 }
180 let wrapper = serde_json::json!({ "clusterProperties": value });
181 let mut error = mln_conversion::Error::default();
182 let options = mln_style::conversion::convert_geojson_options(
183 &mln_conversion::Convertible::from(&wrapper),
184 functions,
185 &mut error,
186 )
187 .ok_or_else(|| Error::invalid_argument(format!("GeoJSON source options: {}", error.message)))?;
188 Ok(options.cluster_properties)
189}
190
191#[derive(Clone, Debug)]
193pub struct SourceInfo {
194 pub id: String,
195 pub kind: SourceKind,
196 pub is_volatile: bool,
197 pub attribution: Option<String>,
200 pub url: Option<String>,
201 pub tiles: Option<SourceTiles>,
203 pub tile_size: Option<u16>,
205 pub vector_encoding: Option<VectorEncoding>,
207 pub geojson: Option<GeoJsonSourceOptions>,
208}
209
210#[derive(Clone, Debug, PartialEq)]
212pub struct LayerInfo {
213 pub id: String,
214 pub layer_type: &'static str,
217 pub source_id: Option<String>,
219 pub source_layer: Option<String>,
221 pub min_zoom: Option<f64>,
222 pub max_zoom: Option<f64>,
223 pub visible: bool,
224}
225
226pub struct CustomSourceCallbacks {
235 pub fetch_tile: Box<dyn Fn(CanonicalTileID) + Send + Sync>,
236 pub cancel_tile: Option<Box<dyn Fn(CanonicalTileID) + Send + Sync>>,
237}
238
239impl std::fmt::Debug for CustomSourceCallbacks {
240 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241 f.debug_struct("CustomSourceCallbacks")
242 .field("cancel_tile", &self.cancel_tile.is_some())
243 .finish_non_exhaustive()
244 }
245}
246
247fn tile_functions(
251 callbacks: &Arc<CustomSourceCallbacks>,
252) -> (Option<mln_style::custom_tile_loader::TileFunction>, Option<mln_style::custom_tile_loader::TileFunction>) {
253 let fetch: Weak<CustomSourceCallbacks> = Arc::downgrade(callbacks);
254 let fetch = Arc::new(move |tile: &CanonicalTileID| {
255 if let Some(callbacks) = fetch.upgrade() {
256 (callbacks.fetch_tile)(*tile);
257 }
258 });
259 let cancel = callbacks.cancel_tile.as_ref().map(|_| {
260 let cancel = Arc::downgrade(callbacks);
261 let cancel: mln_style::custom_tile_loader::TileFunction = Arc::new(move |tile: &CanonicalTileID| {
262 if let Some(callback) = cancel.upgrade().as_ref().and_then(|callbacks| callbacks.cancel_tile.as_ref()) {
263 callback(*tile);
264 }
265 });
266 cancel
267 });
268 (Some(fetch), cancel)
269}
270
271struct CallbackSource {
274 id: String,
275 instance: SourceInstance,
276 _callbacks: Arc<CustomSourceCallbacks>,
279}
280
281#[derive(Default)]
284pub(crate) struct CallbackSources(Vec<CallbackSource>);
285
286struct GeoJsonUpdate {
289 instance: SourceInstance,
292 building: Option<(u64, Resolver<Applied>)>,
296 waiting: Option<(GeoJson, Resolver<Applied>)>,
297}
298
299#[derive(Default)]
301pub(crate) struct GeoJsonUpdates(HashMap<String, GeoJsonUpdate>);
302
303pub(crate) fn reconcile(entry: &mut MapEntry, outbox: &mut Outbox) {
308 let map = &entry.core;
309 let present = |id: &str, instance: SourceInstance| map.source(id).is_some_and(|found| found.instance() == instance);
310 let (kept, gone): (Vec<_>, Vec<_>) =
311 std::mem::take(&mut entry.callback_sources.0).into_iter().partition(|held| present(&held.id, held.instance));
312 entry.callback_sources.0 = kept;
313 if !gone.is_empty() {
314 outbox.push(move || drop(gone));
315 }
316 entry.geojson_updates.0.retain(|id, update| {
317 if present(id, update.instance) {
318 return true;
319 }
320 let cancelled = || Err(Error::cancelled("the source left the style before its data was ready"));
321 if let Some((_, resolver)) = update.building.take() {
322 outbox.resolve(resolver, cancelled());
323 }
324 if let Some((_, resolver)) = update.waiting.take() {
325 outbox.resolve(resolver, cancelled());
326 }
327 false
328 });
329}
330
331pub(crate) fn release(entry: &mut MapEntry, outbox: &mut Outbox) {
334 let held = std::mem::take(&mut entry.callback_sources.0);
335 if !held.is_empty() {
336 outbox.push(move || drop(held));
337 }
338 for (_, mut update) in entry.geojson_updates.0.drain() {
339 let cancelled = || Err(Error::cancelled("the map was released before the data was ready"));
340 if let Some((_, resolver)) = update.building.take() {
341 outbox.resolve(resolver, cancelled());
342 }
343 if let Some((_, resolver)) = update.waiting.take() {
344 outbox.resolve(resolver, cancelled());
345 }
346 }
347}
348
349fn quote(id: &str) -> String {
350 format!("\"{id}\"")
351}
352
353fn require_loaded(map: &mln_map::Map) -> Result<(), Error> {
354 if map.style_document_loaded() { Ok(()) } else { Err(style_not_loaded()) }
355}
356
357fn source_not_found(id: &str) -> Error {
358 Error::not_found(format!("source {} does not exist", quote(id)))
359}
360
361fn find_source<'a>(map: &'a mln_map::Map, id: &str) -> Result<&'a Source, Error> {
362 map.source(id).ok_or_else(|| source_not_found(id))
363}
364
365fn not_a(id: &str, kind: &str) -> Error {
368 Error::invalid_argument(format!("source {} is not {kind}", quote(id)))
369}
370
371fn geojson_data<'a>(map: &'a mln_map::Map, id: &str) -> Result<&'a SourceData<GeoJsonSourceType>, Error> {
373 SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "a GeoJSON source"))
374}
375
376fn image_data<'a>(map: &'a mln_map::Map, id: &str) -> Result<&'a SourceData<ImageSourceType>, Error> {
378 SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "an image source"))
379}
380
381fn require_new_source(map: &mln_map::Map, id: &str) -> Result<(), Error> {
382 require_loaded(map)?;
383 if map.source(id).is_some() {
384 return Err(Error::already_exists(format!("source {} already exists", quote(id))));
385 }
386 Ok(())
387}
388
389impl SourceKind {
390 fn of(source: &Source) -> Option<SourceKind> {
393 let name = source.info().name;
394 [
395 (VectorSourceType::INFO, SourceKind::Vector),
396 (RasterSourceType::INFO, SourceKind::Raster),
397 (RasterDemSourceType::INFO, SourceKind::RasterDem),
398 (GeoJsonSourceType::INFO, SourceKind::GeoJson),
399 (ImageSourceType::INFO, SourceKind::Image),
400 (CustomGeometrySourceType::INFO, SourceKind::CustomGeometry),
401 (CustomVectorSourceType::INFO, SourceKind::CustomVector),
402 ]
403 .into_iter()
404 .find_map(|(info, kind)| (info.name == name).then_some(kind))
405 }
406}
407
408fn cluster_properties_json(options: &GeoJSONOptions) -> Option<String> {
410 if options.cluster_properties.is_empty() {
411 return None;
412 }
413 let members = options
414 .cluster_properties
415 .iter()
416 .map(|(key, (map, reduce))| {
417 let pair = feature::Value::Array(vec![reduce.serialize(), map.serialize()]);
418 (key.clone(), mln_conversion::value_to_json(&pair))
419 })
420 .collect::<serde_json::Map<_, _>>();
421 Some(serde_json::Value::Object(members).to_string())
422}
423
424fn source_info(source: &Source) -> Option<SourceInfo> {
427 let kind = SourceKind::of(source)?;
428 let summary = source.data().summary();
429 Some(SourceInfo {
430 id: source.id().to_owned(),
431 kind,
432 is_volatile: source.common().volatile,
433 attribution: source.data().attribution().filter(|attribution| !attribution.is_empty()),
434 url: summary.url,
435 tiles: summary.inline_tileset.map(|tileset| SourceTiles {
436 urls: tileset.tiles,
437 zoom_range: tileset.zoom_range,
438 scheme: tileset.scheme,
439 bounds: tileset.bounds,
440 vector_encoding: tileset.vector_encoding,
441 raster_encoding: tileset.raster_encoding,
442 }),
443 tile_size: summary.tile_size,
444 vector_encoding: summary.vector_encoding,
445 geojson: summary.geojson.map(|options| GeoJsonSourceOptions::from_core(&options)),
446 })
447}
448
449fn layer_info(layer: &mln_style::Layer) -> LayerInfo {
450 LayerInfo {
451 id: layer.get_id().to_owned(),
452 layer_type: layer.info().name,
453 source_id: Some(layer.get_source_id()).filter(|id| !id.is_empty()).map(str::to_owned),
454 source_layer: Some(layer.get_source_layer()).filter(|id| !id.is_empty()).map(str::to_owned),
455 min_zoom: Some(f64::from(layer.get_min_zoom())).filter(|zoom| zoom.is_finite()),
456 max_zoom: Some(f64::from(layer.get_max_zoom())).filter(|zoom| zoom.is_finite()),
457 visible: layer.get_visibility() != mln_style_types::VisibilityType::None,
458 }
459}
460
461fn parse_geojson(json: &str) -> Result<GeoJson, Error> {
463 serde_json::from_str(json).map_err(|error| {
464 let what = if error.is_data() { "invalid" } else { "not valid JSON" };
465 Error::invalid_argument(format!("GeoJSON data is {what}: {error}"))
466 })
467}
468
469fn check_clusterable(geojson: &GeoJson) -> Result<(), Error> {
473 let features = match geojson {
474 GeoJson::FeatureCollection(collection) => &collection.features,
475 other => {
476 let found = if matches!(other, GeoJson::Feature(_)) { "a single feature" } else { "a bare geometry" };
477 return Err(Error::invalid_argument(format!(
478 "clustered GeoJSON data requires a feature collection; the data is {found}"
479 )));
480 }
481 };
482 let point = |feature: &geojson::Feature| matches!(&feature.geometry, Some(g) if matches!(g.value, GeometryValue::Point { .. }));
483 match features.iter().position(|feature| !point(feature)) {
484 None => Ok(()),
485 Some(index) => Err(Error::invalid_argument(format!(
486 "clustered GeoJSON data requires point geometry on every feature; feature {index} has {} geometry",
487 features[index].geometry.as_ref().map_or("no", |g| g.value.type_name())
488 ))),
489 }
490}
491
492fn feature_collection(geojson: GeoJson) -> GeoJson {
495 match geojson {
496 GeoJson::FeatureCollection(_) => geojson,
497 GeoJson::Feature(feature) => GeoJson::from(vec![feature]),
498 GeoJson::Geometry(geometry) => GeoJson::from(vec![geojson::Feature::from(geometry)]),
499 }
500}
501
502impl Map {
503 pub fn set_global_state_property(
508 &self,
509 name: impl Into<String>,
510 json: impl Into<String>,
511 ) -> Result<Completion<Applied>, Error> {
512 let (name, json) = (name.into(), json.into());
513 self.command(move |map| map.edit_loaded_style(|style| style.set_global_state_property_json(&name, &json)))
514 }
515
516 pub fn global_state(&self) -> Result<Completion<String>, Error> {
518 self.query(|map| Ok(map.style().global_state_json()))
519 }
520
521 pub fn style_source(&self, source_id: impl Into<String>) -> Result<Completion<Option<SourceInfo>>, Error> {
525 let source_id = source_id.into();
526 self.query(move |map| Ok(map.source(&source_id).and_then(source_info)))
527 }
528
529 pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
531 self.query(|map| Ok(map.sources().filter_map(source_info).collect()))
532 }
533
534 pub fn set_style_source_volatile(
536 &self,
537 source_id: impl Into<String>,
538 is_volatile: bool,
539 ) -> Result<Completion<Applied>, Error> {
540 let source_id = source_id.into();
541 self.command(move |map| {
542 require_loaded(map)?;
543 let mut common = *find_source(map, &source_id)?.common();
544 common.volatile = is_volatile;
545 map.edit_style(|style| style.apply(Edit::SetSourceCommon { id: source_id, common }))
546 })
547 }
548
549 pub fn add_geojson_source(
558 &self,
559 source_id: impl Into<String>,
560 options: GeoJsonSourceOptions,
561 ) -> Result<Completion<Applied>, Error> {
562 options.check()?;
563 let source_id = source_id.into();
564 self.command(move |map| {
565 let functions = Arc::clone(map.style().registry().functions());
566 let options = options.into_core(&functions)?;
567 require_new_source(map, &source_id)?;
568 map.add_source(geojson_source(&source_id, Arc::new(options)))
569 })
570 }
571
572 pub fn set_geojson_source_url(
576 &self,
577 source_id: impl Into<String>,
578 url: impl Into<String>,
579 ) -> Result<Completion<Applied>, Error> {
580 let (source_id, url) = (source_id.into(), url.into());
581 self.send(
582 move |entry, outbox| {
583 require_loaded(&entry.core)?;
584 let edit = GeoJsonSourceType::set_url(source_id.clone(), url);
585 entry.core.edit_style(|style| style.apply(edit))?;
586 if let Some((_, resolver)) =
587 entry.geojson_updates.0.get_mut(&source_id).and_then(|update| update.waiting.take())
588 {
589 outbox.resolve(resolver, Err(Error::cancelled("the source's URL replaced its data")));
590 }
591 Ok(())
592 },
593 |(), entry| entry.applied(),
594 )
595 }
596
597 pub fn set_geojson_source_data(
615 &self,
616 source_id: impl Into<String>,
617 json: impl Into<String>,
618 ) -> Result<Completion<Applied>, Error> {
619 let (source_id, json) = (source_id.into(), json.into());
620 self.post(move |core, outbox, id, sequence, resolver| {
621 if !core.maps.contains_key(&id) {
622 return outbox.resolve(resolver, Err(missing_map()));
623 }
624 let background = core.background();
625 apply_command(
626 core,
627 id,
628 sequence,
629 outbox,
630 move |entry, outbox| match queue_geojson(entry, id, &source_id, &json, resolver, background, outbox) {
631 Ok(installed) => installed,
632 Err((error, resolver)) => {
633 outbox.resolve(resolver, Err(error));
634 None
635 }
636 },
637 |_, installed, applied, outbox| {
638 if let Some(resolver) = installed {
639 outbox.resolve(resolver, Ok(applied));
640 }
641 },
642 );
643 })
644 }
645
646 pub fn set_geojson_source_synchronous_tiling(
649 &self,
650 source_id: impl Into<String>,
651 enabled: bool,
652 ) -> Result<Completion<Applied>, Error> {
653 let source_id = source_id.into();
654 self.command(move |map| {
655 require_loaded(map)?;
656 map.edit_style(|style| style.apply(GeoJsonSourceType::set_synchronous(source_id, enabled)))
657 })
658 }
659
660 pub fn add_custom_geometry_source(
668 &self,
669 source_id: impl Into<String>,
670 callbacks: CustomSourceCallbacks,
671 zoom_range: Range<u8>,
672 tile_options: TileOptions,
673 ) -> Result<Completion<Applied>, Error> {
674 let (source_id, callbacks) = (source_id.into(), Arc::new(callbacks));
675 self.send(
676 move |entry, outbox| {
677 add_callback_source(entry, outbox, source_id, callbacks, |id, callbacks, pool| {
678 let (fetch_tile_function, cancel_tile_function) = tile_functions(callbacks);
679 let options = custom_geometry_source::Options {
680 fetch_tile_function,
681 cancel_tile_function,
682 zoom_range,
683 tile_options,
684 };
685 custom_geometry_source::create(&id, options, pool)
686 .map_err(|error| Error::invalid_argument(error.to_string()))
687 })
688 },
689 |(), entry| entry.applied(),
690 )
691 }
692
693 pub fn add_custom_vector_source(
697 &self,
698 source_id: impl Into<String>,
699 callbacks: CustomSourceCallbacks,
700 zoom_range: Range<u8>,
701 ) -> Result<Completion<Applied>, Error> {
702 let (source_id, callbacks) = (source_id.into(), Arc::new(callbacks));
703 self.send(
704 move |entry, outbox| {
705 add_callback_source(entry, outbox, source_id, callbacks, |id, callbacks, pool| {
706 let (fetch_tile_function, cancel_tile_function) = tile_functions(callbacks);
707 let options =
708 custom_vector_source::Options { fetch_tile_function, cancel_tile_function, zoom_range };
709 Ok(custom_vector_source::create(&id, options, pool))
710 })
711 },
712 |(), entry| entry.applied(),
713 )
714 }
715
716 pub fn set_custom_geometry_source_tile_data(
720 &self,
721 source_id: impl Into<String>,
722 tile_id: CanonicalTileID,
723 json: impl Into<String>,
724 ) -> Result<Completion<Applied>, Error> {
725 let (source_id, json) = (source_id.into(), json.into());
726 self.command(move |map| {
727 let geojson = feature_collection(parse_geojson(&json)?);
728 custom_geometry(map, &source_id)?.set_tile_data(tile_id, geojson);
729 Ok(())
730 })
731 }
732
733 pub fn set_custom_geometry_source_tile_error(
735 &self,
736 source_id: impl Into<String>,
737 tile_id: CanonicalTileID,
738 message: impl Into<String>,
739 ) -> Result<Completion<Applied>, Error> {
740 let (source_id, message) = (source_id.into(), message.into());
741 self.command(move |map| {
742 custom_geometry(map, &source_id)?.set_tile_error(tile_id, Error::native(message));
743 Ok(())
744 })
745 }
746
747 pub fn invalidate_custom_geometry_source_tile(
750 &self,
751 source_id: impl Into<String>,
752 tile_id: CanonicalTileID,
753 ) -> Result<Completion<Applied>, Error> {
754 let source_id = source_id.into();
755 self.command(move |map| {
756 custom_geometry(map, &source_id)?.invalidate_tile(tile_id);
757 Ok(())
758 })
759 }
760
761 pub fn invalidate_custom_geometry_source_region(
764 &self,
765 source_id: impl Into<String>,
766 bounds: LatLngBounds,
767 ) -> Result<Completion<Applied>, Error> {
768 let source_id = source_id.into();
769 self.command(move |map| {
770 custom_geometry(map, &source_id)?.invalidate_region(bounds);
771 Ok(())
772 })
773 }
774
775 pub fn set_custom_vector_source_tile_data(
779 &self,
780 source_id: impl Into<String>,
781 tile_id: CanonicalTileID,
782 data: Option<Vec<u8>>,
783 format: TileDataFormat,
784 ) -> Result<Completion<Applied>, Error> {
785 let source_id = source_id.into();
786 self.command(move |map| {
787 custom_vector(map, &source_id)?.set_tile_data(tile_id, data.map(Arc::new), format);
788 Ok(())
789 })
790 }
791
792 pub fn set_custom_vector_source_tile_error(
794 &self,
795 source_id: impl Into<String>,
796 tile_id: CanonicalTileID,
797 message: impl Into<String>,
798 ) -> Result<Completion<Applied>, Error> {
799 let (source_id, message) = (source_id.into(), message.into());
800 self.command(move |map| {
801 custom_vector(map, &source_id)?.set_tile_error(tile_id, Error::native(message));
802 Ok(())
803 })
804 }
805
806 pub fn invalidate_custom_vector_source_tile(
809 &self,
810 source_id: impl Into<String>,
811 tile_id: CanonicalTileID,
812 ) -> Result<Completion<Applied>, Error> {
813 let source_id = source_id.into();
814 self.command(move |map| {
815 custom_vector(map, &source_id)?.invalidate_tile(tile_id);
816 Ok(())
817 })
818 }
819
820 pub fn invalidate_custom_vector_source_region(
823 &self,
824 source_id: impl Into<String>,
825 bounds: LatLngBounds,
826 ) -> Result<Completion<Applied>, Error> {
827 let source_id = source_id.into();
828 self.command(move |map| {
829 custom_vector(map, &source_id)?.invalidate_region(bounds);
830 Ok(())
831 })
832 }
833
834 pub fn set_style_image(&self, image: StyleImage) -> Result<Completion<Applied>, Error> {
838 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::AddImage(Arc::new(image)))))
839 }
840
841 pub fn remove_style_image(&self, image_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
845 let image_id = image_id.into();
846 self.command(move |map| {
847 map.edit_loaded_style(|style| {
848 if style.get_image(&image_id).is_none() {
849 return Err(Error::not_found(format!("style image {} does not exist", quote(&image_id))));
850 }
851 style.apply(Edit::RemoveImage(image_id))
852 })
853 })
854 }
855
856 pub fn style_image(&self, image_id: impl Into<String>) -> Result<Completion<Option<Arc<StyleImage>>>, Error> {
858 let image_id = image_id.into();
859 self.query(move |map| Ok(map.style().get_image(&image_id).cloned()))
860 }
861
862 pub fn add_image_source(
867 &self,
868 source_id: impl Into<String>,
869 coordinates: [LatLng; 4],
870 image: PremultipliedImage,
871 ) -> Result<Completion<Applied>, Error> {
872 let source_id = source_id.into();
873 self.command(move |map| {
874 require_new_source(map, &source_id)?;
875 let options = ImageSourceOptions { url: None, coordinates };
876 let data = SourceData::<ImageSourceType>::with_description(options, Arc::new(image));
877 map.add_source(Source::new(&source_id, data))
878 })
879 }
880
881 pub fn set_image_source_url(
883 &self,
884 source_id: impl Into<String>,
885 url: impl Into<String>,
886 ) -> Result<Completion<Applied>, Error> {
887 let (source_id, url) = (source_id.into(), url.into());
888 self.command(move |map| {
889 require_loaded(map)?;
890 map.edit_style(|style| style.apply(ImageSourceType::set_url(source_id, url)))
891 })
892 }
893
894 pub fn set_image_source_image(
896 &self,
897 source_id: impl Into<String>,
898 image: PremultipliedImage,
899 ) -> Result<Completion<Applied>, Error> {
900 let source_id = source_id.into();
901 self.command(move |map| {
902 require_loaded(map)?;
903 map.edit_style(|style| style.apply(ImageSourceType::set_image(source_id, image)))
904 })
905 }
906
907 pub fn set_image_source_coordinates(
910 &self,
911 source_id: impl Into<String>,
912 coordinates: [LatLng; 4],
913 ) -> Result<Completion<Applied>, Error> {
914 let source_id = source_id.into();
915 self.command(move |map| {
916 require_loaded(map)?;
917 map.edit_style(|style| style.apply(ImageSourceType::set_coordinates(source_id, coordinates)))
918 })
919 }
920
921 pub fn image_source_coordinates(&self, source_id: impl Into<String>) -> Result<Completion<[LatLng; 4]>, Error> {
923 let source_id = source_id.into();
924 self.query(move |map| Ok(image_data(map, &source_id)?.options.coordinates))
925 }
926
927 pub fn style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Option<LayerInfo>>, Error> {
931 let layer_id = layer_id.into();
932 self.query(move |map| Ok(map.style().get_layer(&layer_id).map(layer_info)))
933 }
934
935 pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
937 self.query(|map| Ok(map.style().get_layers().map(layer_info).collect()))
938 }
939
940 pub fn move_style_layer(
943 &self,
944 layer_id: impl Into<String>,
945 before_layer_id: Option<String>,
946 ) -> Result<Completion<Applied>, Error> {
947 let layer_id = layer_id.into();
948 self.command(move |map| map.edit_loaded_style(|style| style.move_layer(&layer_id, before_layer_id.as_deref())))
949 }
950
951 pub fn set_style_transition_options(&self, options: TransitionOptions) -> Result<Completion<Applied>, Error> {
955 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::SetTransition(options))))
956 }
957
958 pub fn style_transition_options(&self) -> Result<Completion<TransitionOptions>, Error> {
960 self.query(|map| Ok(map.style().get_transition_options()))
961 }
962}
963
964fn add_callback_source(
968 entry: &mut MapEntry,
969 outbox: &mut Outbox,
970 id: String,
971 callbacks: Arc<CustomSourceCallbacks>,
972 make: impl FnOnce(String, &Arc<CustomSourceCallbacks>, &Pool) -> Result<Source, Error>,
973) -> Result<(), Error> {
974 let map = &mut entry.core;
975 let pool = map.pool().clone();
976 let added = require_new_source(map, &id).and_then(|()| {
977 let source = make(id.clone(), &callbacks, &pool)?;
978 let instance = source.instance();
979 map.add_source(source)?;
980 Ok(instance)
981 });
982 match added {
983 Ok(instance) => {
984 entry.callback_sources.0.push(CallbackSource { id, instance, _callbacks: callbacks });
985 Ok(())
986 }
987 Err(error) => {
988 outbox.push(move || drop(callbacks));
989 Err(error)
990 }
991 }
992}
993
994fn custom_geometry(map: &mln_map::Map, id: &str) -> Result<CustomGeometrySourceHandle, Error> {
995 CustomGeometrySourceHandle::of(find_source(map, id)?).ok_or_else(|| not_a(id, "a custom geometry source"))
996}
997
998fn custom_vector(map: &mln_map::Map, id: &str) -> Result<CustomVectorSourceHandle, Error> {
999 CustomVectorSourceHandle::of(find_source(map, id)?).ok_or_else(|| not_a(id, "a custom vector source"))
1000}
1001
1002fn queue_geojson(
1007 entry: &mut MapEntry,
1008 map_id: MapId,
1009 source_id: &str,
1010 json: &str,
1011 resolver: Resolver<Applied>,
1012 background: Background,
1013 outbox: &mut Outbox,
1014) -> Result<Option<Resolver<Applied>>, (Error, Resolver<Applied>)> {
1015 let found = (|| {
1016 require_loaded(&entry.core)?;
1017 let data = geojson_data(&entry.core, source_id)?;
1018 let geojson = parse_geojson(json)?;
1019 if data.options.options.cluster {
1020 check_clusterable(&geojson)?;
1021 }
1022 let instance = find_source(&entry.core, source_id)?.instance();
1023 Ok((instance, data.load, data.options.data_builder(), data.options.synchronous_update, geojson))
1024 })();
1025 let (instance, load, builder, synchronous, geojson) = match found {
1026 Ok(found) => found,
1027 Err(error) => return Err((error, resolver)),
1028 };
1029 if synchronous {
1030 return match builder.build(geojson) {
1031 Ok(data) => {
1032 let edit = GeoJsonSourceType::set_data(source_id, Some(data));
1033 match entry.core.edit_style(|style| style.apply(edit)) {
1034 Ok(()) => Ok(Some(resolver)),
1035 Err(error) => Err((error, resolver)),
1036 }
1037 }
1038 Err(error) => Err((error, resolver)),
1039 };
1040 }
1041 let update = entry.geojson_updates.0.entry(source_id.to_owned()).or_insert_with(|| GeoJsonUpdate {
1042 instance,
1043 building: None,
1044 waiting: None,
1045 });
1046 if update.building.is_none() {
1047 update.instance = instance;
1048 start_geojson(update, map_id, source_id.to_owned(), (builder, load), geojson, resolver, background);
1049 } else if let Some((_, replaced)) = update.waiting.replace((geojson, resolver)) {
1050 outbox.resolve(replaced, Err(Error::cancelled("newer data for the source replaced it")));
1051 }
1052 Ok(None)
1053}
1054
1055fn start_geojson(
1059 update: &mut GeoJsonUpdate,
1060 map_id: MapId,
1061 source_id: String,
1062 (builder, load): (GeoJSONDataBuilder, u64),
1063 geojson: GeoJson,
1064 resolver: Resolver<Applied>,
1065 background: Background,
1066) {
1067 static BUILDS: AtomicU64 = AtomicU64::new(0);
1070 let build = BUILDS.fetch_add(1, Ordering::Relaxed);
1071 update.building = Some((build, resolver));
1072 let next = background.clone();
1073 background.pool.spawn(move || {
1074 let data = builder.build(geojson);
1075 post(&background.queue, move |core, outbox| {
1076 install_geojson(core, map_id, &source_id, (build, load), data, next, outbox);
1077 });
1078 });
1079}
1080
1081fn current_geojson(map: &mln_map::Map, id: &str, instance: SourceInstance) -> Option<(GeoJSONDataBuilder, u64)> {
1084 let source = map.source(id).filter(|source| source.instance() == instance)?;
1085 let data = SourceData::<GeoJsonSourceType>::recover(source)?;
1086 Some((data.options.data_builder(), data.load))
1087}
1088
1089fn install_geojson(
1092 core: &mut RuntimeCore,
1093 map_id: MapId,
1094 source_id: &str,
1095 (build, load): (u64, u64),
1096 data: Result<Arc<dyn GeoJSONData>, Error>,
1097 background: Background,
1098 outbox: &mut Outbox,
1099) {
1100 flush(core, map_id, outbox);
1101 let Some(entry) = core.maps.get_mut(&map_id) else { return };
1102 let Some(update) = entry.geojson_updates.0.get_mut(source_id) else { return };
1103 let Some((_, resolver)) = update.building.take_if(|(building, _)| *building == build) else { return };
1104 let current = current_geojson(&entry.core, source_id, update.instance);
1105 let installed = match data {
1106 Err(error) => Err(error),
1107 Ok(_) if current.as_ref().is_none_or(|(_, current_load)| *current_load != load) => {
1108 Err(Error::cancelled("the source's data was replaced before this data was ready"))
1109 }
1110 Ok(data) => {
1111 let edit = GeoJsonSourceType::set_data(source_id, Some(data));
1112 entry.core.edit_style(|style| style.apply(edit))
1113 }
1114 };
1115 match (update.waiting.take(), current_geojson(&entry.core, source_id, update.instance)) {
1116 (Some((geojson, next)), Some(current)) => {
1117 start_geojson(update, map_id, source_id.to_owned(), current, geojson, next, background);
1118 }
1119 (Some((_, next)), None) => outbox.resolve(next, Err(Error::cancelled("the source left the style"))),
1120 (None, _) => {
1121 entry.geojson_updates.0.remove(source_id);
1122 }
1123 }
1124 flush(core, map_id, outbox);
1125 let Some(entry) = core.maps.get(&map_id) else { return };
1126 outbox.resolve(resolver, installed.map(|()| entry.applied()));
1127}