1use std::cell::RefCell;
4use std::rc::Rc;
5use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
6use std::sync::{Arc, Mutex, Weak};
7
8use mln_actor::RunLoopHandle;
9use mln_map::{
10 AnimationOptions, BoundOptions, Camera, CameraDelta, CameraOptions, CameraUpdate, FreeCameraOptions, LogicalExtent,
11 MapDebugOptions, MapEvent, MapMode, MapSnapshot, ProjectionMode, StyleLoadError, TransitionEnd, TransitionOutcome,
12};
13use mln_text::GlyphCache;
14use mln_util::error::{Error, ErrorKind};
15use mln_util::geo::LatLngBounds;
16use mln_util::size::Size;
17use mln_util::sync::MutexExt;
18
19use crate::camera::{self, CameraFitArea, CameraFitOptions, CameraFitUpdate, TileOptions, ViewportOptions};
20use crate::completion::{Completion, Resolver};
21use crate::event::{EventMask, EventSource, RuntimeEvent, RuntimeEventKind};
22use crate::feature_state::{FeatureState, FeatureStateSelector, FeatureStateStore};
23use crate::render::{
24 Abandoner, AttachOptions, RenderSession, RenderTarget, SessionId, SessionShared, Worker, worker_post,
25};
26use crate::runtime::{Outbox, Runtime, RuntimeCore, RuntimeShared, post};
27use crate::style::{CallbackSources, GeoJsonUpdates};
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct MapId(pub u64);
32
33#[derive(Clone, Debug)]
35pub struct MapOptions {
36 pub map: mln_map::MapOptions,
37 pub event_mask: EventMask,
39 pub fallback_font_faces: Option<String>,
43 pub tile_cache_enabled: bool,
46}
47
48impl Default for MapOptions {
49 fn default() -> Self {
50 MapOptions {
51 map: mln_map::MapOptions::default(),
52 event_mask: EventMask::default(),
53 fallback_font_faces: None,
54 tile_cache_enabled: true,
55 }
56 }
57}
58
59impl MapOptions {
60 #[must_use]
61 pub fn new(map: mln_map::MapOptions) -> Self {
62 MapOptions { map, ..Self::default() }
63 }
64
65 #[must_use]
66 pub fn with_event_mask(mut self, event_mask: EventMask) -> Self {
67 self.event_mask = event_mask;
68 self
69 }
70
71 #[must_use]
72 pub fn with_fallback_font_faces(mut self, json: impl Into<String>) -> Self {
73 self.fallback_font_faces = Some(json.into());
74 self
75 }
76
77 #[must_use]
78 pub fn with_tile_cache_enabled(mut self, enabled: bool) -> Self {
79 self.tile_cache_enabled = enabled;
80 self
81 }
82}
83
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub struct Applied {
87 pub sequence: u64,
90 pub generation: u64,
93 pub render_update_generation: u64,
96}
97
98#[derive(Clone, Copy, Debug, PartialEq)]
100pub struct CameraQuery {
101 pub generation: u64,
102 pub camera: Camera,
103}
104
105pub(crate) struct Published {
107 snapshot: Mutex<Option<MapSnapshot>>,
108 applied: AtomicU64,
110 event_mask: AtomicU64,
111}
112
113impl Published {
114 pub(crate) fn new(event_mask: EventMask) -> Self {
115 Published {
116 snapshot: Mutex::new(None),
117 applied: AtomicU64::new(0),
118 event_mask: AtomicU64::new(event_mask.bits()),
119 }
120 }
121}
122
123pub(crate) struct MapShared {
124 id: MapId,
125 runtime: Arc<RuntimeShared>,
126 mode: MapMode,
127 scale_factor: AtomicU64,
130 tile_cache_enabled: bool,
131 session: Mutex<Option<SessionClaim>>,
134 sent: Mutex<u64>,
138 released: AtomicBool,
140 removed: AtomicBool,
142 published: Arc<Published>,
143}
144
145impl MapShared {
146 pub(crate) fn new(id: MapId, runtime: Arc<RuntimeShared>, options: &MapOptions, published: Arc<Published>) -> Self {
147 MapShared {
148 id,
149 runtime,
150 mode: options.map.map_mode(),
151 scale_factor: AtomicU64::new(f64::from(options.map.pixel_ratio()).to_bits()),
152 tile_cache_enabled: options.tile_cache_enabled,
153 session: Mutex::new(None),
154 sent: Mutex::new(1),
155 released: AtomicBool::new(false),
156 removed: AtomicBool::new(false),
157 published,
158 }
159 }
160
161 pub(crate) fn send<R: Send + 'static>(
163 &self,
164 command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
165 ) -> Result<Completion<R>, Error> {
166 let mut sent = self.sent.lock_unpoisoned();
167 if self.released.load(Ordering::SeqCst) {
168 return Err(released());
169 }
170 let (completion, resolver) = self.runtime.completion();
171 let id = self.id;
172 *sent += 1;
173 let sequence = *sent;
174 self.runtime.post(move |core, outbox| command(core, outbox, id, sequence, resolver));
175 Ok(completion)
176 }
177
178 fn release(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
181 self.close()?;
182 self.remove(done);
183 Ok(())
184 }
185
186 fn close(&self) -> Result<(), Error> {
189 let _sent = self.sent.lock_unpoisoned();
190 if self.released.swap(true, Ordering::SeqCst) {
191 return Err(released());
192 }
193 Ok(())
194 }
195
196 fn remove(&self, done: Option<Resolver<()>>) {
199 if self.removed.swap(true, Ordering::SeqCst) {
200 return;
201 }
202 let id = self.id;
203 self.runtime.post(move |core, outbox| remove(core, id, done, outbox));
204 self.runtime.map_released();
205 }
206}
207
208impl Drop for MapShared {
209 fn drop(&mut self) {
210 let _ = self.close();
211 let deferred = self.session.get_mut_unpoisoned().take().and_then(|claim| claim.removal);
212 self.remove(deferred);
213 }
214}
215
216#[derive(Clone)]
229pub struct Map {
230 pub(crate) shared: Arc<MapShared>,
231}
232
233impl std::fmt::Debug for Map {
234 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235 f.debug_struct("Map").field("id", &self.shared.id).finish()
236 }
237}
238
239impl PartialEq for Map {
240 fn eq(&self, other: &Map) -> bool {
241 Arc::ptr_eq(&self.shared, &other.shared)
242 }
243}
244
245impl Eq for Map {}
246
247fn released() -> Error {
248 Error::invalid_state("the map was released")
249}
250
251pub(crate) fn style_not_loaded() -> Error {
252 Error::invalid_state("style is not loaded")
253}
254
255pub(crate) fn missing_map() -> Error {
258 Error::invalid_state("the map failed to be built or was released")
259}
260
261impl Map {
262 pub(crate) fn new(shared: MapShared) -> Self {
263 Map { shared: Arc::new(shared) }
264 }
265
266 #[must_use]
267 pub fn id(&self) -> MapId {
268 self.shared.id
269 }
270
271 #[must_use]
273 pub fn mode(&self) -> MapMode {
274 self.shared.mode
275 }
276
277 #[must_use]
279 pub fn runtime(&self) -> Runtime {
280 Runtime { shared: self.shared.runtime.clone() }
281 }
282
283 #[must_use]
285 pub fn sent_sequence(&self) -> u64 {
286 *self.shared.sent.lock_unpoisoned()
287 }
288
289 #[must_use]
291 pub fn applied_sequence(&self) -> u64 {
292 self.shared.published.applied.load(Ordering::SeqCst)
293 }
294
295 pub fn snapshot(&self) -> Result<MapSnapshot, Error> {
303 if self.shared.released.load(Ordering::SeqCst) {
304 return Err(released());
305 }
306 self.shared.published.snapshot.lock_unpoisoned().ok_or_else(|| Error::invalid_state("the map isn't built"))
307 }
308
309 #[must_use]
311 pub fn event_mask(&self) -> EventMask {
312 EventMask::from_bits(self.shared.published.event_mask.load(Ordering::SeqCst)).unwrap_or_default()
313 }
314
315 pub(crate) fn send<T: 'static, R: Send + 'static>(
318 &self,
319 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error> + Send + 'static,
320 finish: impl FnOnce(T, &MapEntry) -> R + Send + 'static,
321 ) -> Result<Completion<R>, Error> {
322 self.shared.send(move |core, outbox, id, sequence, resolver| {
323 run_command(core, id, sequence, apply, finish, resolver, outbox);
324 })
325 }
326
327 pub(crate) fn command(
329 &self,
330 apply: impl FnOnce(&mut mln_map::Map) -> Result<(), Error> + Send + 'static,
331 ) -> Result<Completion<Applied>, Error> {
332 self.send(move |entry, _| apply(&mut entry.core), |(), entry| entry.applied())
333 }
334
335 pub(crate) fn query<T: Send + 'static>(
337 &self,
338 read: impl FnOnce(&mut mln_map::Map) -> Result<T, Error> + Send + 'static,
339 ) -> Result<Completion<T>, Error> {
340 self.send(move |entry, _| read(&mut entry.core), |value, _| value)
341 }
342
343 pub fn with_core<R: Send + 'static>(
348 &self,
349 f: impl FnOnce(&mut mln_map::Map) -> R + Send + 'static,
350 ) -> Result<Completion<R>, Error> {
351 self.query(move |map| Ok(f(map)))
352 }
353
354 pub fn release(&self) -> Result<Completion<()>, Error> {
365 self.release_with(false)
366 }
367
368 pub fn dispose(&self) -> Result<Completion<()>, Error> {
380 self.release_with(true)
381 }
382
383 fn release_with(&self, in_any_state: bool) -> Result<Completion<()>, Error> {
384 let (completion, resolver) = self.shared.runtime.completion();
385 let claimed = {
386 let mut claim = self.shared.session.lock_unpoisoned();
387 match claim.as_mut() {
388 None => None,
389 Some(held) => match held.session.upgrade() {
390 Some(session) if session.is_released() => Some((held.id, Some(session))),
392 Some(_) if in_any_state => {
395 self.shared.close()?;
396 held.removal = Some(resolver);
397 return Ok(completion);
398 }
399 Some(_) => return Err(Error::invalid_state("the map still has an attached render session")),
400 None => Some((held.id, None)),
402 },
403 }
404 };
405 if let Some((id, session)) = claimed {
406 if let Some(session) = session {
407 let _ = session.abandon(Abandoner::Library);
408 }
409 self.release_session_claim(id);
410 }
411 self.shared.release(Some(resolver))?;
412 Ok(completion)
413 }
414
415 pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
425 let LogicalExtent { size, scale_factor } = extent;
426 if self.shared.session.lock_unpoisoned().is_some() {
427 return Err(Error::invalid_state("the map has a render session: resize the session instead"));
428 }
429 if size.is_empty() {
430 return Err(Error::invalid_argument("logical size dimensions must be positive"));
431 }
432 if !scale_factor.is_finite() || scale_factor <= 0.0 {
433 return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
434 }
435 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
437 self.command(move |map| {
438 if map.get_map_options().size() != size {
439 map.set_size(size)?;
440 }
441 map.set_pixel_ratio(scale_factor as f32)
442 })
443 }
444
445 pub fn request_repaint(&self) -> Result<Completion<Applied>, Error> {
449 if self.shared.mode != MapMode::Continuous {
450 return Err(Error::invalid_state("map is not in continuous mode"));
451 }
452 self.command(|map| {
453 map.trigger_repaint();
454 Ok(())
455 })
456 }
457
458 pub fn begin_command_group(&self) -> Result<Completion<Applied>, Error> {
463 self.command(|map| {
464 map.begin_command_group();
465 Ok(())
466 })
467 }
468
469 pub fn end_command_group(&self) -> Result<Completion<Applied>, Error> {
473 self.command(mln_map::Map::end_command_group)
474 }
475
476 pub fn command_group(&self) -> Result<CommandGroup, Error> {
479 drop(self.begin_command_group()?);
480 Ok(CommandGroup { map: Some(self.clone()) })
481 }
482
483 pub fn set_event_mask(&self, mask: EventMask) -> Result<Completion<Applied>, Error> {
485 self.send(
486 move |entry, _| {
487 if entry.mask != mask {
488 entry.mask = mask;
489 entry.published.event_mask.store(mask.bits(), Ordering::SeqCst);
490 entry.core.record_change();
491 }
492 Ok(())
493 },
494 |(), entry| entry.applied(),
495 )
496 }
497
498 pub fn attach(
524 &self,
525 target: RenderTarget,
526 options: AttachOptions,
527 ) -> Result<(RenderSession, Completion<()>), Error> {
528 crate::render::attach(self, target, options)
529 }
530
531 pub fn request_still_image(&self) -> Result<Completion<()>, Error> {
545 if self.shared.mode == MapMode::Continuous {
546 return Err(Error::invalid_state("the map is not in static or tile mode"));
547 }
548 self.shared.send(move |core, outbox, id, sequence, resolver| {
549 if !core.maps.contains_key(&id) {
550 return outbox.resolve(resolver, Err(missing_map()));
551 }
552 apply_command(
553 core,
554 id,
555 sequence,
556 outbox,
557 move |entry, outbox| {
558 if entry.pending_still.is_some() {
559 let error = Error::invalid_state("the map is rendering a still image already");
560 return outbox.resolve(resolver, Err(error));
561 }
562 if entry.core.command_group_depth() > 0 {
564 let error = Error::invalid_state("a still image can't render while a command group is open");
565 return outbox.resolve(resolver, Err(error));
566 }
567 let outcome = Rc::new(RefCell::new(None));
568 let done = outcome.clone();
569 entry.core.render_still(Box::new(move |result| {
570 *done.borrow_mut() = Some(result.map_err(still_image_error));
571 }));
572 entry.pending_still = Some(PendingStill { resolver, outcome });
573 },
574 |_, (), _, _| {},
575 );
576 })
577 }
578
579 pub(crate) fn runtime_thread(&self) -> std::thread::ThreadId {
580 self.shared.runtime.thread()
581 }
582
583 #[must_use]
588 pub fn scale_factor(&self) -> f64 {
589 f64::from_bits(self.shared.scale_factor.load(Ordering::SeqCst))
590 }
591
592 pub(crate) fn tile_cache_enabled(&self) -> bool {
593 self.shared.tile_cache_enabled
594 }
595
596 pub(crate) fn glyph_cache(&self) -> Arc<GlyphCache> {
597 self.shared.runtime.glyph_cache.clone()
598 }
599
600 pub(crate) fn claim_session(&self, id: SessionId, session: Weak<SessionShared>) -> Result<(), Error> {
602 let mut claim = self.shared.session.lock_unpoisoned();
603 if self.shared.released.load(Ordering::SeqCst) {
604 return Err(released());
605 }
606 if claim.is_some() {
607 return Err(Error::invalid_state("the map already has an attached render session"));
608 }
609 *claim = Some(SessionClaim { id, session, removal: None });
610 Ok(())
611 }
612
613 pub(crate) fn release_session_claim(&self, id: SessionId) {
616 let claim = {
617 let mut session = self.shared.session.lock_unpoisoned();
618 if session.as_ref().is_some_and(|claim| claim.id == id) { session.take() } else { None }
619 };
620 if let Some(removal) = claim.and_then(|claim| claim.removal) {
621 self.shared.remove(Some(removal));
622 }
623 }
624
625 pub(crate) fn bind_session(&self, id: SessionId, run_loop: RunLoopHandle, size: Size) -> Result<(), Error> {
629 let sent = self.shared.send(move |core, outbox, map_id, sequence, resolver: Resolver<()>| {
630 drop(resolver);
631 if !core.maps.contains_key(&map_id) {
632 return worker_post(&run_loop, |worker, outbox| worker.bind_failed(missing_map(), outbox));
633 }
634 let link = SessionLink { id, run_loop: run_loop.clone() };
635 apply_command(
636 core,
637 map_id,
638 sequence,
639 outbox,
640 move |entry, _| {
641 entry.session = Some(link);
642 let resized = entry.core.set_size(size);
643 (resized, entry.core.update_reader(), entry.core.renderer_events())
644 },
645 move |_, (resized, reader, events), _, _| match resized {
646 Ok(()) => {
647 worker_post(&run_loop, move |worker, outbox| worker.bound(sequence, reader, events, outbox));
648 }
649 Err(error) => worker_post(&run_loop, move |worker, outbox| worker.bind_failed(error, outbox)),
650 },
651 );
652 });
653 sent.map(drop)
654 }
655
656 pub(crate) fn unbind_session(&self, id: SessionId) {
659 let map_id = self.shared.id;
660 self.shared.runtime.post_or((), move |core, _, ()| unbind(core, map_id, id), |()| {});
662 }
663
664 pub(crate) fn unbind_session_then(
667 &self,
668 id: SessionId,
669 run_loop: RunLoopHandle,
670 then: impl FnOnce(&mut Worker, &mut Outbox) + Send + 'static,
671 ) {
672 let map_id = self.shared.id;
673 let session_loop = run_loop.clone();
674 self.shared.runtime.post_or(
676 then,
677 move |core, _, then| {
678 unbind(core, map_id, id);
679 worker_post(&run_loop, then);
680 },
681 |then| worker_post(&session_loop, then),
682 );
683 }
684
685 pub(crate) fn resize_for_session(
689 &self,
690 size: Size,
691 scale_factor: f64,
692 run_loop: RunLoopHandle,
693 resize: impl FnOnce(&mut Worker, Result<Applied, Error>, &mut Outbox) + Send + 'static,
694 ) -> Result<(), Error> {
695 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
697 let sent = self.shared.send(move |core, outbox, id, sequence, resolver: Resolver<()>| {
698 drop(resolver);
699 if !core.maps.contains_key(&id) {
700 return worker_post(&run_loop, move |worker, outbox| resize(worker, Err(missing_map()), outbox));
701 }
702 apply_command(
703 core,
704 id,
705 sequence,
706 outbox,
707 move |entry, _| {
708 let pixel_ratio = scale_factor as f32;
712 if entry.core.get_map_options().size() == size && entry.core.get_pixel_ratio() == pixel_ratio {
713 return Ok(());
714 }
715 entry.core.set_size(size)?;
716 entry.core.set_pixel_ratio(pixel_ratio)
717 },
718 move |_, resized, applied, _| {
719 let result = resized.map(|()| applied);
720 worker_post(&run_loop, move |worker, outbox| resize(worker, result, outbox));
721 },
722 );
723 });
724 sent.map(drop)
725 }
726
727 pub fn set_feature_state(
743 &self,
744 selector: &FeatureStateSelector,
745 state: FeatureState,
746 ) -> Result<Completion<Applied>, Error> {
747 let key = selector.key(true)?;
748 if state.is_empty() {
749 return Err(Error::invalid_argument("feature state must not be empty"));
750 }
751 self.send(
752 move |entry, _| {
753 entry.feature_state.set(key, state);
754 Ok(())
755 },
756 |(), entry| entry.applied(),
757 )
758 }
759
760 pub fn feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<FeatureState>, Error> {
764 let key = selector.key(true)?;
765 self.send(move |entry, _| Ok(entry.feature_state.get(&key)), |state, _| state)
766 }
767
768 pub fn remove_feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<Applied>, Error> {
773 let key = selector.key(false)?;
774 self.send(
775 move |entry, _| {
776 entry.feature_state.remove(&key);
777 Ok(())
778 },
779 |(), entry| entry.applied(),
780 )
781 }
782
783 pub fn set_style_url(&self, url: impl Into<String>) -> Result<Completion<Applied>, Error> {
795 let url = url.into();
796 if url.is_empty() {
797 return Err(Error::invalid_argument("style URL must not be empty"));
798 }
799 self.load_style(StyleLoad::Url(url))
800 }
801
802 pub fn set_style_json(&self, json: impl Into<String>) -> Result<Completion<Applied>, Error> {
808 let json = json.into();
809 if json.is_empty() {
810 return Err(Error::invalid_argument("style JSON must not be empty"));
811 }
812 self.load_style(StyleLoad::Json(json))
813 }
814
815 fn load_style(&self, load: StyleLoad) -> Result<Completion<Applied>, Error> {
816 self.shared.send(move |core, outbox, id, sequence, resolver| {
817 load_style(core, id, sequence, load, resolver, outbox);
818 })
819 }
820
821 pub fn loaded_style_json(&self) -> Result<Completion<String>, Error> {
824 self.query(|map| Ok(map.style().get_json()))
825 }
826
827 pub fn style_url(&self) -> Result<Completion<Option<String>>, Error> {
829 self.query(|map| Ok(Some(map.style().get_url()).filter(|url| !url.is_empty())))
830 }
831
832 pub fn add_style_source_json(
835 &self,
836 source_id: impl Into<String>,
837 json: impl Into<String>,
838 ) -> Result<Completion<Applied>, Error> {
839 let (source_id, json) = (source_id.into(), json.into());
840 self.command(move |map| map.style_mut().add_source_json(&source_id, &json))
841 }
842
843 pub fn remove_style_source(&self, source_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
850 let source_id = source_id.into();
851 self.send(
852 move |entry, _| {
853 let style = entry.core.style_mut();
854 if !style.is_loaded() {
855 return Err(style_not_loaded());
856 }
857 if style.get_source(&source_id).is_none() {
858 return Err(Error::not_found(format!("source \"{source_id}\" does not exist")));
859 }
860 if let Some(layer) = style.get_layers().into_iter().find(|layer| layer.get_source_id() == source_id) {
861 let message = format!("source \"{source_id}\" is used by layer \"{}\"", layer.get_id());
862 return Err(Error::invalid_state(message));
863 }
864 style.remove_source(&source_id);
865 entry.feature_state.remove_source(&source_id);
866 Ok(())
867 },
868 |(), entry| entry.applied(),
869 )
870 }
871
872 pub fn add_style_layer_json(
875 &self,
876 json: impl Into<String>,
877 before_layer_id: Option<String>,
878 ) -> Result<Completion<Applied>, Error> {
879 let json = json.into();
880 self.command(move |map| map.style_mut().add_layer_json(&json, before_layer_id.as_deref()))
881 }
882
883 pub fn remove_style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
888 let layer_id = layer_id.into();
889 self.command(move |map| {
890 let style = map.style_mut();
891 if !style.is_loaded() {
892 return Err(style_not_loaded());
893 }
894 style
895 .remove_layer(&layer_id)
896 .map(drop)
897 .ok_or_else(|| Error::not_found(format!("layer \"{layer_id}\" does not exist")))
898 })
899 }
900
901 pub fn style_layer_json(&self, layer_id: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
904 let layer_id = layer_id.into();
905 self.query(move |map| Ok(map.style().layer_json(&layer_id)))
906 }
907
908 pub fn set_style_layer_property(
911 &self,
912 layer_id: impl Into<String>,
913 name: impl Into<String>,
914 json: impl Into<String>,
915 ) -> Result<Completion<Applied>, Error> {
916 let (layer_id, name, json) = (layer_id.into(), name.into(), json.into());
917 self.command(move |map| map.style_mut().set_layer_property_json(&layer_id, &name, &json))
918 }
919
920 pub fn style_layer_property(
923 &self,
924 layer_id: impl Into<String>,
925 name: impl Into<String>,
926 ) -> Result<Completion<Option<String>>, Error> {
927 let (layer_id, name) = (layer_id.into(), name.into());
928 self.query(move |map| map.style().layer_property_json(&layer_id, &name))
929 }
930
931 pub fn set_style_root_property(
935 &self,
936 name: impl Into<String>,
937 json: impl Into<String>,
938 ) -> Result<Completion<Applied>, Error> {
939 let (name, json) = (name.into(), json.into());
940 self.command(move |map| map.style_mut().set_root_property_json(&name, &json))
941 }
942
943 pub fn style_root_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
946 let name = name.into();
947 self.query(move |map| map.style().root_property_json(&name))
948 }
949
950 pub fn set_style_light_property(
952 &self,
953 name: impl Into<String>,
954 json: impl Into<String>,
955 ) -> Result<Completion<Applied>, Error> {
956 let (name, json) = (name.into(), json.into());
957 self.command(move |map| map.style_mut().set_light_property_json(&name, &json))
958 }
959
960 pub fn style_light_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
963 let name = name.into();
964 self.query(move |map| Ok(map.style().light_property_json(&name)))
965 }
966
967 fn camera_command(
974 &self,
975 apply: impl FnOnce(&mut mln_map::Map, &Ends) -> Result<(), Error> + Send + 'static,
976 ) -> Result<Completion<Applied>, Error> {
977 self.send(move |entry, _| apply(&mut entry.core, &entry.ends), |(), entry| entry.applied())
978 }
979
980 pub fn update_camera(&self, mut update: CameraUpdate) -> Result<Completion<Applied>, Error> {
982 self.camera_command(move |map, ends| {
983 ends.defer(&mut update.animation);
984 map.update_camera(&update);
985 Ok(())
986 })
987 }
988
989 pub fn apply_camera_delta(&self, mut delta: CameraDelta) -> Result<Completion<Applied>, Error> {
993 self.camera_command(move |map, ends| {
994 ends.defer(&mut delta.animation);
995 map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string()))
996 })
997 }
998
999 pub fn camera_for(
1006 &self,
1007 area: CameraFitArea,
1008 options: CameraFitOptions,
1009 ) -> Result<Completion<CameraOptions>, Error> {
1010 self.query(move |map| camera::camera_for(map, &area, &options))
1011 }
1012
1013 pub fn fit_camera(&self, area: CameraFitArea, update: CameraFitUpdate) -> Result<Completion<Applied>, Error> {
1020 self.camera_command(move |map, ends| {
1021 let CameraFitUpdate { mode, fit, mut animation } = update;
1022 ends.defer(&mut animation);
1023 match camera::camera_for(map, &area, &fit) {
1024 Ok(camera) => {
1025 map.update_camera(&CameraUpdate { mode, camera, animation, ..CameraUpdate::default() });
1026 Ok(())
1027 }
1028 Err(error) => {
1029 if let Some(end_fn) = &animation.transition_end_fn {
1030 end_fn(&TransitionEnd { outcome: TransitionOutcome::Cancelled, ..TransitionEnd::default() });
1031 }
1032 Err(error)
1033 }
1034 }
1035 })
1036 }
1037
1038 pub fn cancel_camera_transitions(&self) -> Result<Completion<Applied>, Error> {
1040 self.command(|map| {
1041 map.cancel_transitions();
1042 Ok(())
1043 })
1044 }
1045
1046 pub fn cancel_camera_transitions_with_id(&self, transition_id: u64) -> Result<Completion<Applied>, Error> {
1048 self.command(move |map| {
1049 map.cancel_transitions_with_id(transition_id);
1050 Ok(())
1051 })
1052 }
1053
1054 pub fn camera(&self) -> Result<Completion<CameraQuery>, Error> {
1056 self.send(
1057 |_, _| Ok(()),
1058 |(), entry| CameraQuery { generation: entry.core.generation(), camera: entry.core.snapshot().view.camera },
1059 )
1060 }
1061
1062 pub fn lat_lng_bounds_for_camera(&self, camera: CameraOptions) -> Result<Completion<LatLngBounds>, Error> {
1067 self.query(move |map| map.lat_lng_bounds_for_camera_unwrapped(&camera))
1068 }
1069
1070 pub fn set_bounds(&self, bounds: BoundOptions) -> Result<Completion<Applied>, Error> {
1072 self.command(move |map| map.set_bounds(&bounds))
1073 }
1074
1075 pub fn set_free_camera_options(&self, camera: FreeCameraOptions) -> Result<Completion<Applied>, Error> {
1077 self.command(move |map| {
1078 map.set_free_camera_options(&camera);
1079 Ok(())
1080 })
1081 }
1082
1083 pub fn set_viewport_options(&self, options: ViewportOptions) -> Result<Completion<Applied>, Error> {
1085 self.command(move |map| {
1086 camera::set_viewport(map, &options);
1087 Ok(())
1088 })
1089 }
1090
1091 pub fn set_tile_options(&self, options: TileOptions) -> Result<Completion<Applied>, Error> {
1093 self.command(move |map| {
1094 camera::set_tile_options(map, &options);
1095 Ok(())
1096 })
1097 }
1098
1099 pub fn set_projection_mode(&self, mode: ProjectionMode) -> Result<Completion<Applied>, Error> {
1100 self.command(move |map| {
1101 map.set_projection_mode(&mode);
1102 Ok(())
1103 })
1104 }
1105
1106 pub fn set_debug_flags(&self, flags: MapDebugOptions) -> Result<Completion<Applied>, Error> {
1108 self.command(move |map| {
1109 map.set_debug(flags);
1110 Ok(())
1111 })
1112 }
1113
1114 pub fn set_rendering_stats_view_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1116 self.command(move |map| {
1117 map.enable_rendering_stats_view(enabled);
1118 Ok(())
1119 })
1120 }
1121
1122 pub fn set_globe_free_bearing_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1125 self.command(move |map| {
1126 map.set_globe_free_bearing(enabled);
1127 Ok(())
1128 })
1129 }
1130
1131 pub fn dump_debug_logs(&self) -> Result<Completion<Applied>, Error> {
1133 self.command(|map| {
1134 map.dump_debug_logs();
1135 Ok(())
1136 })
1137 }
1138}
1139
1140#[must_use = "the group ends when it drops"]
1142pub struct CommandGroup {
1143 map: Option<Map>,
1144}
1145
1146impl CommandGroup {
1147 pub fn end(mut self) -> Result<Completion<Applied>, Error> {
1149 match self.map.take() {
1150 Some(map) => map.end_command_group(),
1151 None => Err(Error::invalid_state("the group ended already")),
1152 }
1153 }
1154}
1155
1156impl Drop for CommandGroup {
1157 fn drop(&mut self) {
1158 if let Some(map) = self.map.take() {
1159 let _ = map.end_command_group();
1160 }
1161 }
1162}
1163
1164enum StyleLoad {
1165 Url(String),
1166 Json(String),
1167}
1168
1169struct PendingStyle {
1171 resolver: Resolver<Applied>,
1172 from_json: bool,
1175}
1176
1177struct SessionClaim {
1179 id: SessionId,
1180 session: Weak<SessionShared>,
1181 removal: Option<Resolver<()>>,
1183}
1184
1185fn unbind(core: &mut RuntimeCore, map_id: MapId, id: SessionId) {
1188 if let Some(entry) = core.maps.get_mut(&map_id)
1189 && entry.session.as_ref().is_some_and(|link| link.id == id)
1190 {
1191 entry.session = None;
1192 }
1193}
1194
1195pub(crate) struct SessionLink {
1197 id: SessionId,
1198 run_loop: RunLoopHandle,
1199}
1200
1201struct PendingStill {
1204 resolver: Resolver<()>,
1205 outcome: Rc<RefCell<Option<Result<(), Error>>>>,
1206}
1207
1208fn still_image_error(error: Error) -> Error {
1211 match error.kind {
1212 ErrorKind::InvalidState => error,
1213 _ => Error::native(error.message),
1214 }
1215}
1216
1217pub(crate) struct MapEntry {
1219 pub(crate) core: mln_map::Map,
1220 published: Arc<Published>,
1221 mask: EventMask,
1222 applied: u64,
1224 pending_style: Option<PendingStyle>,
1226 pending_still: Option<PendingStill>,
1227 session: Option<SessionLink>,
1229 flush_scheduled: Arc<AtomicBool>,
1231 ends: Ends,
1232 pub(crate) feature_state: FeatureStateStore,
1233 pub(crate) callback_sources: CallbackSources,
1235 pub(crate) geojson_updates: GeoJsonUpdates,
1237}
1238
1239impl MapEntry {
1240 pub(crate) fn applied(&self) -> Applied {
1241 Applied {
1242 sequence: self.applied,
1243 generation: self.core.generation(),
1244 render_update_generation: self.core.pending_update_generation(),
1245 }
1246 }
1247}
1248
1249#[derive(Clone, Default)]
1252pub(crate) struct Ends(Arc<Mutex<Vec<(EndFn, TransitionEnd)>>>);
1253
1254type EndFn = Arc<dyn Fn(&TransitionEnd) + Send + Sync>;
1255
1256impl Ends {
1257 fn defer(&self, animation: &mut AnimationOptions) {
1259 if let Some(end_fn) = animation.transition_end_fn.take() {
1260 let ended = self.0.clone();
1261 animation.transition_end_fn = Some(Arc::new(move |end: &TransitionEnd| {
1262 ended.lock_unpoisoned().push((end_fn.clone(), *end));
1263 }));
1264 }
1265 }
1266
1267 fn deliver(&self, generation: u64, outbox: &mut Outbox) {
1270 for (end_fn, end) in std::mem::take(&mut *self.0.lock_unpoisoned()) {
1271 outbox.push(move || end_fn(&TransitionEnd { generation, ..end }));
1272 }
1273 }
1274}
1275
1276pub(crate) fn create(
1278 core: &mut RuntimeCore,
1279 id: MapId,
1280 options: &MapOptions,
1281 published: Arc<Published>,
1282 resolver: Resolver<Applied>,
1283 outbox: &mut Outbox,
1284) {
1285 let (file_sources, resource_options) = core.file_sources();
1286 let mut map = match mln_map::Map::with_resource_options(options.map, file_sources, resource_options) {
1287 Ok(map) => map,
1288 Err(error) => return outbox.resolve(resolver, Err(error)),
1289 };
1290 if let Some(json) = &options.fallback_font_faces
1291 && let Err(error) = map.style_mut().set_fallback_font_faces(json)
1292 {
1293 return outbox.resolve(resolver, Err(error));
1294 }
1295 let flush_scheduled = Arc::new(AtomicBool::new(false));
1296 let scheduled = flush_scheduled.clone();
1297 let run_loop = core.run_loop.clone();
1298 map.set_waker(Some(Arc::new(move || {
1299 if !scheduled.swap(true, Ordering::SeqCst) {
1300 post(&run_loop, move |core, outbox| flush(core, id, outbox));
1301 }
1302 })));
1303 published.applied.store(1, Ordering::SeqCst);
1304 core.maps.insert(
1305 id,
1306 MapEntry {
1307 core: map,
1308 published,
1309 mask: options.event_mask,
1310 applied: 1,
1311 pending_style: None,
1312 pending_still: None,
1313 session: None,
1314 flush_scheduled,
1315 ends: Ends::default(),
1316 feature_state: FeatureStateStore::default(),
1317 callback_sources: CallbackSources::default(),
1318 geojson_updates: GeoJsonUpdates::default(),
1319 },
1320 );
1321 flush(core, id, outbox);
1322 if let Some(entry) = core.maps.get(&id) {
1323 outbox.resolve(resolver, Ok(entry.applied()));
1324 }
1325}
1326
1327pub(crate) fn apply_command<T>(
1333 core: &mut RuntimeCore,
1334 id: MapId,
1335 sequence: u64,
1336 outbox: &mut Outbox,
1337 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> T,
1338 after: impl FnOnce(&MapEntry, T, Applied, &mut Outbox),
1339) {
1340 flush(core, id, outbox);
1341 let Some(entry) = core.maps.get_mut(&id) else { return };
1342 let value = apply(entry, outbox);
1343 entry.applied = sequence;
1344 flush(core, id, outbox);
1345 let Some(entry) = core.maps.get(&id) else { return };
1346 after(entry, value, entry.applied(), outbox);
1347 entry.published.applied.store(sequence, Ordering::SeqCst);
1348 if let Some(link) = &entry.session {
1349 worker_post(&link.run_loop, move |worker, outbox| worker.map_applied(sequence, outbox));
1350 }
1351}
1352
1353pub(crate) fn run_command<T, R: 'static>(
1356 core: &mut RuntimeCore,
1357 id: MapId,
1358 sequence: u64,
1359 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error>,
1360 finish: impl FnOnce(T, &MapEntry) -> R,
1361 resolver: Resolver<R>,
1362 outbox: &mut Outbox,
1363) {
1364 if !core.maps.contains_key(&id) {
1365 return outbox.resolve(resolver, Err(missing_map()));
1366 }
1367 apply_command(core, id, sequence, outbox, apply, move |entry, result, _, outbox| {
1368 outbox.resolve(resolver, result.map(|value| finish(value, entry)));
1369 });
1370}
1371
1372fn load_style(
1375 core: &mut RuntimeCore,
1376 id: MapId,
1377 sequence: u64,
1378 load: StyleLoad,
1379 resolver: Resolver<Applied>,
1380 outbox: &mut Outbox,
1381) {
1382 if !core.maps.contains_key(&id) {
1383 return outbox.resolve(resolver, Err(missing_map()));
1384 }
1385 apply_command(
1388 core,
1389 id,
1390 sequence,
1391 outbox,
1392 move |entry, outbox| {
1393 let from_json = matches!(load, StyleLoad::Json(_));
1394 if let Some(previous) = entry.pending_style.replace(PendingStyle { resolver, from_json }) {
1395 outbox.resolve(previous.resolver, Err(Error::cancelled("another style load started")));
1396 }
1397 let style = entry.core.style_mut();
1398 match load {
1399 StyleLoad::Url(url) => style.load_url(&url),
1400 StyleLoad::Json(json) => style.load_json(&json),
1401 }
1402 },
1403 |_, (), _, _| {},
1404 );
1405}
1406
1407pub(crate) fn flush(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1410 let Some(entry) = core.maps.get_mut(&id) else { return };
1411 entry.flush_scheduled.store(false, Ordering::SeqCst);
1412 let events = entry.core.drain_events();
1413 crate::style::reconcile(entry, outbox);
1416 let generation = entry.core.generation();
1417 *entry.published.snapshot.lock_unpoisoned() = Some(entry.core.snapshot());
1418
1419 let mut style_outcome = None;
1420 let from_json = entry.pending_style.as_ref().is_some_and(|pending| pending.from_json);
1421 for event in &events {
1422 match event {
1423 MapEvent::StyleLoaded => {
1424 entry.feature_state.clear();
1426 style_outcome = Some(Ok(()));
1427 }
1428 MapEvent::LoadingFailed(StyleLoadError::Parse(message)) if from_json => {
1429 style_outcome = Some(Err(Error::invalid_argument(message)));
1430 }
1431 MapEvent::LoadingFailed(error) => style_outcome = Some(Err(Error::native(error.message()))),
1432 _ => {}
1433 }
1434 }
1435 let style_outcome = style_outcome.map(|outcome| (outcome, entry.pending_style.take(), entry.applied()));
1436 let still_outcome = entry.pending_still.as_ref().and_then(|pending| pending.outcome.borrow_mut().take());
1437 let still = still_outcome.and_then(|outcome| Some((outcome, entry.pending_still.take()?.resolver)));
1438
1439 let mask = entry.mask;
1440 let events: Vec<RuntimeEvent> = events
1441 .into_iter()
1442 .map(RuntimeEventKind::Map)
1443 .filter(|kind| mask.contains(kind.event_type()))
1444 .map(|kind| RuntimeEvent { source: EventSource::Map { id, generation }, kind })
1445 .collect();
1446 let ends = entry.ends.clone();
1447 core.send_events(events, outbox);
1448 ends.deliver(generation, outbox);
1449
1450 if let Some((outcome, Some(pending), applied)) = style_outcome {
1451 outbox.resolve(pending.resolver, outcome.map(|()| applied));
1452 }
1453 if let Some((outcome, resolver)) = still {
1454 outbox.resolve(resolver, outcome);
1455 }
1456}
1457
1458fn remove(core: &mut RuntimeCore, id: MapId, done: Option<Resolver<()>>, outbox: &mut Outbox) {
1460 flush(core, id, outbox);
1461 if let Some(mut entry) = core.maps.remove(&id) {
1462 entry.core.set_waker(None);
1463 if let Some(pending) = entry.pending_style.take() {
1464 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1465 }
1466 if let Some(pending) = entry.pending_still.take() {
1467 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1468 }
1469 crate::style::release(&mut entry, outbox);
1470 let ends = entry.ends.clone();
1473 drop(entry);
1474 ends.deliver(0, outbox);
1475 }
1476 if let Some(done) = done {
1477 outbox.resolve(done, Ok(()));
1478 }
1479}