1use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::{Arc, OnceLock, Weak};
5
6use mln_map::{
7 BoundOptions, Camera, CameraCommandId, CameraDelta, CameraOptions, CameraUpdate, FrameClock, FreeCameraOptions,
8 LogicalExtent, MapDebugOptions, MapEvent, MapMode, MapSnapshot, ProjectionMode, StyleLoadError, TransitionEnd,
9 TransitionOutcome,
10};
11use mln_renderer::text::font_face_engine::FontFaceEngine;
12use mln_renderer::{Registry, UpdateReader};
13use mln_style::Edit;
14use mln_style::layers::CustomLayerHost;
15use mln_text::GlyphCache;
16use mln_util::error::{Error, ErrorKind};
17use mln_util::event_queue::Waker;
18use mln_util::geo::LatLngBounds;
19use mln_util::hash::HashMap;
20use mln_util::pool::Pool;
21use mln_util::size::Size;
22use mln_util::time::Instant;
23use parking_lot::Mutex;
24
25use crate::camera::{self, CameraFitArea, CameraFitOptions, CameraFitUpdate, TileOptions, ViewportOptions};
26use crate::completion::{Completion, Resolver};
27use crate::event::{EventMask, EventSource, RuntimeEvent, RuntimeEventKind};
28use crate::feature_state::{FeatureState, FeatureStateSelector};
29use crate::render::{
30 Abandoner, AttachOptions, RenderSession, RenderTarget, SessionId, SessionQueue, SessionShared, Worker, worker_post,
31};
32use crate::runtime::{CoreQueue, Outbox, Runtime, RuntimeCore, RuntimeShared, post};
33use crate::style::{CallbackSources, GeoJsonUpdates};
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
37pub struct MapId(pub u64);
38
39#[derive(Clone, Debug)]
41pub struct MapOptions {
42 pub map: mln_map::MapOptions,
43 pub event_mask: EventMask,
45 pub fallback_font_faces: Option<String>,
50 pub system_fonts: bool,
58 pub tile_cache_enabled: bool,
61}
62
63impl Default for MapOptions {
64 fn default() -> Self {
65 MapOptions {
66 map: mln_map::MapOptions::default(),
67 event_mask: EventMask::default(),
68 fallback_font_faces: None,
69 system_fonts: true,
70 tile_cache_enabled: true,
71 }
72 }
73}
74
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub struct Applied {
78 pub sequence: u64,
81 pub generation: u64,
84 pub render_update_generation: u64,
87}
88
89fn fit(map: &mut mln_map::Map, area: &CameraFitArea, update: CameraFitUpdate) -> Result<CameraCommandId, Error> {
91 let CameraFitUpdate { mode, fit, animation } = update;
92 let camera = camera::camera_for(map, area, &fit)?;
93 Ok(map.update_camera(&CameraUpdate { mode, camera, animation, ..CameraUpdate::default() }))
94}
95
96#[derive(Clone, Copy, Debug, PartialEq)]
98pub struct CameraQuery {
99 pub generation: u64,
100 pub camera: Camera,
101}
102
103pub(crate) struct Published {
105 snapshot: Mutex<Option<MapSnapshot>>,
106 updates: OnceLock<UpdateReader>,
108 applied: AtomicU64,
111 frame_clock: OnceLock<FrameClock>,
114 samples_requested: AtomicU64,
117 sampled: AtomicU64,
118 sample_queued: AtomicBool,
121 event_mask: AtomicU64,
122 still_image: AtomicU64,
125}
126
127impl Published {
128 pub(crate) fn applied(&self) -> u64 {
131 self.applied.load(Ordering::SeqCst)
132 }
133
134 pub(crate) fn sampled(&self) -> u64 {
136 self.sampled.load(Ordering::SeqCst)
137 }
138
139 pub(crate) fn pending_still_image(&self) -> u64 {
143 self.still_image.load(Ordering::SeqCst)
144 }
145
146 pub(crate) fn new(event_mask: EventMask) -> Self {
147 Published {
148 snapshot: Mutex::new(None),
149 updates: OnceLock::new(),
150 applied: AtomicU64::new(0),
151 frame_clock: OnceLock::new(),
152 samples_requested: AtomicU64::new(0),
153 sampled: AtomicU64::new(0),
154 sample_queued: AtomicBool::new(false),
155 event_mask: AtomicU64::new(event_mask.bits()),
156 still_image: AtomicU64::new(0),
157 }
158 }
159}
160
161pub(crate) struct MapShared {
162 id: MapId,
163 runtime: Arc<RuntimeShared>,
164 mode: MapMode,
165 scale_factor: AtomicU64,
168 tile_cache_enabled: bool,
169 system_fonts: bool,
170 session: Mutex<Option<SessionClaim>>,
173 sent: Mutex<u64>,
177 released: AtomicBool,
179 removed: AtomicBool,
181 published: Arc<Published>,
182}
183
184impl MapShared {
185 pub(crate) fn new(id: MapId, runtime: Arc<RuntimeShared>, options: &MapOptions, published: Arc<Published>) -> Self {
186 MapShared {
187 id,
188 runtime,
189 mode: options.map.map_mode,
190 scale_factor: AtomicU64::new(f64::from(options.map.pixel_ratio).to_bits()),
191 tile_cache_enabled: options.tile_cache_enabled,
192 system_fonts: options.system_fonts,
193 session: Mutex::new(None),
194 sent: Mutex::new(1),
195 released: AtomicBool::new(false),
196 removed: AtomicBool::new(false),
197 published,
198 }
199 }
200
201 fn completion<R: Send + 'static>(&self, discard: Option<fn(Error)>) -> (Completion<R>, Resolver<R>) {
205 match discard {
206 Some(on_failure) => Completion::discarded(on_failure),
207 None => self.runtime.completion(),
208 }
209 }
210
211 pub(crate) fn send<R: Send + 'static>(
213 &self,
214 discard: Option<fn(Error)>,
215 command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
216 ) -> Result<Completion<R>, Error> {
217 let mut sent = self.sent.lock();
218 if self.released.load(Ordering::SeqCst) {
219 return Err(released());
220 }
221 let (completion, resolver) = self.completion(discard);
222 let id = self.id;
223 *sent += 1;
224 let sequence = *sent;
225 self.runtime.post(move |core, outbox| command(core, outbox, id, sequence, resolver));
226 Ok(completion)
227 }
228
229 fn release(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
232 self.close()?;
233 self.remove(done);
234 Ok(())
235 }
236
237 fn close(&self) -> Result<(), Error> {
240 let _sent = self.sent.lock();
241 if self.released.swap(true, Ordering::SeqCst) {
242 return Err(released());
243 }
244 Ok(())
245 }
246
247 fn remove(&self, done: Option<Resolver<()>>) {
250 if self.removed.swap(true, Ordering::SeqCst) {
251 return;
252 }
253 let id = self.id;
254 self.runtime.post(move |core, outbox| remove(core, id, done, outbox));
255 self.runtime.map_released();
256 }
257}
258
259impl Drop for MapShared {
260 fn drop(&mut self) {
261 let _ = self.close();
262 let deferred = self.session.get_mut().take().and_then(|claim| claim.removal);
263 self.remove(deferred);
264 }
265}
266
267#[derive(Clone)]
280pub struct Map {
281 pub(crate) shared: Arc<MapShared>,
282 discard: Option<fn(Error)>,
285}
286
287impl std::fmt::Debug for Map {
288 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289 f.debug_struct("Map").field("id", &self.shared.id).field("discards_results", &self.discard.is_some()).finish()
290 }
291}
292
293impl PartialEq for Map {
294 fn eq(&self, other: &Map) -> bool {
295 Arc::ptr_eq(&self.shared, &other.shared)
296 }
297}
298
299impl Eq for Map {}
300
301fn released() -> Error {
302 Error::invalid_state("the map was released")
303}
304
305pub(crate) fn style_not_loaded() -> Error {
306 Error::invalid_state("style is not loaded")
307}
308
309pub(crate) fn missing_map() -> Error {
312 Error::invalid_state("the map failed to be built or was released")
313}
314
315impl Map {
316 pub(crate) fn new(shared: MapShared) -> Self {
317 Map { shared: Arc::new(shared), discard: None }
318 }
319
320 #[must_use]
325 pub fn discarding_results(&self, on_failure: fn(Error)) -> Map {
326 Map { shared: Arc::clone(&self.shared), discard: Some(on_failure) }
327 }
328
329 pub(crate) fn post<R: Send + 'static>(
332 &self,
333 command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
334 ) -> Result<Completion<R>, Error> {
335 self.shared.send(self.discard, command)
336 }
337
338 #[must_use]
339 pub fn id(&self) -> MapId {
340 self.shared.id
341 }
342
343 #[must_use]
345 pub fn mode(&self) -> MapMode {
346 self.shared.mode
347 }
348
349 #[must_use]
351 pub fn runtime(&self) -> Runtime {
352 Runtime { shared: Arc::clone(&self.shared.runtime) }
353 }
354
355 #[must_use]
357 pub fn sent_sequence(&self) -> u64 {
358 *self.shared.sent.lock()
359 }
360
361 #[must_use]
365 pub fn applied_sequence(&self) -> u64 {
366 self.shared.published.applied.load(Ordering::SeqCst)
367 }
368
369 pub fn snapshot(&self) -> Result<MapSnapshot, Error> {
379 if self.shared.released.load(Ordering::SeqCst) {
380 return Err(released());
381 }
382 let mut snapshot =
383 self.shared.published.snapshot.lock().ok_or_else(|| Error::invalid_state("the map isn't built"))?;
384 if let Some(updates) = self.shared.published.updates.get() {
388 snapshot.update_generation = updates.generation();
389 }
390 Ok(snapshot)
391 }
392
393 #[must_use]
395 pub fn event_mask(&self) -> EventMask {
396 EventMask::from_bits(self.shared.published.event_mask.load(Ordering::SeqCst)).unwrap_or_default()
397 }
398
399 pub(crate) fn send<T: 'static, R: Send + 'static>(
402 &self,
403 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error> + Send + 'static,
404 finish: impl FnOnce(T, &MapEntry) -> R + Send + 'static,
405 ) -> Result<Completion<R>, Error> {
406 self.post(move |core, outbox, id, sequence, resolver| {
407 run_command(core, id, sequence, apply, finish, resolver, outbox);
408 })
409 }
410
411 pub(crate) fn command(
413 &self,
414 apply: impl FnOnce(&mut mln_map::Map) -> Result<(), Error> + Send + 'static,
415 ) -> Result<Completion<Applied>, Error> {
416 self.send(move |entry, _| apply(&mut entry.core), |(), entry| entry.applied())
417 }
418
419 pub(crate) fn query<T: Send + 'static>(
421 &self,
422 read: impl FnOnce(&mut mln_map::Map) -> Result<T, Error> + Send + 'static,
423 ) -> Result<Completion<T>, Error> {
424 self.send(move |entry, _| read(&mut entry.core), |value, _| value)
425 }
426
427 pub fn with_core<R: Send + 'static>(
432 &self,
433 f: impl FnOnce(&mut mln_map::Map) -> R + Send + 'static,
434 ) -> Result<Completion<R>, Error> {
435 self.query(move |map| Ok(f(map)))
436 }
437
438 pub fn release(&self) -> Result<Completion<()>, Error> {
449 self.release_with(false)
450 }
451
452 pub fn dispose(&self) -> Result<Completion<()>, Error> {
464 self.release_with(true)
465 }
466
467 fn release_with(&self, in_any_state: bool) -> Result<Completion<()>, Error> {
468 let (completion, resolver) = self.shared.completion(self.discard);
469 let claimed = {
470 let mut claim = self.shared.session.lock();
471 match claim.as_mut() {
472 None => None,
473 Some(held) => match held.session.upgrade() {
474 Some(session) if session.is_released() => Some((held.id, Some(session))),
476 Some(_) if in_any_state => {
479 self.shared.close()?;
480 held.removal = Some(resolver);
481 return Ok(completion);
482 }
483 Some(_) => return Err(Error::invalid_state("map still has an attached render session")),
484 None => Some((held.id, None)),
486 },
487 }
488 };
489 if let Some((id, session)) = claimed {
490 if let Some(session) = session {
491 let _ = session.abandon(Abandoner::Library);
492 }
493 self.release_session_claim(id);
494 }
495 self.shared.release(Some(resolver))?;
496 Ok(completion)
497 }
498
499 pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
509 let LogicalExtent { size, scale_factor } = extent;
510 if self.shared.session.lock().is_some() {
511 return Err(Error::invalid_state("the map has a render session: resize the session instead"));
512 }
513 if size.is_empty() {
514 return Err(Error::invalid_argument("logical size dimensions must be positive"));
515 }
516 if !scale_factor.is_finite() || scale_factor <= 0.0 {
517 return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
518 }
519 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
521 self.command(move |map| {
522 if map.snapshot().view.extent.size != size {
523 map.set_size(size)?;
524 }
525 map.set_pixel_ratio(scale_factor as f32)
526 })
527 }
528
529 pub fn request_repaint(&self) -> Result<Completion<Applied>, Error> {
533 if self.shared.mode != MapMode::Continuous {
534 return Err(Error::invalid_state("map is not in continuous mode"));
535 }
536 self.command(|map| {
537 map.trigger_repaint();
538 Ok(())
539 })
540 }
541
542 pub fn begin_command_group(&self) -> Result<Completion<Applied>, Error> {
547 self.command(|map| {
548 map.begin_command_group();
549 Ok(())
550 })
551 }
552
553 pub fn end_command_group(&self) -> Result<Completion<Applied>, Error> {
557 self.command(mln_map::Map::end_command_group)
558 }
559
560 pub fn command_group(&self) -> Result<CommandGroup, Error> {
563 drop(self.begin_command_group()?);
564 Ok(CommandGroup { map: Some(self.clone()) })
565 }
566
567 pub fn set_event_mask(&self, mask: EventMask) -> Result<Completion<Applied>, Error> {
569 self.send(
570 move |entry, _| {
571 if entry.mask != mask {
572 entry.mask = mask;
573 entry.published.event_mask.store(mask.bits(), Ordering::SeqCst);
574 entry.core.record_change();
575 }
576 Ok(())
577 },
578 |(), entry| entry.applied(),
579 )
580 }
581
582 pub fn attach(
609 &self,
610 target: RenderTarget,
611 options: AttachOptions,
612 ) -> Result<(RenderSession, Completion<()>), Error> {
613 crate::render::attach(self, target, options, |session, attached| (session.clone(), attached))
614 }
615
616 pub fn attach_then<R>(
628 &self,
629 target: RenderTarget,
630 options: AttachOptions,
631 then: impl FnOnce(&RenderSession, Completion<()>) -> R,
632 ) -> Result<R, Error> {
633 crate::render::attach(self, target, options, then)
634 }
635
636 pub fn request_still_image(&self) -> Result<Completion<()>, Error> {
661 if self.shared.mode == MapMode::Continuous {
662 return Err(Error::invalid_state("the map is not in static or tile mode"));
663 }
664 self.post(move |core, outbox, id, sequence, resolver| {
665 if !core.maps.contains_key(&id) {
666 return outbox.resolve(resolver, Err(missing_map()));
667 }
668 apply_command(
669 core,
670 id,
671 sequence,
672 outbox,
673 move |entry, outbox| {
674 if entry.pending_still.is_some() {
675 let error = Error::invalid_state("the map is rendering a still image already");
676 return outbox.resolve(resolver, Err(error));
677 }
678 if entry.core.command_group_depth() > 0 {
680 let error = Error::invalid_state("a still image can't render while a command group is open");
681 return outbox.resolve(resolver, Err(error));
682 }
683 let refused = entry.core.render_still().err().map(|error| Err(still_image_error(error)));
684 entry.pending_still = Some(PendingStill { resolver, refused });
685 },
686 |_, (), _, _| {},
687 );
688 })
689 }
690
691 pub(crate) fn is_released(&self) -> bool {
693 self.shared.released.load(Ordering::SeqCst)
694 }
695
696 pub(crate) fn runtime_thread(&self) -> std::thread::ThreadId {
697 self.shared.runtime.thread()
698 }
699
700 #[must_use]
705 pub fn scale_factor(&self) -> f64 {
706 f64::from_bits(self.shared.scale_factor.load(Ordering::SeqCst))
707 }
708
709 pub(crate) fn tile_cache_enabled(&self) -> bool {
710 self.shared.tile_cache_enabled
711 }
712
713 pub(crate) fn local_font_family(&self) -> Option<String> {
718 (cfg!(target_family = "wasm") && self.shared.system_fonts).then(|| "sans-serif".to_owned())
719 }
720
721 pub(crate) fn glyph_cache(&self) -> Arc<GlyphCache> {
722 Arc::clone(&self.shared.runtime.glyph_cache)
723 }
724
725 pub(crate) fn pool(&self) -> Pool {
727 self.shared.runtime.pool.clone()
728 }
729
730 pub(crate) fn font_face_engine(&self) -> Arc<dyn FontFaceEngine> {
732 Arc::clone(&self.shared.runtime.font_face_engine)
733 }
734
735 #[must_use]
740 pub fn registry(&self) -> &Arc<Registry> {
741 &self.shared.runtime.registry
742 }
743
744 pub(crate) fn claim_session(&self, id: SessionId, session: Weak<SessionShared>) -> Result<(), Error> {
746 let mut claim = self.shared.session.lock();
747 if self.shared.released.load(Ordering::SeqCst) {
748 return Err(released());
749 }
750 if claim.is_some() {
751 return Err(Error::invalid_state("the map already has an attached render session"));
752 }
753 *claim = Some(SessionClaim { id, session, removal: None });
754 Ok(())
755 }
756
757 pub(crate) fn release_session_claim(&self, id: SessionId) {
760 let claim = {
761 let mut session = self.shared.session.lock();
762 if session.as_ref().is_some_and(|claim| claim.id == id) { session.take() } else { None }
763 };
764 if let Some(removal) = claim.and_then(|claim| claim.removal) {
765 self.shared.remove(Some(removal));
766 }
767 }
768
769 pub(crate) fn bind_session(
774 &self,
775 id: SessionId,
776 queue: SessionQueue,
777 awaited: Arc<AtomicU64>,
778 size: Size,
779 ) -> Result<(), Error> {
780 let sent = self.shared.send(Some(drop), move |core, outbox, map_id, sequence, resolver: Resolver<()>| {
781 drop(resolver);
782 if !core.maps.contains_key(&map_id) {
783 return worker_post(&queue, |worker, outbox| worker.bind_failed(missing_map(), outbox));
784 }
785 let link = SessionLink { id, queue: queue.clone(), awaited };
786 apply_command(
787 core,
788 map_id,
789 sequence,
790 outbox,
791 move |entry, _| {
792 entry.session = Some(link);
793 let resized = entry.core.set_size(size);
794 (resized, entry.core.update_reader(), entry.core.renderer_events(), Arc::clone(&entry.published))
795 },
796 move |_, (resized, reader, events, published), _, _| match resized {
797 Ok(()) => {
798 let bound = move |worker: &mut Worker, outbox: &mut Outbox| {
799 worker.bound(sequence, reader, events, published, outbox);
800 };
801 worker_post(&queue, bound);
802 }
803 Err(error) => worker_post(&queue, move |worker, outbox| worker.bind_failed(error, outbox)),
804 },
805 );
806 });
807 sent.map(drop)
808 }
809
810 pub(crate) fn unbind_session(&self, id: SessionId) {
813 let map_id = self.shared.id;
814 self.shared.runtime.post_or((), move |core, _, ()| unbind(core, map_id, id), |()| {});
816 }
817
818 pub(crate) fn unbind_session_then(
821 &self,
822 id: SessionId,
823 queue: SessionQueue,
824 then: impl FnOnce(&mut Worker, &mut Outbox) + Send + 'static,
825 ) {
826 let map_id = self.shared.id;
827 let session_queue = queue.clone();
828 self.shared.runtime.post_or(
830 then,
831 move |core, _, then| {
832 unbind(core, map_id, id);
833 worker_post(&queue, then);
834 },
835 |then| worker_post(&session_queue, then),
836 );
837 }
838
839 pub(crate) fn frame_demanded(&self) -> u64 {
845 let published = &self.shared.published;
846 if let Some(clock) = published.frame_clock.get() {
847 clock.set(Some(Instant::now()));
848 }
849 let animating = published.snapshot.lock().is_some_and(|snapshot| snapshot.transition_in_progress);
852 if self.shared.mode != MapMode::Continuous || !animating {
853 return 0;
854 }
855 let sample = published.samples_requested.fetch_add(1, Ordering::SeqCst) + 1;
856 if !published.sample_queued.swap(true, Ordering::SeqCst) {
857 let id = self.shared.id;
858 self.shared.runtime.post_apart(move |core, outbox| sample_frame(core, id, outbox));
859 }
860 sample
861 }
862
863 pub(crate) fn resize_for_session(
867 &self,
868 size: Size,
869 scale_factor: f64,
870 queue: SessionQueue,
871 resize: impl FnOnce(&mut Worker, Result<Applied, Error>, &mut Outbox) + Send + 'static,
872 ) -> Result<(), Error> {
873 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
875 let sent = self.shared.send(Some(drop), move |core, outbox, id, sequence, resolver: Resolver<()>| {
876 drop(resolver);
877 if !core.maps.contains_key(&id) {
878 return worker_post(&queue, move |worker, outbox| resize(worker, Err(missing_map()), outbox));
879 }
880 apply_command(
881 core,
882 id,
883 sequence,
884 outbox,
885 move |entry, _| {
886 let pixel_ratio = scale_factor as f32;
890 let extent = entry.core.snapshot().view.extent;
891 if extent.size == size && extent.scale_factor == f64::from(pixel_ratio) {
892 return Ok(());
893 }
894 entry.core.set_size(size)?;
895 entry.core.set_pixel_ratio(pixel_ratio)
896 },
897 move |_, resized, applied, _| {
898 let result = resized.map(|()| applied);
899 worker_post(&queue, move |worker, outbox| resize(worker, result, outbox));
900 },
901 );
902 });
903 sent.map(drop)
904 }
905
906 pub fn set_feature_state(
927 &self,
928 selector: &FeatureStateSelector,
929 state: FeatureState,
930 ) -> Result<Completion<Applied>, Error> {
931 let key = selector.key(true)?;
932 self.command(move |map| {
933 let feature_id = key.feature_id.as_deref().unwrap_or_default();
934 map.set_feature_state(&key.source_id, Some(&key.source_layer_id), feature_id, state);
935 Ok(())
936 })
937 }
938
939 pub fn feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<FeatureState>, Error> {
943 let key = selector.key(true)?;
944 self.query(move |map| {
945 let feature_id = key.feature_id.as_deref().unwrap_or_default();
946 Ok(map.get_feature_state(&key.source_id, Some(&key.source_layer_id), feature_id))
947 })
948 }
949
950 pub fn remove_feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<Applied>, Error> {
958 let key = selector.key(false)?;
959 self.command(move |map| {
960 map.remove_feature_state(
961 &key.source_id,
962 Some(&key.source_layer_id),
963 key.feature_id.as_deref(),
964 key.state_key.as_deref(),
965 );
966 Ok(())
967 })
968 }
969
970 pub fn set_style_url(&self, url: impl Into<String>) -> Result<Completion<Applied>, Error> {
982 let url = url.into();
983 if url.is_empty() {
984 return Err(Error::invalid_argument("style URL must not be empty"));
985 }
986 self.load_style(StyleLoad::Url(url))
987 }
988
989 pub fn set_style_json(&self, json: impl Into<String>) -> Result<Completion<Applied>, Error> {
995 let json = json.into();
996 if json.is_empty() {
997 return Err(Error::invalid_argument("style JSON must not be empty"));
998 }
999 self.load_style(StyleLoad::Json(json))
1000 }
1001
1002 fn load_style(&self, load: StyleLoad) -> Result<Completion<Applied>, Error> {
1003 self.post(move |core, outbox, id, sequence, resolver| {
1004 load_style(core, id, sequence, load, resolver, outbox);
1005 })
1006 }
1007
1008 pub fn loaded_style_json(&self) -> Result<Completion<String>, Error> {
1011 self.query(|map| Ok(map.style().get_json().to_owned()))
1012 }
1013
1014 pub fn style_url(&self) -> Result<Completion<Option<String>>, Error> {
1016 self.query(|map| Ok(map.style_url().filter(|url| !url.is_empty()).map(str::to_owned)))
1017 }
1018
1019 pub fn add_style_source_json(
1022 &self,
1023 source_id: impl Into<String>,
1024 json: impl Into<String>,
1025 ) -> Result<Completion<Applied>, Error> {
1026 let (source_id, json) = (source_id.into(), json.into());
1027 self.command(move |map| map.add_source_json(&source_id, &json))
1028 }
1029
1030 pub fn remove_style_source(&self, source_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1037 let source_id = source_id.into();
1038 self.send(
1039 move |entry, _| {
1040 let map = &mut entry.core;
1041 if !map.style_document_loaded() {
1042 return Err(style_not_loaded());
1043 }
1044 if map.source(&source_id).is_none() {
1045 return Err(Error::not_found(format!("source \"{source_id}\" does not exist")));
1046 }
1047 if let Some(layer) = map.style().get_layers().find(|layer| layer.get_source_id() == source_id) {
1048 let message = format!("source \"{source_id}\" is used by layer \"{}\"", layer.get_id());
1049 return Err(Error::invalid_state(message));
1050 }
1051 map.remove_source(&source_id);
1052 entry.core.remove_source_feature_state(&source_id);
1053 Ok(())
1054 },
1055 |(), entry| entry.applied(),
1056 )
1057 }
1058
1059 pub fn add_style_layer_json(
1062 &self,
1063 json: impl Into<String>,
1064 before_layer_id: Option<String>,
1065 ) -> Result<Completion<Applied>, Error> {
1066 let json = json.into();
1067 self.command(move |map| map.edit_loaded_style(|style| style.add_layer_json(&json, before_layer_id.as_deref())))
1068 }
1069
1070 pub fn add_custom_layer(
1075 &self,
1076 layer_id: impl Into<String>,
1077 host: Arc<dyn CustomLayerHost>,
1078 before_layer_id: Option<String>,
1079 ) -> Result<Completion<Applied>, Error> {
1080 let layer_id = layer_id.into();
1081 self.command(move |map| {
1082 map.edit_loaded_style(|style| style.add_custom_layer(&layer_id, host, before_layer_id.as_deref()))
1083 })
1084 }
1085
1086 pub fn remove_style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1091 let layer_id = layer_id.into();
1092 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::RemoveLayer(layer_id))))
1093 }
1094
1095 pub fn style_layer_json(&self, layer_id: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1098 let layer_id = layer_id.into();
1099 self.query(move |map| Ok(map.style().layer_json(&layer_id)))
1100 }
1101
1102 pub fn set_style_layer_property(
1105 &self,
1106 layer_id: impl Into<String>,
1107 name: impl Into<String>,
1108 json: impl Into<String>,
1109 ) -> Result<Completion<Applied>, Error> {
1110 let (layer_id, name, json) = (layer_id.into(), name.into(), json.into());
1111 self.command(move |map| map.edit_loaded_style(|style| style.set_layer_property_json(&layer_id, &name, &json)))
1112 }
1113
1114 pub fn style_layer_property(
1117 &self,
1118 layer_id: impl Into<String>,
1119 name: impl Into<String>,
1120 ) -> Result<Completion<Option<String>>, Error> {
1121 let (layer_id, name) = (layer_id.into(), name.into());
1122 self.query(move |map| map.style().layer_property_json(&layer_id, &name))
1123 }
1124
1125 pub fn set_style_root_property(
1129 &self,
1130 name: impl Into<String>,
1131 json: impl Into<String>,
1132 ) -> Result<Completion<Applied>, Error> {
1133 let (name, json) = (name.into(), json.into());
1134 self.command(move |map| map.edit_loaded_style(|style| style.set_root_property_json(&name, &json)))
1135 }
1136
1137 pub fn style_root_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1140 let name = name.into();
1141 self.query(move |map| map.style().root_property_json(&name))
1142 }
1143
1144 pub fn set_style_light_property(
1146 &self,
1147 name: impl Into<String>,
1148 json: impl Into<String>,
1149 ) -> Result<Completion<Applied>, Error> {
1150 let (name, json) = (name.into(), json.into());
1151 self.command(move |map| map.edit_loaded_style(|style| style.set_light_property_json(&name, &json)))
1152 }
1153
1154 pub fn style_light_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1157 let name = name.into();
1158 self.query(move |map| Ok(map.style().light_property_json(&name)))
1159 }
1160
1161 fn camera_command(
1166 &self,
1167 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1168 ) -> Result<Completion<Applied>, Error> {
1169 self.send_camera(apply, None)
1170 }
1171
1172 fn camera_command_then(
1177 &self,
1178 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1179 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1180 ) -> Result<Completion<Applied>, Error> {
1181 let (ended, end) = self.shared.runtime.completion();
1182 ended.on_complete(on_end);
1183 self.send_camera(apply, Some(end))
1184 }
1185
1186 fn send_camera(
1189 &self,
1190 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1191 end: Option<Resolver<TransitionEnd>>,
1192 ) -> Result<Completion<Applied>, Error> {
1193 self.send(
1194 move |entry, outbox| match (apply(&mut entry.core), end) {
1195 (Ok(command), Some(end)) => {
1196 entry.camera_commands.insert(command, end);
1197 Ok(())
1198 }
1199 (Ok(_), None) => Ok(()),
1200 (Err(error), end) => {
1201 if let Some(end) = end {
1202 let generation = entry.core.generation();
1203 let cancelled =
1204 TransitionEnd { outcome: TransitionOutcome::Cancelled, generation, ..Default::default() };
1205 outbox.resolve(end, Ok(cancelled));
1206 }
1207 Err(error)
1208 }
1209 },
1210 |(), entry| entry.applied(),
1211 )
1212 }
1213
1214 pub fn update_camera(&self, update: CameraUpdate) -> Result<Completion<Applied>, Error> {
1216 self.camera_command(move |map| Ok(map.update_camera(&update)))
1217 }
1218
1219 pub fn update_camera_then(
1229 &self,
1230 update: CameraUpdate,
1231 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1232 ) -> Result<Completion<Applied>, Error> {
1233 self.camera_command_then(move |map| Ok(map.update_camera(&update)), on_end)
1234 }
1235
1236 pub fn apply_camera_delta(&self, delta: CameraDelta) -> Result<Completion<Applied>, Error> {
1240 self.camera_command(move |map| {
1241 map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string()))
1242 })
1243 }
1244
1245 pub fn apply_camera_delta_then(
1249 &self,
1250 delta: CameraDelta,
1251 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1252 ) -> Result<Completion<Applied>, Error> {
1253 self.camera_command_then(
1254 move |map| map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string())),
1255 on_end,
1256 )
1257 }
1258
1259 pub fn camera_for(
1266 &self,
1267 area: CameraFitArea,
1268 options: CameraFitOptions,
1269 ) -> Result<Completion<CameraOptions>, Error> {
1270 self.query(move |map| camera::camera_for(map, &area, &options))
1271 }
1272
1273 pub fn fit_camera(&self, area: CameraFitArea, update: CameraFitUpdate) -> Result<Completion<Applied>, Error> {
1280 self.camera_command(move |map| fit(map, &area, update))
1281 }
1282
1283 pub fn fit_camera_then(
1287 &self,
1288 area: CameraFitArea,
1289 update: CameraFitUpdate,
1290 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1291 ) -> Result<Completion<Applied>, Error> {
1292 self.camera_command_then(move |map| fit(map, &area, update), on_end)
1293 }
1294
1295 pub fn cancel_camera_transitions(&self) -> Result<Completion<Applied>, Error> {
1297 self.command(|map| {
1298 map.cancel_transitions();
1299 Ok(())
1300 })
1301 }
1302
1303 pub fn cancel_camera_transitions_with_id(&self, transition_id: u64) -> Result<Completion<Applied>, Error> {
1305 self.command(move |map| {
1306 map.cancel_transitions_with_id(transition_id);
1307 Ok(())
1308 })
1309 }
1310
1311 pub fn camera(&self) -> Result<Completion<CameraQuery>, Error> {
1313 self.send(
1314 |_, _| Ok(()),
1315 |(), entry| CameraQuery { generation: entry.core.generation(), camera: entry.core.snapshot().view.camera },
1316 )
1317 }
1318
1319 pub fn lat_lng_bounds_for_camera(&self, camera: CameraOptions) -> Result<Completion<LatLngBounds>, Error> {
1324 self.query(move |map| map.lat_lng_bounds_for_camera_unwrapped(&camera))
1325 }
1326
1327 pub fn set_bounds(&self, bounds: BoundOptions) -> Result<Completion<Applied>, Error> {
1329 self.command(move |map| map.set_bounds(&bounds))
1330 }
1331
1332 pub fn set_free_camera_options(&self, camera: FreeCameraOptions) -> Result<Completion<Applied>, Error> {
1334 self.command(move |map| {
1335 map.set_free_camera_options(&camera);
1336 Ok(())
1337 })
1338 }
1339
1340 pub fn set_viewport_options(&self, options: ViewportOptions) -> Result<Completion<Applied>, Error> {
1342 self.command(move |map| {
1343 camera::set_viewport(map, &options);
1344 Ok(())
1345 })
1346 }
1347
1348 pub fn set_tile_options(&self, options: TileOptions) -> Result<Completion<Applied>, Error> {
1350 self.command(move |map| {
1351 camera::set_tile_options(map, &options);
1352 Ok(())
1353 })
1354 }
1355
1356 pub fn set_projection_mode(&self, mode: ProjectionMode) -> Result<Completion<Applied>, Error> {
1357 self.command(move |map| {
1358 map.set_projection_mode(&mode);
1359 Ok(())
1360 })
1361 }
1362
1363 pub fn set_debug_flags(&self, flags: MapDebugOptions) -> Result<Completion<Applied>, Error> {
1365 self.command(move |map| {
1366 map.set_debug(flags);
1367 Ok(())
1368 })
1369 }
1370
1371 pub fn set_rendering_stats_view_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1373 self.command(move |map| {
1374 map.enable_rendering_stats_view(enabled);
1375 Ok(())
1376 })
1377 }
1378
1379 pub fn set_globe_free_bearing_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1382 self.command(move |map| {
1383 map.set_globe_free_bearing(enabled);
1384 Ok(())
1385 })
1386 }
1387
1388 pub fn dump_debug_logs(&self) -> Result<Completion<Applied>, Error> {
1390 self.command(|map| {
1391 map.dump_debug_logs();
1392 Ok(())
1393 })
1394 }
1395}
1396
1397#[must_use = "the group ends when it drops"]
1399pub struct CommandGroup {
1400 map: Option<Map>,
1401}
1402
1403impl CommandGroup {
1404 pub fn end(mut self) -> Result<Completion<Applied>, Error> {
1406 match self.map.take() {
1407 Some(map) => map.end_command_group(),
1408 None => Err(Error::invalid_state("the group ended already")),
1409 }
1410 }
1411}
1412
1413impl Drop for CommandGroup {
1414 fn drop(&mut self) {
1415 if let Some(map) = self.map.take() {
1416 let _ = map.end_command_group();
1417 }
1418 }
1419}
1420
1421enum StyleLoad {
1422 Url(String),
1423 Json(String),
1424}
1425
1426struct PendingStyle {
1428 resolver: Resolver<Applied>,
1429 from_json: bool,
1432}
1433
1434struct SessionClaim {
1436 id: SessionId,
1437 session: Weak<SessionShared>,
1438 removal: Option<Resolver<()>>,
1440}
1441
1442fn unbind(core: &mut RuntimeCore, map_id: MapId, id: SessionId) {
1445 if let Some(entry) = core.maps.get_mut(&map_id)
1446 && entry.session.as_ref().is_some_and(|link| link.id == id)
1447 {
1448 entry.session = None;
1449 }
1450}
1451
1452pub(crate) struct SessionLink {
1454 id: SessionId,
1455 queue: SessionQueue,
1456 awaited: Arc<AtomicU64>,
1458}
1459
1460struct PendingStill {
1463 resolver: Resolver<()>,
1464 refused: Option<Result<(), Error>>,
1467}
1468
1469fn still_image_error(error: Error) -> Error {
1472 match error.kind {
1473 ErrorKind::InvalidState => error,
1474 _ => Error::native(error.message),
1475 }
1476}
1477
1478pub(crate) struct MapEntry {
1480 pub(crate) core: mln_map::Map,
1481 published: Arc<Published>,
1482 mask: EventMask,
1483 applied: u64,
1485 held_applied: Option<u64>,
1488 held_sampled: Option<u64>,
1489 pending_style: Option<PendingStyle>,
1491 pending_still: Option<PendingStill>,
1492 session: Option<SessionLink>,
1494 flush_pending: FlushFlag,
1496 camera_commands: HashMap<CameraCommandId, Resolver<TransitionEnd>>,
1498 pub(crate) callback_sources: CallbackSources,
1500 pub(crate) geojson_updates: GeoJsonUpdates,
1502}
1503
1504impl MapEntry {
1505 pub(crate) fn applied(&self) -> Applied {
1506 Applied {
1507 sequence: self.applied,
1508 generation: self.core.generation(),
1509 render_update_generation: self.core.pending_update_generation(),
1510 }
1511 }
1512}
1513
1514#[derive(Clone, Default)]
1518struct FlushFlag(Arc<AtomicBool>);
1519
1520impl FlushFlag {
1521 fn waker(&self, queue: &CoreQueue, id: MapId) -> Waker {
1525 let (flag, queue) = (self.clone(), queue.downgrade());
1526 Arc::new(move || {
1527 if !flag.0.swap(true, Ordering::SeqCst)
1528 && let Some(queue) = queue.upgrade()
1529 {
1530 let flag = flag.clone();
1531 post(&queue, move |core, outbox| {
1532 if flag.is_set() {
1533 flush(core, id, outbox);
1534 }
1535 });
1536 }
1537 })
1538 }
1539
1540 fn is_set(&self) -> bool {
1541 self.0.load(Ordering::SeqCst)
1542 }
1543
1544 fn clear(&self) {
1545 self.0.store(false, Ordering::SeqCst);
1546 }
1547}
1548
1549pub(crate) fn create(
1551 core: &mut RuntimeCore,
1552 id: MapId,
1553 options: &MapOptions,
1554 published: Arc<Published>,
1555 resolver: Resolver<Applied>,
1556 outbox: &mut Outbox,
1557) {
1558 let registry = Arc::clone(core.registry.style());
1559 let mut map = match mln_map::Map::with_registry(Arc::clone(core.loader()), options.map, registry, &core.pool) {
1560 Ok(map) => map,
1561 Err(error) => return outbox.resolve(resolver, Err(error)),
1562 };
1563 if let Some(json) = &options.fallback_font_faces {
1564 if let Err(error) = map.set_fallback_font_faces(json) {
1565 return outbox.resolve(resolver, Err(error));
1566 }
1567 } else if options.system_fonts {
1568 map.set_fallback_font_face_list(mln_system_fonts::fallback_font_face_list());
1569 }
1570 let _ = published.updates.set(map.update_reader());
1571 let _ = published.frame_clock.set(map.frame_clock());
1572 let flush_pending = FlushFlag::default();
1573 map.set_reports_waker(Some(flush_pending.waker(&core.queue, id)));
1574 published.applied.store(1, Ordering::SeqCst);
1575 core.maps.insert(
1576 id,
1577 MapEntry {
1578 core: map,
1579 published,
1580 mask: options.event_mask,
1581 applied: 1,
1582 held_applied: None,
1583 held_sampled: None,
1584 pending_style: None,
1585 pending_still: None,
1586 session: None,
1587 flush_pending,
1588 camera_commands: HashMap::default(),
1589 callback_sources: CallbackSources::default(),
1590 geojson_updates: GeoJsonUpdates::default(),
1591 },
1592 );
1593 flush(core, id, outbox);
1594 if let Some(entry) = core.maps.get(&id) {
1595 outbox.resolve(resolver, Ok(entry.applied()));
1596 }
1597}
1598
1599pub(crate) fn apply_command<T>(
1607 core: &mut RuntimeCore,
1608 id: MapId,
1609 sequence: u64,
1610 outbox: &mut Outbox,
1611 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> T,
1612 after: impl FnOnce(&MapEntry, T, Applied, &mut Outbox),
1613) {
1614 if core.maps.get(&id).is_some_and(|entry| entry.flush_pending.is_set() || entry.core.has_reports()) {
1618 flush(core, id, outbox);
1619 }
1620 let Some(entry) = core.maps.get_mut(&id) else { return };
1621 let value = apply(entry, outbox);
1622 entry.applied = sequence;
1623 flush(core, id, outbox);
1624 let holding = core.holding_updates();
1625 let Some(entry) = core.maps.get_mut(&id) else { return };
1626 after(entry, value, entry.applied(), outbox);
1627 if holding {
1628 entry.held_applied = Some(sequence);
1629 } else {
1630 report_applied(entry, sequence);
1631 }
1632}
1633
1634fn report_applied(entry: &MapEntry, sequence: u64) {
1637 entry.published.applied.store(sequence, Ordering::SeqCst);
1638 if let Some(link) = &entry.session
1639 && sequence >= link.awaited.load(Ordering::SeqCst)
1640 {
1641 worker_post(&link.queue, move |worker, outbox| worker.map_applied(sequence, outbox));
1642 }
1643}
1644
1645fn report_sampled(entry: &MapEntry, sample: u64) {
1648 entry.published.sampled.fetch_max(sample, Ordering::SeqCst);
1649 if let Some(link) = &entry.session {
1650 worker_post(&link.queue, move |worker, outbox| worker.map_sampled(sample, outbox));
1651 }
1652}
1653
1654pub(crate) fn report_held(entry: &mut MapEntry) {
1657 if let Some(sequence) = entry.held_applied.take() {
1658 report_applied(entry, sequence);
1659 }
1660 if let Some(sample) = entry.held_sampled.take() {
1661 report_sampled(entry, sample);
1662 }
1663}
1664
1665fn sample_frame(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1668 let Some(entry) = core.maps.get(&id) else { return };
1669 entry.published.sample_queued.store(false, Ordering::SeqCst);
1671 let sample = entry.published.samples_requested.load(Ordering::SeqCst);
1672 if entry.flush_pending.is_set() || entry.core.has_reports() {
1673 flush(core, id, outbox);
1674 }
1675 let Some(entry) = core.maps.get_mut(&id) else { return };
1676 entry.core.sample_frame();
1677 flush(core, id, outbox);
1678 let holding = core.holding_updates();
1679 let Some(entry) = core.maps.get_mut(&id) else { return };
1680 if holding {
1681 entry.held_sampled = Some(sample);
1682 } else {
1683 report_sampled(entry, sample);
1684 }
1685}
1686
1687pub(crate) fn run_command<T, R: 'static>(
1690 core: &mut RuntimeCore,
1691 id: MapId,
1692 sequence: u64,
1693 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error>,
1694 finish: impl FnOnce(T, &MapEntry) -> R,
1695 resolver: Resolver<R>,
1696 outbox: &mut Outbox,
1697) {
1698 if !core.maps.contains_key(&id) {
1699 return outbox.resolve(resolver, Err(missing_map()));
1700 }
1701 apply_command(core, id, sequence, outbox, apply, move |entry, result, _, outbox| {
1702 outbox.resolve(resolver, result.map(|value| finish(value, entry)));
1703 });
1704}
1705
1706fn load_style(
1709 core: &mut RuntimeCore,
1710 id: MapId,
1711 sequence: u64,
1712 load: StyleLoad,
1713 resolver: Resolver<Applied>,
1714 outbox: &mut Outbox,
1715) {
1716 if !core.maps.contains_key(&id) {
1717 return outbox.resolve(resolver, Err(missing_map()));
1718 }
1719 apply_command(
1722 core,
1723 id,
1724 sequence,
1725 outbox,
1726 move |entry, outbox| {
1727 let from_json = matches!(load, StyleLoad::Json(_));
1728 if let Some(previous) = entry.pending_style.replace(PendingStyle { resolver, from_json }) {
1729 outbox.resolve(previous.resolver, Err(Error::cancelled("another style load started")));
1730 }
1731 match load {
1732 StyleLoad::Url(url) => entry.core.load_style_url(&url),
1733 StyleLoad::Json(json) => entry.core.load_style_json(&json),
1734 }
1735 },
1736 |_, (), _, _| {},
1737 );
1738}
1739
1740pub(crate) fn flush(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1745 let Some(entry) = core.maps.get_mut(&id) else { return };
1746 entry.flush_pending.clear();
1749 let events = entry.core.drain_events();
1750 crate::style::reconcile(entry, outbox);
1753 let generation = entry.core.generation();
1754 let ends: Vec<_> = entry
1756 .core
1757 .drain_command_ends()
1758 .filter_map(|end| Some((entry.camera_commands.remove(&end.command)?, TransitionEnd { generation, ..end.end })))
1759 .collect();
1760 let mut published = entry.published.snapshot.lock();
1763 if published.is_none_or(|snapshot| snapshot.generation != generation) {
1764 *published = Some(entry.core.snapshot());
1765 }
1766 drop(published);
1767
1768 let mut style_outcome = None;
1769 let from_json = entry.pending_style.as_ref().is_some_and(|pending| pending.from_json);
1770 for event in &events {
1771 match event {
1772 MapEvent::StyleLoaded => style_outcome = Some(Ok(())),
1773 MapEvent::LoadingFailed(StyleLoadError::Parse(message)) if from_json => {
1774 style_outcome = Some(Err(Error::invalid_argument(message)));
1775 }
1776 MapEvent::LoadingFailed(error) => style_outcome = Some(Err(Error::native(error.message()))),
1777 _ => {}
1778 }
1779 }
1780 let style_outcome = style_outcome.map(|outcome| (outcome, entry.pending_style.take(), entry.applied()));
1781 let still_outcome = match &mut entry.pending_still {
1782 Some(pending) => pending
1783 .refused
1784 .take()
1785 .or_else(|| entry.core.take_still_image().map(|result| result.map_err(still_image_error))),
1786 None => None,
1787 };
1788 let still = still_outcome.and_then(|outcome| Some((outcome, entry.pending_still.take()?.resolver)));
1789 let still_image = entry.pending_still.as_ref().and(entry.core.pending_still_image()).unwrap_or(0);
1792 if entry.published.still_image.swap(still_image, Ordering::SeqCst) != still_image
1793 && let Some(link) = &entry.session
1794 {
1795 worker_post(&link.queue, Worker::still_image_changed);
1796 }
1797
1798 let mask = entry.mask;
1799 let events: Vec<RuntimeEvent> = events
1800 .into_iter()
1801 .map(RuntimeEventKind::Map)
1802 .filter(|kind| mask.contains(kind.event_type()))
1803 .map(|kind| RuntimeEvent { source: EventSource::Map { id, generation }, kind })
1804 .collect();
1805 core.send_events(events, outbox);
1806 for (resolver, end) in ends {
1807 outbox.resolve(resolver, Ok(end));
1808 }
1809
1810 if let Some((outcome, Some(pending), applied)) = style_outcome {
1811 outbox.resolve(pending.resolver, outcome.map(|()| applied));
1812 }
1813 if let Some((outcome, resolver)) = still {
1814 outbox.resolve(resolver, outcome);
1815 }
1816}
1817
1818fn remove(core: &mut RuntimeCore, id: MapId, done: Option<Resolver<()>>, outbox: &mut Outbox) {
1820 flush(core, id, outbox);
1821 if let Some(mut entry) = core.maps.remove(&id) {
1822 entry.core.set_waker(None);
1823 if let Some(pending) = entry.pending_style.take() {
1824 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1825 }
1826 if let Some(pending) = entry.pending_still.take() {
1827 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1828 }
1829 crate::style::release(&mut entry, outbox);
1830 entry.core.close_camera();
1833 for end in entry.core.drain_command_ends() {
1834 if let Some(resolver) = entry.camera_commands.remove(&end.command) {
1835 outbox.resolve(resolver, Ok(end.end));
1836 }
1837 }
1838 }
1839 if let Some(done) = done {
1840 outbox.resolve(done, Ok(()));
1841 }
1842}