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::{SourceData, StyleSourceType};
11use mln_style::sources::custom::{CustomVectorTileData, TileFunction};
12use mln_style::sources::custom_geometry_source::{self, TileOptions};
13use mln_style::sources::geojson::{GeoJSONData, GeoJSONDataBuilder};
14use mln_style::sources::image::ImageSourceOptions;
15use mln_style::sources::{
16 CustomGeometrySourceType, CustomSourceHandle, CustomVectorSourceType, GeoJSONOptions, GeoJsonSourceType,
17 ImageSourceType, RasterDemSourceType, RasterSourceType, TileDataFormat, VectorSourceType, custom_vector_source,
18 geojson_source,
19};
20use mln_style::{Edit, Source, SourceInstance, TransitionOptions};
21use mln_tile_id::CanonicalTileID;
22use mln_util::error::Error;
23use mln_util::geo::{LatLng, LatLngBounds};
24use mln_util::hash::HashMap;
25use mln_util::image::PremultipliedImage;
26use mln_util::range::Range;
27use mln_util::tileset::{RasterEncoding, Scheme, VectorEncoding};
28use parking_lot::Mutex;
29
30use crate::completion::{Completion, Resolver};
31use crate::map::{Applied, Map, MapEntry, MapId, apply_command, flush, missing_map, style_not_loaded};
32use crate::runtime::{Background, Outbox, RuntimeCore, post};
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum SourceKind {
37 Vector,
38 Raster,
39 RasterDem,
40 GeoJson,
41 Image,
42 CustomGeometry,
43 CustomVector,
44}
45
46#[derive(Clone, Debug, PartialEq)]
48pub struct SourceTiles {
49 pub urls: Vec<String>,
50 pub zoom_range: Range<u8>,
51 pub scheme: Scheme,
52 pub bounds: Option<LatLngBounds>,
53 pub vector_encoding: Option<VectorEncoding>,
54 pub raster_encoding: Option<RasterEncoding>,
55}
56
57#[derive(Clone, Debug, PartialEq)]
60pub struct GeoJsonSourceOptions {
61 pub min_zoom: u8,
63 pub max_zoom: u8,
65 pub tolerance: f64,
67 pub buffer: u16,
69 pub line_metrics: bool,
71 pub cluster: bool,
73 pub cluster_radius: u16,
75 pub cluster_max_zoom: u8,
77 pub cluster_min_points: usize,
79 pub cluster_properties: Option<String>,
83 pub attribution: Option<String>,
84}
85
86impl Default for GeoJsonSourceOptions {
87 fn default() -> Self {
88 GeoJsonSourceOptions::from_core(&GeoJSONOptions::default())
89 }
90}
91
92impl GeoJsonSourceOptions {
93 fn from_core(options: &GeoJSONOptions) -> Self {
94 GeoJsonSourceOptions {
95 min_zoom: options.minzoom,
96 max_zoom: options.maxzoom,
97 tolerance: options.tolerance,
98 buffer: options.buffer,
99 line_metrics: options.line_metrics,
100 cluster: options.cluster,
101 cluster_radius: options.cluster_radius,
102 cluster_max_zoom: options.cluster_max_zoom,
103 cluster_min_points: options.cluster_min_points,
104 cluster_properties: cluster_properties_json(options),
105 attribution: options.attribution.clone(),
106 }
107 }
108
109 fn check(&self) -> Result<(), Error> {
112 if self.max_zoom > 24 {
115 return Err(Error::invalid_argument("max_zoom must be an integer within [0, 24]"));
116 }
117 if self.cluster_max_zoom > 30 {
118 return Err(Error::invalid_argument("cluster_max_zoom must be an integer within [0, 30]"));
119 }
120 if self.min_zoom > self.max_zoom {
121 return Err(Error::invalid_argument("min_zoom must be less than or equal to max_zoom"));
122 }
123 if !self.tolerance.is_finite() || self.tolerance < 0.0 {
124 return Err(Error::invalid_argument("tolerance must be finite and non-negative"));
125 }
126 if self.buffer > 512 {
127 return Err(Error::invalid_argument("buffer must be at most 512"));
128 }
129 if self.cluster_radius > 4095 {
130 return Err(Error::invalid_argument("cluster_radius must be at most 4095"));
131 }
132 Ok(())
133 }
134
135 pub fn check_cluster_properties(&self, functions: &Arc<Functions>) -> Result<(), Error> {
141 self.cluster_properties.as_deref().map_or(Ok(()), |json| parse_cluster_properties(json, functions).map(drop))
142 }
143
144 fn into_core(self, functions: &Arc<Functions>) -> Result<GeoJSONOptions, Error> {
147 let cluster_properties = match &self.cluster_properties {
148 Some(json) => parse_cluster_properties(json, functions)?,
149 None => mln_style::sources::geojson::ClusterProperties::default(),
150 };
151 Ok(GeoJSONOptions {
152 minzoom: self.min_zoom,
153 maxzoom: self.max_zoom,
154 tolerance: self.tolerance,
155 buffer: self.buffer,
156 line_metrics: self.line_metrics,
157 cluster: self.cluster,
158 cluster_radius: self.cluster_radius,
159 cluster_max_zoom: self.cluster_max_zoom,
160 cluster_min_points: self.cluster_min_points,
161 cluster_properties,
162 attribution: self.attribution,
163 ..GeoJSONOptions::default()
164 })
165 }
166}
167
168fn parse_cluster_properties(
173 json: &str,
174 functions: &Arc<Functions>,
175) -> Result<mln_style::sources::geojson::ClusterProperties, Error> {
176 let value: serde_json::Value = serde_json::from_str(json)
177 .map_err(|error| Error::invalid_argument(format!("cluster_properties is not valid JSON: {error}")))?;
178 if !value.is_object() {
179 return Err(Error::invalid_argument("cluster_properties must contain a JSON object"));
180 }
181 let wrapper = serde_json::json!({ "clusterProperties": value });
182 let mut error = mln_style::conversion::Error::default();
183 let options = mln_style::conversion::convert_geojson_options(
184 &mln_style::conversion::Convertible::from(&wrapper),
185 functions,
186 &mut error,
187 )
188 .ok_or_else(|| Error::invalid_argument(format!("GeoJSON source options: {}", error.message)))?;
189 Ok(options.cluster_properties)
190}
191
192#[derive(Clone, Debug)]
194pub struct SourceInfo {
195 pub id: String,
196 pub kind: SourceKind,
197 pub is_volatile: bool,
198 pub attribution: Option<String>,
201 pub url: Option<String>,
202 pub tiles: Option<SourceTiles>,
204 pub tile_size: Option<u16>,
206 pub vector_encoding: Option<VectorEncoding>,
208 pub geojson: Option<GeoJsonSourceOptions>,
209}
210
211#[derive(Clone, Debug, PartialEq)]
213pub struct LayerInfo {
214 pub id: String,
215 pub layer_type: &'static str,
218 pub source_id: Option<String>,
220 pub source_layer: Option<String>,
222 pub min_zoom: Option<f64>,
223 pub max_zoom: Option<f64>,
224 pub visible: bool,
225}
226
227pub struct CustomSourceCallbacks {
236 pub fetch_tile: Box<dyn Fn(CanonicalTileID) + Send + Sync>,
237 pub cancel_tile: Option<Box<dyn Fn(CanonicalTileID) + Send + Sync>>,
238}
239
240impl std::fmt::Debug for CustomSourceCallbacks {
241 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242 f.debug_struct("CustomSourceCallbacks")
243 .field("cancel_tile", &self.cancel_tile.is_some())
244 .finish_non_exhaustive()
245 }
246}
247
248fn tile_functions<D: Clone + 'static>(
253 callbacks: &Arc<CustomSourceCallbacks>,
254 handles: &Arc<SourceHandles<D>>,
255) -> (Option<TileFunction<D>>, Option<TileFunction<D>>) {
256 let (fetch, handles): (Weak<CustomSourceCallbacks>, _) = (Arc::downgrade(callbacks), Arc::clone(handles));
257 let fetch: TileFunction<D> = Arc::new(move |tile: &CanonicalTileID, handle: &CustomSourceHandle<D>| {
258 if let Some(callbacks) = fetch.upgrade() {
259 handles.keep(handle);
260 (callbacks.fetch_tile)(*tile);
261 }
262 });
263 let cancel = callbacks.cancel_tile.as_ref().map(|_| {
264 let cancel = Arc::downgrade(callbacks);
265 let cancel: TileFunction<D> = Arc::new(move |tile: &CanonicalTileID, _: &CustomSourceHandle<D>| {
266 if let Some(callback) = cancel.upgrade().as_ref().and_then(|callbacks| callbacks.cancel_tile.as_ref()) {
267 callback(*tile);
268 }
269 });
270 cancel
271 });
272 (Some(fetch), cancel)
273}
274
275struct SourceHandles<D>(Mutex<Vec<CustomSourceHandle<D>>>);
280
281impl<D> Default for SourceHandles<D> {
282 fn default() -> Self {
283 SourceHandles(Mutex::new(Vec::new()))
284 }
285}
286
287impl<D: Clone> SourceHandles<D> {
288 fn keep(&self, handle: &CustomSourceHandle<D>) {
290 let mut handles = self.0.lock();
291 handles.retain(|kept| !kept.is_closed());
292 if !handles.iter().any(|kept| kept.ptr_eq(handle)) {
293 handles.push(handle.clone());
294 }
295 }
296
297 fn each<V: Clone>(&self, value: V, act: impl Fn(&CustomSourceHandle<D>, V)) {
299 let handles = self.0.lock();
300 if let Some((last, rest)) = handles.split_last() {
301 for handle in rest {
302 act(handle, value.clone());
303 }
304 act(last, value);
305 }
306 }
307}
308
309enum CustomHandles {
311 Geometry(Arc<SourceHandles<GeoJson>>),
312 Vector(Arc<SourceHandles<CustomVectorTileData>>),
313}
314
315struct CallbackSource {
318 id: String,
319 instance: SourceInstance,
320 _callbacks: Arc<CustomSourceCallbacks>,
323 handles: CustomHandles,
324}
325
326#[derive(Default)]
329pub(crate) struct CallbackSources(Vec<CallbackSource>);
330
331impl CallbackSources {
332 fn handles(&self, id: &str, source: &Source) -> Option<&CustomHandles> {
334 let instance = source.instance();
335 self.0.iter().find(|held| held.id == id && held.instance == instance).map(|held| &held.handles)
336 }
337}
338
339struct GeoJsonUpdate {
342 instance: SourceInstance,
345 building: Option<(u64, Resolver<Applied>)>,
349 waiting: Option<(GeoJson, Resolver<Applied>)>,
350}
351
352#[derive(Default)]
354pub(crate) struct GeoJsonUpdates(HashMap<String, GeoJsonUpdate>);
355
356pub(crate) fn reconcile(entry: &mut MapEntry, outbox: &mut Outbox) {
361 let map = &entry.core;
362 let present = |id: &str, instance: SourceInstance| map.source(id).is_some_and(|found| found.instance() == instance);
363 let (kept, gone): (Vec<_>, Vec<_>) =
364 std::mem::take(&mut entry.callback_sources.0).into_iter().partition(|held| present(&held.id, held.instance));
365 entry.callback_sources.0 = kept;
366 if !gone.is_empty() {
367 outbox.push(move || drop(gone));
368 }
369 entry.geojson_updates.0.retain(|id, update| {
370 if present(id, update.instance) {
371 return true;
372 }
373 let cancelled = || Err(Error::cancelled("the source left the style before its data was ready"));
374 if let Some((_, resolver)) = update.building.take() {
375 outbox.resolve(resolver, cancelled());
376 }
377 if let Some((_, resolver)) = update.waiting.take() {
378 outbox.resolve(resolver, cancelled());
379 }
380 false
381 });
382}
383
384pub(crate) fn release(entry: &mut MapEntry, outbox: &mut Outbox) {
387 let held = std::mem::take(&mut entry.callback_sources.0);
388 if !held.is_empty() {
389 outbox.push(move || drop(held));
390 }
391 for (_, mut update) in entry.geojson_updates.0.drain() {
392 let cancelled = || Err(Error::cancelled("the map was released before the data was ready"));
393 if let Some((_, resolver)) = update.building.take() {
394 outbox.resolve(resolver, cancelled());
395 }
396 if let Some((_, resolver)) = update.waiting.take() {
397 outbox.resolve(resolver, cancelled());
398 }
399 }
400}
401
402fn quote(id: &str) -> String {
403 format!("\"{id}\"")
404}
405
406fn require_loaded(map: &mln_map::Map) -> Result<(), Error> {
407 if map.style_document_loaded() { Ok(()) } else { Err(style_not_loaded()) }
408}
409
410fn source_not_found(id: &str) -> Error {
411 Error::not_found(format!("source {} does not exist", quote(id)))
412}
413
414fn find_source<'a>(map: &'a mln_map::Map, id: &str) -> Result<&'a Source, Error> {
415 map.source(id).ok_or_else(|| source_not_found(id))
416}
417
418fn not_a(id: &str, kind: &str) -> Error {
421 Error::invalid_argument(format!("source {} is not {kind}", quote(id)))
422}
423
424fn geojson_data<'a>(map: &'a mln_map::Map, id: &str) -> Result<&'a SourceData<GeoJsonSourceType>, Error> {
426 SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "a GeoJSON source"))
427}
428
429fn image_data<'a>(map: &'a mln_map::Map, id: &str) -> Result<&'a SourceData<ImageSourceType>, Error> {
431 SourceData::recover(find_source(map, id)?).ok_or_else(|| not_a(id, "an image source"))
432}
433
434fn require_new_source(map: &mln_map::Map, id: &str) -> Result<(), Error> {
435 require_loaded(map)?;
436 if map.source(id).is_some() {
437 return Err(Error::already_exists(format!("source {} already exists", quote(id))));
438 }
439 Ok(())
440}
441
442impl SourceKind {
443 fn of(source: &Source) -> Option<SourceKind> {
446 let name = source.info().name;
447 [
448 (VectorSourceType::INFO, SourceKind::Vector),
449 (RasterSourceType::INFO, SourceKind::Raster),
450 (RasterDemSourceType::INFO, SourceKind::RasterDem),
451 (GeoJsonSourceType::INFO, SourceKind::GeoJson),
452 (ImageSourceType::INFO, SourceKind::Image),
453 (CustomGeometrySourceType::INFO, SourceKind::CustomGeometry),
454 (CustomVectorSourceType::INFO, SourceKind::CustomVector),
455 ]
456 .into_iter()
457 .find_map(|(info, kind)| (info.name == name).then_some(kind))
458 }
459}
460
461fn cluster_properties_json(options: &GeoJSONOptions) -> Option<String> {
463 if options.cluster_properties.is_empty() {
464 return None;
465 }
466 let members = options
467 .cluster_properties
468 .iter()
469 .map(|(key, (map, reduce))| {
470 let pair = feature::Value::Array(vec![reduce.serialize(), map.serialize()]);
471 (key.clone(), mln_style::conversion::value_to_json(&pair))
472 })
473 .collect::<serde_json::Map<_, _>>();
474 Some(serde_json::Value::Object(members).to_string())
475}
476
477fn source_info(source: &Source) -> Option<SourceInfo> {
480 let kind = SourceKind::of(source)?;
481 let summary = source.data().summary();
482 Some(SourceInfo {
483 id: source.id().to_owned(),
484 kind,
485 is_volatile: source.common().volatile,
486 attribution: source.data().attribution().filter(|attribution| !attribution.is_empty()),
487 url: summary.url,
488 tiles: summary.inline_tileset.map(|tileset| SourceTiles {
489 urls: tileset.tiles,
490 zoom_range: tileset.zoom_range,
491 scheme: tileset.scheme,
492 bounds: tileset.bounds,
493 vector_encoding: tileset.vector_encoding,
494 raster_encoding: tileset.raster_encoding,
495 }),
496 tile_size: summary.tile_size,
497 vector_encoding: summary.vector_encoding,
498 geojson: summary.geojson.map(|options| GeoJsonSourceOptions::from_core(&options)),
499 })
500}
501
502fn layer_info(layer: &mln_style::Layer) -> LayerInfo {
503 LayerInfo {
504 id: layer.get_id().to_owned(),
505 layer_type: layer.info().name,
506 source_id: Some(layer.get_source_id()).filter(|id| !id.is_empty()).map(str::to_owned),
507 source_layer: Some(layer.get_source_layer()).filter(|id| !id.is_empty()).map(str::to_owned),
508 min_zoom: Some(f64::from(layer.get_min_zoom())).filter(|zoom| zoom.is_finite()),
509 max_zoom: Some(f64::from(layer.get_max_zoom())).filter(|zoom| zoom.is_finite()),
510 visible: layer.get_visibility() != mln_style::types::VisibilityType::None,
511 }
512}
513
514pub(crate) fn parse_geojson(json: &str) -> Result<GeoJson, Error> {
516 serde_json::from_str(json).map_err(|error| {
517 let what = if error.is_data() { "invalid" } else { "not valid JSON" };
518 Error::invalid_argument(format!("GeoJSON data is {what}: {error}"))
519 })
520}
521
522fn check_clusterable(geojson: &GeoJson) -> Result<(), Error> {
526 let features = match geojson {
527 GeoJson::FeatureCollection(collection) => &collection.features,
528 other => {
529 let found = if matches!(other, GeoJson::Feature(_)) { "a single feature" } else { "a bare geometry" };
530 return Err(Error::invalid_argument(format!(
531 "clustered GeoJSON data requires a feature collection; the data is {found}"
532 )));
533 }
534 };
535 let point = |feature: &geojson::Feature| matches!(&feature.geometry, Some(g) if matches!(g.value, GeometryValue::Point { .. }));
536 match features.iter().position(|feature| !point(feature)) {
537 None => Ok(()),
538 Some(index) => Err(Error::invalid_argument(format!(
539 "clustered GeoJSON data requires point geometry on every feature; feature {index} has {} geometry",
540 features[index].geometry.as_ref().map_or("no", |g| g.value.type_name())
541 ))),
542 }
543}
544
545fn feature_collection(geojson: GeoJson) -> GeoJson {
548 match geojson {
549 GeoJson::FeatureCollection(_) => geojson,
550 GeoJson::Feature(feature) => GeoJson::from(vec![feature]),
551 GeoJson::Geometry(geometry) => GeoJson::from(vec![geojson::Feature::from(geometry)]),
552 }
553}
554
555impl Map {
556 pub fn set_global_state_property(
561 &self,
562 name: impl Into<String>,
563 json: impl Into<String>,
564 ) -> Result<Completion<Applied>, Error> {
565 let (name, json) = (name.into(), json.into());
566 self.command(move |map| map.edit_loaded_style(|style| style.set_global_state_property_json(&name, &json)))
567 }
568
569 pub fn global_state(&self) -> Result<Completion<String>, Error> {
571 self.query(|map| Ok(map.style().global_state_json()))
572 }
573
574 pub fn style_source(&self, source_id: impl Into<String>) -> Result<Completion<Option<SourceInfo>>, Error> {
578 let source_id = source_id.into();
579 self.query(move |map| Ok(map.source(&source_id).and_then(source_info)))
580 }
581
582 pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
584 self.query(|map| Ok(map.sources().filter_map(source_info).collect()))
585 }
586
587 pub fn set_style_source_volatile(
589 &self,
590 source_id: impl Into<String>,
591 is_volatile: bool,
592 ) -> Result<Completion<Applied>, Error> {
593 let source_id = source_id.into();
594 self.command(move |map| {
595 require_loaded(map)?;
596 let mut common = *find_source(map, &source_id)?.common();
597 common.volatile = is_volatile;
598 map.edit_style(|style| style.apply(Edit::SetSourceCommon { id: source_id, common }))
599 })
600 }
601
602 pub fn add_geojson_source(
611 &self,
612 source_id: impl Into<String>,
613 options: GeoJsonSourceOptions,
614 ) -> Result<Completion<Applied>, Error> {
615 options.check()?;
616 let source_id = source_id.into();
617 self.command(move |map| {
618 let functions = Arc::clone(map.style().registry().functions());
619 let options = options.into_core(&functions)?;
620 require_new_source(map, &source_id)?;
621 map.add_source(geojson_source(&source_id, Arc::new(options)))
622 })
623 }
624
625 pub fn set_geojson_source_url(
629 &self,
630 source_id: impl Into<String>,
631 url: impl Into<String>,
632 ) -> Result<Completion<Applied>, Error> {
633 let (source_id, url) = (source_id.into(), url.into());
634 self.send(
635 move |entry, outbox| {
636 require_loaded(&entry.core)?;
637 let edit = GeoJsonSourceType::set_url(source_id.clone(), url);
638 entry.core.edit_style(|style| style.apply(edit))?;
639 if let Some((_, resolver)) =
640 entry.geojson_updates.0.get_mut(&source_id).and_then(|update| update.waiting.take())
641 {
642 outbox.resolve(resolver, Err(Error::cancelled("the source's URL replaced its data")));
643 }
644 Ok(())
645 },
646 |(), entry| entry.applied(),
647 )
648 }
649
650 pub fn set_geojson_source_data(
668 &self,
669 source_id: impl Into<String>,
670 json: impl Into<String>,
671 ) -> Result<Completion<Applied>, Error> {
672 let (source_id, json) = (source_id.into(), json.into());
673 self.post(move |core, outbox, id, sequence, resolver| {
674 if !core.maps.contains_key(&id) {
675 return outbox.resolve(resolver, Err(missing_map()));
676 }
677 let background = core.background();
678 apply_command(
679 core,
680 id,
681 sequence,
682 outbox,
683 move |entry, outbox| match queue_geojson(entry, id, &source_id, &json, resolver, background, outbox) {
684 Ok(installed) => installed,
685 Err((error, resolver)) => {
686 outbox.resolve(resolver, Err(error));
687 None
688 }
689 },
690 |_, installed, applied, outbox| {
691 if let Some(resolver) = installed {
692 outbox.resolve(resolver, Ok(applied));
693 }
694 },
695 );
696 })
697 }
698
699 pub fn set_geojson_source_synchronous_tiling(
702 &self,
703 source_id: impl Into<String>,
704 enabled: bool,
705 ) -> Result<Completion<Applied>, Error> {
706 let source_id = source_id.into();
707 self.command(move |map| {
708 require_loaded(map)?;
709 map.edit_style(|style| style.apply(GeoJsonSourceType::set_synchronous(source_id, enabled)))
710 })
711 }
712
713 fn custom_command(
719 &self,
720 apply: impl FnOnce(&MapEntry) -> Result<(), Error> + Send + 'static,
721 ) -> Result<Completion<Applied>, Error> {
722 self.send(move |entry, _| apply(entry), |(), entry| entry.applied())
723 }
724
725 pub fn add_custom_geometry_source(
731 &self,
732 source_id: impl Into<String>,
733 callbacks: CustomSourceCallbacks,
734 zoom_range: Range<u8>,
735 tile_options: TileOptions,
736 ) -> Result<Completion<Applied>, Error> {
737 let (source_id, callbacks) = (source_id.into(), Arc::new(callbacks));
738 self.send(
739 move |entry, outbox| {
740 add_callback_source(entry, outbox, source_id, callbacks, |id, callbacks| {
741 let handles = Arc::default();
742 let (fetch_tile_function, cancel_tile_function) = tile_functions(callbacks, &handles);
743 let options = custom_geometry_source::Options {
744 fetch_tile_function,
745 cancel_tile_function,
746 zoom_range,
747 tile_options,
748 };
749 let source = custom_geometry_source::create(&id, options)
750 .map_err(|error| Error::invalid_argument(error.to_string()))?;
751 Ok((source, CustomHandles::Geometry(handles)))
752 })
753 },
754 |(), entry| entry.applied(),
755 )
756 }
757
758 pub fn add_custom_vector_source(
762 &self,
763 source_id: impl Into<String>,
764 callbacks: CustomSourceCallbacks,
765 zoom_range: Range<u8>,
766 ) -> Result<Completion<Applied>, Error> {
767 let (source_id, callbacks) = (source_id.into(), Arc::new(callbacks));
768 self.send(
769 move |entry, outbox| {
770 add_callback_source(entry, outbox, source_id, callbacks, |id, callbacks| {
771 let handles = Arc::default();
772 let (fetch_tile_function, cancel_tile_function) = tile_functions(callbacks, &handles);
773 let options =
774 custom_vector_source::Options { fetch_tile_function, cancel_tile_function, zoom_range };
775 Ok((custom_vector_source::create(&id, options), CustomHandles::Vector(handles)))
776 })
777 },
778 |(), entry| entry.applied(),
779 )
780 }
781
782 pub fn set_custom_geometry_source_tile_data(
786 &self,
787 source_id: impl Into<String>,
788 tile_id: CanonicalTileID,
789 json: impl Into<String>,
790 ) -> Result<Completion<Applied>, Error> {
791 let (source_id, json) = (source_id.into(), json.into());
792 self.custom_command(move |entry| {
793 let geojson = feature_collection(parse_geojson(&json)?);
794 if let Some(handles) = geometry_handles(entry, &source_id)? {
795 handles.each(geojson, |handle, geojson| handle.set_tile_data(tile_id, geojson));
796 }
797 Ok(())
798 })
799 }
800
801 pub fn set_custom_geometry_source_tile_error(
803 &self,
804 source_id: impl Into<String>,
805 tile_id: CanonicalTileID,
806 message: impl Into<String>,
807 ) -> Result<Completion<Applied>, Error> {
808 let (source_id, message) = (source_id.into(), message.into());
809 self.custom_command(move |entry| {
810 if let Some(handles) = geometry_handles(entry, &source_id)? {
811 handles.each(Error::native(message), |handle, error| handle.set_tile_error(tile_id, error));
812 }
813 Ok(())
814 })
815 }
816
817 pub fn invalidate_custom_geometry_source_tile(
820 &self,
821 source_id: impl Into<String>,
822 tile_id: CanonicalTileID,
823 ) -> Result<Completion<Applied>, Error> {
824 let source_id = source_id.into();
825 self.custom_command(move |entry| {
826 if let Some(handles) = geometry_handles(entry, &source_id)? {
827 handles.each((), |handle, ()| handle.invalidate_tile(tile_id));
828 }
829 Ok(())
830 })
831 }
832
833 pub fn invalidate_custom_geometry_source_region(
836 &self,
837 source_id: impl Into<String>,
838 bounds: LatLngBounds,
839 ) -> Result<Completion<Applied>, Error> {
840 let source_id = source_id.into();
841 self.custom_command(move |entry| {
842 if let Some(handles) = geometry_handles(entry, &source_id)? {
843 handles.each(bounds, CustomSourceHandle::invalidate_region);
844 }
845 Ok(())
846 })
847 }
848
849 pub fn set_custom_vector_source_tile_data(
853 &self,
854 source_id: impl Into<String>,
855 tile_id: CanonicalTileID,
856 data: Option<Vec<u8>>,
857 format: TileDataFormat,
858 ) -> Result<Completion<Applied>, Error> {
859 let source_id = source_id.into();
860 self.custom_command(move |entry| {
861 if let Some(handles) = vector_handles(entry, &source_id)? {
862 handles.each((data.map(Arc::new), format), |handle, data| handle.set_tile_data(tile_id, data));
863 }
864 Ok(())
865 })
866 }
867
868 pub fn set_custom_vector_source_tile_error(
870 &self,
871 source_id: impl Into<String>,
872 tile_id: CanonicalTileID,
873 message: impl Into<String>,
874 ) -> Result<Completion<Applied>, Error> {
875 let (source_id, message) = (source_id.into(), message.into());
876 self.custom_command(move |entry| {
877 if let Some(handles) = vector_handles(entry, &source_id)? {
878 handles.each(Error::native(message), |handle, error| handle.set_tile_error(tile_id, error));
879 }
880 Ok(())
881 })
882 }
883
884 pub fn invalidate_custom_vector_source_tile(
887 &self,
888 source_id: impl Into<String>,
889 tile_id: CanonicalTileID,
890 ) -> Result<Completion<Applied>, Error> {
891 let source_id = source_id.into();
892 self.custom_command(move |entry| {
893 if let Some(handles) = vector_handles(entry, &source_id)? {
894 handles.each((), |handle, ()| handle.invalidate_tile(tile_id));
895 }
896 Ok(())
897 })
898 }
899
900 pub fn invalidate_custom_vector_source_region(
903 &self,
904 source_id: impl Into<String>,
905 bounds: LatLngBounds,
906 ) -> Result<Completion<Applied>, Error> {
907 let source_id = source_id.into();
908 self.custom_command(move |entry| {
909 if let Some(handles) = vector_handles(entry, &source_id)? {
910 handles.each(bounds, CustomSourceHandle::invalidate_region);
911 }
912 Ok(())
913 })
914 }
915
916 pub fn set_style_image(&self, image: StyleImage) -> Result<Completion<Applied>, Error> {
920 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::AddImage(Arc::new(image)))))
921 }
922
923 pub fn remove_style_image(&self, image_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
927 let image_id = image_id.into();
928 self.command(move |map| {
929 map.edit_loaded_style(|style| {
930 if style.get_image(&image_id).is_none() {
931 return Err(Error::not_found(format!("style image {} does not exist", quote(&image_id))));
932 }
933 style.apply(Edit::RemoveImage(image_id))
934 })
935 })
936 }
937
938 pub fn style_image(&self, image_id: impl Into<String>) -> Result<Completion<Option<Arc<StyleImage>>>, Error> {
940 let image_id = image_id.into();
941 self.query(move |map| Ok(map.style().get_image(&image_id).cloned()))
942 }
943
944 pub fn add_image_source(
949 &self,
950 source_id: impl Into<String>,
951 coordinates: [LatLng; 4],
952 image: PremultipliedImage,
953 ) -> Result<Completion<Applied>, Error> {
954 let source_id = source_id.into();
955 self.command(move |map| {
956 require_new_source(map, &source_id)?;
957 let options = ImageSourceOptions { url: None, coordinates };
958 let data = SourceData::<ImageSourceType>::with_description(options, Arc::new(image));
959 map.add_source(Source::new(&source_id, data))
960 })
961 }
962
963 pub fn set_image_source_url(
965 &self,
966 source_id: impl Into<String>,
967 url: impl Into<String>,
968 ) -> Result<Completion<Applied>, Error> {
969 let (source_id, url) = (source_id.into(), url.into());
970 self.command(move |map| {
971 require_loaded(map)?;
972 map.edit_style(|style| style.apply(ImageSourceType::set_url(source_id, url)))
973 })
974 }
975
976 pub fn set_image_source_image(
978 &self,
979 source_id: impl Into<String>,
980 image: PremultipliedImage,
981 ) -> Result<Completion<Applied>, Error> {
982 let source_id = source_id.into();
983 self.command(move |map| {
984 require_loaded(map)?;
985 map.edit_style(|style| style.apply(ImageSourceType::set_image(source_id, image)))
986 })
987 }
988
989 pub fn set_image_source_coordinates(
992 &self,
993 source_id: impl Into<String>,
994 coordinates: [LatLng; 4],
995 ) -> Result<Completion<Applied>, Error> {
996 let source_id = source_id.into();
997 self.command(move |map| {
998 require_loaded(map)?;
999 map.edit_style(|style| style.apply(ImageSourceType::set_coordinates(source_id, coordinates)))
1000 })
1001 }
1002
1003 pub fn image_source_coordinates(&self, source_id: impl Into<String>) -> Result<Completion<[LatLng; 4]>, Error> {
1005 let source_id = source_id.into();
1006 self.query(move |map| Ok(image_data(map, &source_id)?.options.coordinates))
1007 }
1008
1009 pub fn style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Option<LayerInfo>>, Error> {
1013 let layer_id = layer_id.into();
1014 self.query(move |map| Ok(map.style().get_layer(&layer_id).map(layer_info)))
1015 }
1016
1017 pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
1019 self.query(|map| Ok(map.style().get_layers().map(layer_info).collect()))
1020 }
1021
1022 pub fn move_style_layer(
1025 &self,
1026 layer_id: impl Into<String>,
1027 before_layer_id: Option<String>,
1028 ) -> Result<Completion<Applied>, Error> {
1029 let layer_id = layer_id.into();
1030 self.command(move |map| map.edit_loaded_style(|style| style.move_layer(&layer_id, before_layer_id.as_deref())))
1031 }
1032
1033 pub fn set_style_transition_options(&self, options: TransitionOptions) -> Result<Completion<Applied>, Error> {
1037 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::SetTransition(options))))
1038 }
1039
1040 pub fn style_transition_options(&self) -> Result<Completion<TransitionOptions>, Error> {
1042 self.query(|map| Ok(map.style().get_transition_options()))
1043 }
1044}
1045
1046fn add_callback_source(
1050 entry: &mut MapEntry,
1051 outbox: &mut Outbox,
1052 id: String,
1053 callbacks: Arc<CustomSourceCallbacks>,
1054 make: impl FnOnce(String, &Arc<CustomSourceCallbacks>) -> Result<(Source, CustomHandles), Error>,
1055) -> Result<(), Error> {
1056 let map = &mut entry.core;
1057 let added = require_new_source(map, &id).and_then(|()| {
1058 let (source, handles) = make(id.clone(), &callbacks)?;
1059 let instance = source.instance();
1060 map.add_source(source)?;
1061 Ok((instance, handles))
1062 });
1063 match added {
1064 Ok((instance, handles)) => {
1065 entry.callback_sources.0.push(CallbackSource { id, instance, _callbacks: callbacks, handles });
1066 Ok(())
1067 }
1068 Err(error) => {
1069 outbox.push(move || drop(callbacks));
1070 Err(error)
1071 }
1072 }
1073}
1074
1075fn geometry_handles(entry: &MapEntry, id: &str) -> Result<Option<Arc<SourceHandles<GeoJson>>>, Error> {
1078 let source = find_source(&entry.core, id)?;
1079 SourceData::<CustomGeometrySourceType>::recover(source).ok_or_else(|| not_a(id, "a custom geometry source"))?;
1080 Ok(match entry.callback_sources.handles(id, source) {
1081 Some(CustomHandles::Geometry(handles)) => Some(Arc::clone(handles)),
1082 Some(CustomHandles::Vector(_)) | None => None,
1083 })
1084}
1085
1086fn vector_handles(entry: &MapEntry, id: &str) -> Result<Option<Arc<SourceHandles<CustomVectorTileData>>>, Error> {
1089 let source = find_source(&entry.core, id)?;
1090 SourceData::<CustomVectorSourceType>::recover(source).ok_or_else(|| not_a(id, "a custom vector source"))?;
1091 Ok(match entry.callback_sources.handles(id, source) {
1092 Some(CustomHandles::Vector(handles)) => Some(Arc::clone(handles)),
1093 Some(CustomHandles::Geometry(_)) | None => None,
1094 })
1095}
1096
1097fn queue_geojson(
1102 entry: &mut MapEntry,
1103 map_id: MapId,
1104 source_id: &str,
1105 json: &str,
1106 resolver: Resolver<Applied>,
1107 background: Background,
1108 outbox: &mut Outbox,
1109) -> Result<Option<Resolver<Applied>>, (Error, Resolver<Applied>)> {
1110 let found = (|| {
1111 require_loaded(&entry.core)?;
1112 let data = geojson_data(&entry.core, source_id)?;
1113 let geojson = parse_geojson(json)?;
1114 if data.options.options.cluster {
1115 check_clusterable(&geojson)?;
1116 }
1117 let instance = find_source(&entry.core, source_id)?.instance();
1118 Ok((instance, data.load, data.options.data_builder(), data.options.synchronous_update, geojson))
1119 })();
1120 let (instance, load, builder, synchronous, geojson) = match found {
1121 Ok(found) => found,
1122 Err(error) => return Err((error, resolver)),
1123 };
1124 if synchronous {
1125 return match builder.build(geojson) {
1126 Ok(data) => {
1127 let edit = GeoJsonSourceType::set_data(source_id, Some(data));
1128 match entry.core.edit_style(|style| style.apply(edit)) {
1129 Ok(()) => Ok(Some(resolver)),
1130 Err(error) => Err((error, resolver)),
1131 }
1132 }
1133 Err(error) => Err((error, resolver)),
1134 };
1135 }
1136 let update = entry.geojson_updates.0.entry(source_id.to_owned()).or_insert_with(|| GeoJsonUpdate {
1137 instance,
1138 building: None,
1139 waiting: None,
1140 });
1141 if update.building.is_none() {
1142 update.instance = instance;
1143 start_geojson(update, map_id, source_id.to_owned(), (builder, load), geojson, resolver, background);
1144 } else if let Some((_, replaced)) = update.waiting.replace((geojson, resolver)) {
1145 outbox.resolve(replaced, Err(Error::cancelled("newer data for the source replaced it")));
1146 }
1147 Ok(None)
1148}
1149
1150fn start_geojson(
1154 update: &mut GeoJsonUpdate,
1155 map_id: MapId,
1156 source_id: String,
1157 (builder, load): (GeoJSONDataBuilder, u64),
1158 geojson: GeoJson,
1159 resolver: Resolver<Applied>,
1160 background: Background,
1161) {
1162 static BUILDS: AtomicU64 = AtomicU64::new(0);
1165 let build = BUILDS.fetch_add(1, Ordering::Relaxed);
1166 update.building = Some((build, resolver));
1167 let next = background.clone();
1168 background.pool.spawn(move || {
1169 let data = builder.build(geojson);
1170 post(&background.queue, move |core, outbox| {
1171 install_geojson(core, map_id, &source_id, (build, load), data, next, outbox);
1172 });
1173 });
1174}
1175
1176fn current_geojson(map: &mln_map::Map, id: &str, instance: SourceInstance) -> Option<(GeoJSONDataBuilder, u64)> {
1179 let source = map.source(id).filter(|source| source.instance() == instance)?;
1180 let data = SourceData::<GeoJsonSourceType>::recover(source)?;
1181 Some((data.options.data_builder(), data.load))
1182}
1183
1184fn install_geojson(
1187 core: &mut RuntimeCore,
1188 map_id: MapId,
1189 source_id: &str,
1190 (build, load): (u64, u64),
1191 data: Result<Arc<dyn GeoJSONData>, Error>,
1192 background: Background,
1193 outbox: &mut Outbox,
1194) {
1195 flush(core, map_id, outbox);
1196 let Some(entry) = core.maps.get_mut(&map_id) else { return };
1197 let Some(update) = entry.geojson_updates.0.get_mut(source_id) else { return };
1198 let Some((_, resolver)) = update.building.take_if(|(building, _)| *building == build) else { return };
1199 let current = current_geojson(&entry.core, source_id, update.instance);
1200 let installed = match data {
1201 Err(error) => Err(error),
1202 Ok(_) if current.as_ref().is_none_or(|(_, current_load)| *current_load != load) => {
1203 Err(Error::cancelled("the source's data was replaced before this data was ready"))
1204 }
1205 Ok(data) => {
1206 let edit = GeoJsonSourceType::set_data(source_id, Some(data));
1207 entry.core.edit_style(|style| style.apply(edit))
1208 }
1209 };
1210 match (update.waiting.take(), current_geojson(&entry.core, source_id, update.instance)) {
1211 (Some((geojson, next)), Some(current)) => {
1212 start_geojson(update, map_id, source_id.to_owned(), current, geojson, next, background);
1213 }
1214 (Some((_, next)), None) => outbox.resolve(next, Err(Error::cancelled("the source left the style"))),
1215 (None, _) => {
1216 entry.geojson_updates.0.remove(source_id);
1217 }
1218 }
1219 flush(core, map_id, outbox);
1220 let Some(entry) = core.maps.get(&map_id) else { return };
1221 outbox.resolve(resolver, installed.map(|()| entry.applied()));
1222}