1use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::{Arc, OnceLock, Weak};
5
6use mln_map::{
7 BoundOptions, Camera, CameraCommandId, CameraDelta, CameraOptions, CameraUpdate, Elevation, FrameClock,
8 FreeCameraOptions, LogicalExtent, MapEvent, MapMode, MapProjection, MapSnapshot, MapView, ProjectionMode,
9 StyleLoadError, TransitionEnd, TransitionOutcome,
10};
11use mln_renderer::text::font_face_engine::FontFaceEngine;
12use mln_renderer::{Custom, CustomLayerHost, Registry, UpdateReader};
13use mln_style::Edit;
14use mln_text::GlyphCache;
15use mln_text::local_fonts::LocalGlyphs;
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::queue::TimedTask;
22use mln_util::size::Size;
23use mln_util::time::Instant;
24use parking_lot::Mutex;
25
26use crate::camera::{self, CameraFitArea, CameraFitOptions, CameraFitUpdate, TileOptions, ViewportOptions};
27use crate::completion::{Completion, Resolver};
28use crate::event::{EventMask, EventSource, RuntimeEvent, RuntimeEventKind};
29use crate::feature_state::{FeatureState, FeatureStateSelector};
30use crate::render::{
31 Abandoner, AttachOptions, RenderSession, RenderTarget, SessionId, SessionQueue, SessionShared, Worker, worker_post,
32};
33use crate::runtime::{CoreQueue, Outbox, Runtime, RuntimeCore, RuntimeShared, post, post_at};
34use crate::style::{CallbackSources, GeoJsonUpdates};
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub struct MapId(pub u64);
39
40#[derive(Clone, Debug)]
42pub struct MapOptions {
43 pub map: mln_map::MapOptions,
44 pub event_mask: EventMask,
46 pub fallback_font_faces: Option<String>,
52 pub system_fonts: bool,
64 pub local_ideographs: bool,
69 pub tile_cache_enabled: bool,
72}
73
74impl Default for MapOptions {
75 fn default() -> Self {
76 MapOptions {
77 map: mln_map::MapOptions::default(),
78 event_mask: EventMask::default(),
79 fallback_font_faces: None,
80 system_fonts: true,
81 local_ideographs: true,
82 tile_cache_enabled: true,
83 }
84 }
85}
86
87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub struct Applied {
90 pub sequence: u64,
93 pub generation: u64,
96 pub render_update_generation: u64,
99}
100
101fn fit(map: &mut mln_map::Map, area: &CameraFitArea, update: CameraFitUpdate) -> Result<CameraCommandId, Error> {
103 let CameraFitUpdate { mode, fit, animation } = update;
104 let camera = camera::camera_for(map, area, &fit)?;
105 Ok(map.update_camera(&CameraUpdate { mode, camera, animation, ..CameraUpdate::default() }))
106}
107
108#[derive(Clone, Copy, Debug, PartialEq)]
110pub struct CameraQuery {
111 pub generation: u64,
112 pub camera: Camera,
113}
114
115pub(crate) struct Published {
117 state: Mutex<Option<PublishedState>>,
121 updates: OnceLock<UpdateReader>,
123 applied: AtomicU64,
126 frame_clock: OnceLock<FrameClock>,
129 samples_requested: AtomicU64,
132 sampled: AtomicU64,
133 sample_queued: AtomicBool,
136 event_mask: AtomicU64,
137 still_image: AtomicU64,
140}
141
142struct PublishedState {
144 snapshot: MapSnapshot,
145 ground: Option<Arc<dyn Elevation>>,
147}
148
149impl Published {
150 pub(crate) fn applied(&self) -> u64 {
153 self.applied.load(Ordering::SeqCst)
154 }
155
156 pub(crate) fn sampled(&self) -> u64 {
158 self.sampled.load(Ordering::SeqCst)
159 }
160
161 pub(crate) fn animating(&self) -> bool {
164 self.state.lock().as_ref().is_some_and(|state| state.snapshot.transition_in_progress)
165 }
166
167 pub(crate) fn pending_still_image(&self) -> u64 {
171 self.still_image.load(Ordering::SeqCst)
172 }
173
174 pub(crate) fn new(event_mask: EventMask) -> Self {
175 Published {
176 state: Mutex::new(None),
177 updates: OnceLock::new(),
178 applied: AtomicU64::new(0),
179 frame_clock: OnceLock::new(),
180 samples_requested: AtomicU64::new(0),
181 sampled: AtomicU64::new(0),
182 sample_queued: AtomicBool::new(false),
183 event_mask: AtomicU64::new(event_mask.bits()),
184 still_image: AtomicU64::new(0),
185 }
186 }
187}
188
189pub(crate) struct MapShared {
190 id: MapId,
191 runtime: Arc<RuntimeShared>,
192 mode: MapMode,
193 scale_factor: AtomicU64,
196 tile_cache_enabled: bool,
197 system_fonts: bool,
198 local_ideographs: bool,
199 session: Mutex<Option<SessionClaim>>,
202 sent: Mutex<u64>,
206 released: AtomicBool,
208 removed: AtomicBool,
210 published: Arc<Published>,
211}
212
213impl MapShared {
214 pub(crate) fn new(id: MapId, runtime: Arc<RuntimeShared>, options: &MapOptions, published: Arc<Published>) -> Self {
215 MapShared {
216 id,
217 runtime,
218 mode: options.map.map_mode,
219 scale_factor: AtomicU64::new(f64::from(options.map.pixel_ratio).to_bits()),
220 tile_cache_enabled: options.tile_cache_enabled,
221 system_fonts: options.system_fonts,
222 local_ideographs: options.local_ideographs,
223 session: Mutex::new(None),
224 sent: Mutex::new(1),
225 released: AtomicBool::new(false),
226 removed: AtomicBool::new(false),
227 published,
228 }
229 }
230
231 fn completion<R: Send + 'static>(&self, discard: Option<fn(Error)>) -> (Completion<R>, Resolver<R>) {
235 match discard {
236 Some(on_failure) => Completion::discarded(on_failure),
237 None => self.runtime.completion(),
238 }
239 }
240
241 pub(crate) fn send<R: Send + 'static>(
243 &self,
244 discard: Option<fn(Error)>,
245 command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
246 ) -> Result<Completion<R>, Error> {
247 let mut sent = self.sent.lock();
248 if self.released.load(Ordering::SeqCst) {
249 return Err(released());
250 }
251 self.runtime.check_running()?;
252 let (completion, resolver) = self.completion(discard);
253 let id = self.id;
254 *sent += 1;
255 let sequence = *sent;
256 self.runtime.post(move |core, outbox| command(core, outbox, id, sequence, resolver));
257 Ok(completion)
258 }
259
260 fn release(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
263 self.close()?;
264 self.remove(done);
265 Ok(())
266 }
267
268 fn close(&self) -> Result<(), Error> {
271 let _sent = self.sent.lock();
272 if self.released.swap(true, Ordering::SeqCst) {
273 return Err(released());
274 }
275 Ok(())
276 }
277
278 fn remove(&self, done: Option<Resolver<()>>) {
281 if self.removed.swap(true, Ordering::SeqCst) {
282 return;
283 }
284 let id = self.id;
285 self.runtime.post_or_stopped(
287 done,
288 move |core, outbox, done| remove(core, id, done, outbox),
289 |done| {
290 if let Some(done) = done {
291 done.resolve(Ok(()));
292 }
293 },
294 );
295 self.runtime.map_released();
296 }
297}
298
299impl Drop for MapShared {
300 fn drop(&mut self) {
301 let _ = self.close();
302 let deferred = self.session.get_mut().take().and_then(|claim| claim.removal);
303 self.remove(deferred);
304 }
305}
306
307#[derive(Clone)]
320pub struct Map {
321 pub(crate) shared: Arc<MapShared>,
322 discard: Option<fn(Error)>,
325}
326
327impl std::fmt::Debug for Map {
328 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
329 f.debug_struct("Map").field("id", &self.shared.id).field("discards_results", &self.discard.is_some()).finish()
330 }
331}
332
333impl PartialEq for Map {
334 fn eq(&self, other: &Map) -> bool {
335 Arc::ptr_eq(&self.shared, &other.shared)
336 }
337}
338
339impl Eq for Map {}
340
341fn released() -> Error {
342 Error::invalid_state("the map was released")
343}
344
345pub(crate) fn style_not_loaded() -> Error {
346 Error::invalid_state("style is not loaded")
347}
348
349pub(crate) fn missing_map() -> Error {
352 Error::invalid_state("the map failed to be built or was released")
353}
354
355type Reply<T> = Box<dyn FnOnce(&mut Worker, Result<T, Error>, &mut Outbox) + Send>;
357
358struct SessionReply<T: Send + 'static> {
363 queue: SessionQueue,
364 reply: Option<Reply<T>>,
365}
366
367impl<T: Send + 'static> SessionReply<T> {
368 fn new(
369 queue: SessionQueue,
370 reply: impl FnOnce(&mut Worker, Result<T, Error>, &mut Outbox) + Send + 'static,
371 ) -> Self {
372 SessionReply { queue, reply: Some(Box::new(reply)) }
373 }
374
375 fn send(mut self, result: Result<T, Error>) {
376 if let Some(reply) = self.reply.take() {
377 worker_post(&self.queue, move |worker, outbox| reply(worker, result, outbox));
378 }
379 }
380}
381
382impl<T: Send + 'static> Drop for SessionReply<T> {
383 fn drop(&mut self) {
384 if let Some(reply) = self.reply.take() {
385 let error = Error::cancelled("the runtime stopped before the command ran");
386 worker_post(&self.queue, move |worker, outbox| reply(worker, Err(error), outbox));
387 }
388 }
389}
390
391impl Map {
392 pub(crate) fn new(shared: MapShared) -> Self {
393 Map { shared: Arc::new(shared), discard: None }
394 }
395
396 #[must_use]
401 pub fn discarding_results(&self, on_failure: fn(Error)) -> Map {
402 Map { shared: Arc::clone(&self.shared), discard: Some(on_failure) }
403 }
404
405 pub(crate) fn post<R: Send + 'static>(
408 &self,
409 command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
410 ) -> Result<Completion<R>, Error> {
411 self.shared.send(self.discard, command)
412 }
413
414 #[must_use]
415 pub fn id(&self) -> MapId {
416 self.shared.id
417 }
418
419 #[must_use]
421 pub fn mode(&self) -> MapMode {
422 self.shared.mode
423 }
424
425 #[must_use]
427 pub fn runtime(&self) -> Runtime {
428 Runtime { shared: Arc::clone(&self.shared.runtime) }
429 }
430
431 #[must_use]
433 pub fn sent_sequence(&self) -> u64 {
434 *self.shared.sent.lock()
435 }
436
437 #[must_use]
441 pub fn applied_sequence(&self) -> u64 {
442 self.shared.published.applied.load(Ordering::SeqCst)
443 }
444
445 pub fn snapshot(&self) -> Result<MapSnapshot, Error> {
455 let mut snapshot = self.published(|state| state.snapshot)?;
456 if let Some(updates) = self.shared.published.updates.get() {
460 snapshot.update_generation = updates.generation();
461 }
462 Ok(snapshot)
463 }
464
465 pub fn projection(&self, view: Option<&MapView>) -> Result<MapProjection, Error> {
474 let (snapshot_view, ground) = self.published(|state| (state.snapshot.view, state.ground.clone()))?;
475 Ok(MapProjection::from_view(view.unwrap_or(&snapshot_view))?.with_ground(ground))
476 }
477
478 fn published<T>(&self, read: impl FnOnce(&PublishedState) -> T) -> Result<T, Error> {
482 if self.shared.released.load(Ordering::SeqCst) {
483 return Err(released());
484 }
485 self.shared.published.state.lock().as_ref().map(read).ok_or_else(|| Error::invalid_state("the map isn't built"))
486 }
487
488 #[must_use]
490 pub fn event_mask(&self) -> EventMask {
491 EventMask::from_bits(self.shared.published.event_mask.load(Ordering::SeqCst)).unwrap_or_default()
492 }
493
494 pub(crate) fn send<T: 'static, R: Send + 'static>(
497 &self,
498 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error> + Send + 'static,
499 finish: impl FnOnce(T, &MapEntry) -> R + Send + 'static,
500 ) -> Result<Completion<R>, Error> {
501 self.post(move |core, outbox, id, sequence, resolver| {
502 run_command(core, id, sequence, apply, finish, resolver, outbox);
503 })
504 }
505
506 pub(crate) fn command(
508 &self,
509 apply: impl FnOnce(&mut mln_map::Map) -> Result<(), Error> + Send + 'static,
510 ) -> Result<Completion<Applied>, Error> {
511 self.send(move |entry, _| apply(&mut entry.core), |(), entry| entry.applied())
512 }
513
514 pub(crate) fn query<T: Send + 'static>(
516 &self,
517 read: impl FnOnce(&mut mln_map::Map) -> Result<T, Error> + Send + 'static,
518 ) -> Result<Completion<T>, Error> {
519 self.send(move |entry, _| read(&mut entry.core), |value, _| value)
520 }
521
522 pub fn with_core<R: Send + 'static>(
527 &self,
528 f: impl FnOnce(&mut mln_map::Map) -> R + Send + 'static,
529 ) -> Result<Completion<R>, Error> {
530 self.query(move |map| Ok(f(map)))
531 }
532
533 pub fn release(&self) -> Result<Completion<()>, Error> {
544 self.release_with(false)
545 }
546
547 pub fn dispose(&self) -> Result<Completion<()>, Error> {
559 self.release_with(true)
560 }
561
562 fn release_with(&self, in_any_state: bool) -> Result<Completion<()>, Error> {
563 let (completion, resolver) = self.shared.completion(self.discard);
564 let claimed = {
565 let mut claim = self.shared.session.lock();
566 match claim.as_mut() {
567 None => None,
568 Some(held) => match held.session.upgrade() {
569 Some(session) if session.is_released() => Some((held.id, Some(session))),
571 Some(_) if in_any_state => {
574 self.shared.close()?;
575 held.removal = Some(resolver);
576 return Ok(completion);
577 }
578 Some(_) => return Err(Error::invalid_state("map still has an attached render session")),
579 None => Some((held.id, None)),
581 },
582 }
583 };
584 if let Some((id, session)) = claimed {
585 if let Some(session) = session {
586 let _ = session.abandon(Abandoner::Library);
587 }
588 self.release_session_claim(id);
589 }
590 self.shared.release(Some(resolver))?;
591 Ok(completion)
592 }
593
594 pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
604 let LogicalExtent { size, scale_factor } = extent;
605 if self.shared.session.lock().is_some() {
606 return Err(Error::invalid_state("the map has a render session: resize the session instead"));
607 }
608 if size.is_empty() {
609 return Err(Error::invalid_argument("logical size dimensions must be positive"));
610 }
611 if !scale_factor.is_finite() || scale_factor <= 0.0 {
612 return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
613 }
614 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
616 self.command(move |map| {
617 if map.snapshot().view.extent.size != size {
618 map.set_size(size)?;
619 }
620 map.set_pixel_ratio(scale_factor as f32)
621 })
622 }
623
624 pub fn request_repaint(&self) -> Result<Completion<Applied>, Error> {
628 if self.shared.mode != MapMode::Continuous {
629 return Err(Error::invalid_state("map is not in continuous mode"));
630 }
631 self.command(|map| {
632 map.trigger_repaint();
633 Ok(())
634 })
635 }
636
637 pub fn begin_command_group(&self) -> Result<Completion<Applied>, Error> {
642 self.command(|map| {
643 map.begin_command_group();
644 Ok(())
645 })
646 }
647
648 pub fn end_command_group(&self) -> Result<Completion<Applied>, Error> {
652 self.command(mln_map::Map::end_command_group)
653 }
654
655 pub fn command_group(&self) -> Result<CommandGroup, Error> {
658 drop(self.begin_command_group()?);
659 Ok(CommandGroup { map: Some(self.clone()) })
660 }
661
662 pub fn set_event_mask(&self, mask: EventMask) -> Result<Completion<Applied>, Error> {
664 self.send(
665 move |entry, _| {
666 if entry.mask != mask {
667 entry.mask = mask;
668 entry.published.event_mask.store(mask.bits(), Ordering::SeqCst);
669 entry.core.record_change();
670 }
671 Ok(())
672 },
673 |(), entry| entry.applied(),
674 )
675 }
676
677 pub fn attach(
704 &self,
705 target: RenderTarget,
706 options: AttachOptions,
707 ) -> Result<(RenderSession, Completion<()>), Error> {
708 crate::render::attach(self, target, options, |session, attached| (session.clone(), attached))
709 }
710
711 pub fn attach_then<R>(
723 &self,
724 target: RenderTarget,
725 options: AttachOptions,
726 then: impl FnOnce(&RenderSession, Completion<()>) -> R,
727 ) -> Result<R, Error> {
728 crate::render::attach(self, target, options, then)
729 }
730
731 pub fn request_still_image(&self) -> Result<Completion<()>, Error> {
756 if self.shared.mode == MapMode::Continuous {
757 return Err(Error::invalid_state("the map is not in static or tile mode"));
758 }
759 self.post(move |core, outbox, id, sequence, resolver| {
760 if !core.maps.contains_key(&id) {
761 return outbox.resolve(resolver, Err(missing_map()));
762 }
763 apply_command(
764 core,
765 id,
766 sequence,
767 outbox,
768 move |entry, outbox| {
769 if entry.pending_still.is_some() {
770 let error = Error::invalid_state("the map is rendering a still image already");
771 return outbox.resolve(resolver, Err(error));
772 }
773 if entry.core.command_group_depth() > 0 {
775 let error = Error::invalid_state("a still image can't render while a command group is open");
776 return outbox.resolve(resolver, Err(error));
777 }
778 let refused = entry.core.render_still().err().map(|error| Err(still_image_error(error)));
779 entry.pending_still = Some(PendingStill { resolver, refused });
780 },
781 |_, (), _, _| {},
782 );
783 })
784 }
785
786 pub(crate) fn is_released(&self) -> bool {
788 self.shared.released.load(Ordering::SeqCst)
789 }
790
791 pub(crate) fn runtime_thread(&self) -> std::thread::ThreadId {
792 self.shared.runtime.thread()
793 }
794
795 #[must_use]
800 pub fn scale_factor(&self) -> f64 {
801 f64::from_bits(self.shared.scale_factor.load(Ordering::SeqCst))
802 }
803
804 pub(crate) fn tile_cache_enabled(&self) -> bool {
805 self.shared.tile_cache_enabled
806 }
807
808 pub(crate) fn local_glyphs(&self) -> LocalGlyphs {
814 let mut local = LocalGlyphs { ideographs: self.shared.local_ideographs, ..LocalGlyphs::default() };
815 if self.shared.system_fonts {
816 #[cfg(not(target_family = "wasm"))]
817 {
818 local.chooser = Some(Arc::new(mln_system_fonts::SystemFonts));
819 }
820 #[cfg(target_family = "wasm")]
821 {
822 let font_family = "sans-serif".to_owned();
823 local.rasterizer =
824 Some(Arc::new(mln_text::browser_glyph_rasterizer::BrowserGlyphRasterizer::new(font_family)));
825 }
826 }
827 local
828 }
829
830 pub(crate) fn glyph_cache(&self) -> Arc<GlyphCache> {
831 Arc::clone(&self.shared.runtime.glyph_cache)
832 }
833
834 pub(crate) fn pool(&self) -> Pool {
836 self.shared.runtime.pool.clone()
837 }
838
839 pub(crate) fn font_face_engine(&self) -> Arc<dyn FontFaceEngine> {
841 Arc::clone(&self.shared.runtime.font_face_engine)
842 }
843
844 #[must_use]
849 pub fn registry(&self) -> &Arc<Registry> {
850 &self.shared.runtime.registry
851 }
852
853 pub(crate) fn claim_session(&self, id: SessionId, session: Weak<SessionShared>) -> Result<(), Error> {
855 let mut claim = self.shared.session.lock();
856 if self.shared.released.load(Ordering::SeqCst) {
857 return Err(released());
858 }
859 if claim.is_some() {
860 return Err(Error::invalid_state("the map already has an attached render session"));
861 }
862 *claim = Some(SessionClaim { id, session, removal: None });
863 Ok(())
864 }
865
866 pub(crate) fn release_session_claim(&self, id: SessionId) {
869 let claim = {
870 let mut session = self.shared.session.lock();
871 if session.as_ref().is_some_and(|claim| claim.id == id) { session.take() } else { None }
872 };
873 if let Some(removal) = claim.and_then(|claim| claim.removal) {
874 self.shared.remove(Some(removal));
875 }
876 }
877
878 pub(crate) fn bind_session(
883 &self,
884 id: SessionId,
885 queue: SessionQueue,
886 awaited: Arc<AtomicU64>,
887 size: Size,
888 ) -> Result<(), Error> {
889 let reply = SessionReply::new(queue.clone(), |worker, bound, outbox| match bound {
890 Ok((sequence, reader, events, published)) => worker.bound(sequence, reader, events, published, outbox),
891 Err(error) => worker.bind_failed(error, outbox),
892 });
893 let sent = self.shared.send(Some(drop), move |core, outbox, map_id, sequence, resolver: Resolver<()>| {
894 drop(resolver);
895 if !core.maps.contains_key(&map_id) {
896 return reply.send(Err(missing_map()));
897 }
898 let link = SessionLink { id, queue, awaited };
899 apply_command(
900 core,
901 map_id,
902 sequence,
903 outbox,
904 move |entry, _| {
905 entry.session = Some(link);
906 let resized = entry.core.set_size(size);
907 (resized, entry.core.update_reader(), entry.core.renderer_events(), Arc::clone(&entry.published))
908 },
909 move |_, (resized, reader, events, published), _, _| {
910 reply.send(resized.map(|()| (sequence, reader, events, published)));
911 },
912 );
913 });
914 sent.map(drop)
915 }
916
917 pub(crate) fn unbind_session(&self, id: SessionId) {
920 let map_id = self.shared.id;
921 self.shared.runtime.post_or((), move |core, _, ()| unbind(core, map_id, id), |()| {});
923 }
924
925 pub(crate) fn unbind_session_then(
928 &self,
929 id: SessionId,
930 queue: SessionQueue,
931 then: impl FnOnce(&mut Worker, &mut Outbox) + Send + 'static,
932 ) {
933 let map_id = self.shared.id;
934 let reply = SessionReply::new(queue, move |worker, _: Result<(), Error>, outbox| then(worker, outbox));
935 self.shared.runtime.post_or(
938 reply,
939 move |core, _, reply| {
940 unbind(core, map_id, id);
941 reply.send(Ok(()));
942 },
943 drop,
944 );
945 }
946
947 pub(crate) fn frame_demanded(&self) -> u64 {
953 let published = &self.shared.published;
954 if let Some(clock) = published.frame_clock.get() {
955 clock.set(Some(Instant::now()));
956 }
957 if self.shared.mode != MapMode::Continuous || !published.animating() {
960 return 0;
961 }
962 let sample = published.samples_requested.fetch_add(1, Ordering::SeqCst) + 1;
963 if !published.sample_queued.swap(true, Ordering::SeqCst) {
964 let id = self.shared.id;
965 self.shared.runtime.post_apart(move |core, outbox| sample_frame(core, id, outbox));
966 }
967 sample
968 }
969
970 pub(crate) fn resize_for_session(
974 &self,
975 size: Size,
976 scale_factor: f64,
977 queue: SessionQueue,
978 resize: impl FnOnce(&mut Worker, Result<Applied, Error>, &mut Outbox) + Send + 'static,
979 ) -> Result<(), Error> {
980 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
982 let reply = SessionReply::new(queue, resize);
983 let sent = self.shared.send(Some(drop), move |core, outbox, id, sequence, resolver: Resolver<()>| {
984 drop(resolver);
985 if !core.maps.contains_key(&id) {
986 return reply.send(Err(missing_map()));
987 }
988 apply_command(
989 core,
990 id,
991 sequence,
992 outbox,
993 move |entry, _| {
994 let pixel_ratio = scale_factor as f32;
998 let extent = entry.core.snapshot().view.extent;
999 if extent.size == size && extent.scale_factor == f64::from(pixel_ratio) {
1000 return Ok(());
1001 }
1002 entry.core.set_size(size)?;
1003 entry.core.set_pixel_ratio(pixel_ratio)
1004 },
1005 move |_, resized, applied, _| reply.send(resized.map(|()| applied)),
1006 );
1007 });
1008 sent.map(drop)
1009 }
1010
1011 pub fn set_feature_state(
1032 &self,
1033 selector: &FeatureStateSelector,
1034 state: FeatureState,
1035 ) -> Result<Completion<Applied>, Error> {
1036 let key = selector.key(true)?;
1037 self.command(move |map| {
1038 let feature_id = key.feature_id.as_deref().unwrap_or_default();
1039 map.set_feature_state(&key.source_id, Some(&key.source_layer_id), feature_id, state);
1040 Ok(())
1041 })
1042 }
1043
1044 pub fn feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<FeatureState>, Error> {
1048 let key = selector.key(true)?;
1049 self.query(move |map| {
1050 let feature_id = key.feature_id.as_deref().unwrap_or_default();
1051 Ok(map.feature_state(&key.source_id, Some(&key.source_layer_id), feature_id))
1052 })
1053 }
1054
1055 pub fn remove_feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<Applied>, Error> {
1063 let key = selector.key(false)?;
1064 self.command(move |map| {
1065 map.remove_feature_state(
1066 &key.source_id,
1067 Some(&key.source_layer_id),
1068 key.feature_id.as_deref(),
1069 key.state_key.as_deref(),
1070 );
1071 Ok(())
1072 })
1073 }
1074
1075 pub fn set_style_url(&self, url: impl Into<String>) -> Result<Completion<Applied>, Error> {
1087 let url = url.into();
1088 if url.is_empty() {
1089 return Err(Error::invalid_argument("style URL must not be empty"));
1090 }
1091 self.load_style(StyleLoad::Url(url))
1092 }
1093
1094 pub fn set_style_json(&self, json: impl Into<String>) -> Result<Completion<Applied>, Error> {
1100 let json = json.into();
1101 if json.is_empty() {
1102 return Err(Error::invalid_argument("style JSON must not be empty"));
1103 }
1104 self.load_style(StyleLoad::Json(json))
1105 }
1106
1107 fn load_style(&self, load: StyleLoad) -> Result<Completion<Applied>, Error> {
1108 self.post(move |core, outbox, id, sequence, resolver| {
1109 load_style(core, id, sequence, load, resolver, outbox);
1110 })
1111 }
1112
1113 pub fn loaded_style_json(&self) -> Result<Completion<String>, Error> {
1116 self.query(|map| Ok(map.style().get_json().to_owned()))
1117 }
1118
1119 pub fn style_url(&self) -> Result<Completion<Option<String>>, Error> {
1121 self.query(|map| Ok(map.style_url().filter(|url| !url.is_empty()).map(str::to_owned)))
1122 }
1123
1124 pub fn add_style_source_json(
1127 &self,
1128 source_id: impl Into<String>,
1129 json: impl Into<String>,
1130 ) -> Result<Completion<Applied>, Error> {
1131 let (source_id, json) = (source_id.into(), json.into());
1132 self.command(move |map| map.add_source_json(&source_id, &json))
1133 }
1134
1135 pub fn remove_style_source(&self, source_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1142 let source_id = source_id.into();
1143 self.send(
1144 move |entry, _| {
1145 let map = &mut entry.core;
1146 if !map.style_document_loaded() {
1147 return Err(style_not_loaded());
1148 }
1149 if map.source(&source_id).is_none() {
1150 return Err(Error::not_found(format!("source \"{source_id}\" does not exist")));
1151 }
1152 if let Some(layer) = map.style().get_layers().find(|layer| layer.get_source_id() == source_id) {
1153 let message = format!("source \"{source_id}\" is used by layer \"{}\"", layer.get_id());
1154 return Err(Error::invalid_state(message));
1155 }
1156 map.remove_source(&source_id);
1157 entry.core.remove_source_feature_state(&source_id);
1158 Ok(())
1159 },
1160 |(), entry| entry.applied(),
1161 )
1162 }
1163
1164 pub fn add_style_layer_json(
1167 &self,
1168 json: impl Into<String>,
1169 before_layer_id: Option<String>,
1170 ) -> Result<Completion<Applied>, Error> {
1171 let json = json.into();
1172 self.command(move |map| map.edit_loaded_style(|style| style.add_layer_json(&json, before_layer_id.as_deref())))
1173 }
1174
1175 pub fn add_custom_layer(
1180 &self,
1181 layer_id: impl Into<String>,
1182 host: Arc<dyn CustomLayerHost>,
1183 before_layer_id: Option<String>,
1184 ) -> Result<Completion<Applied>, Error> {
1185 let layer_id = layer_id.into();
1186 self.command(move |map| {
1187 map.edit_loaded_style(|style| {
1188 let layer = Custom::layer(style.registry(), &layer_id, host);
1189 style.add_layer(layer, before_layer_id.as_deref())
1190 })
1191 })
1192 }
1193
1194 pub fn remove_style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1199 let layer_id = layer_id.into();
1200 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::RemoveLayer(layer_id))))
1201 }
1202
1203 pub fn style_layer_json(&self, layer_id: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1206 let layer_id = layer_id.into();
1207 self.query(move |map| Ok(map.style().layer_json(&layer_id)))
1208 }
1209
1210 pub fn set_style_layer_property(
1213 &self,
1214 layer_id: impl Into<String>,
1215 name: impl Into<String>,
1216 json: impl Into<String>,
1217 ) -> Result<Completion<Applied>, Error> {
1218 let (layer_id, name, json) = (layer_id.into(), name.into(), json.into());
1219 self.command(move |map| map.edit_loaded_style(|style| style.set_layer_property_json(&layer_id, &name, &json)))
1220 }
1221
1222 pub fn style_layer_property(
1225 &self,
1226 layer_id: impl Into<String>,
1227 name: impl Into<String>,
1228 ) -> Result<Completion<Option<String>>, Error> {
1229 let (layer_id, name) = (layer_id.into(), name.into());
1230 self.query(move |map| map.style().layer_property_json(&layer_id, &name))
1231 }
1232
1233 pub fn set_style_root_property(
1237 &self,
1238 name: impl Into<String>,
1239 json: impl Into<String>,
1240 ) -> Result<Completion<Applied>, Error> {
1241 let (name, json) = (name.into(), json.into());
1242 self.command(move |map| map.edit_loaded_style(|style| style.set_root_property_json(&name, &json)))
1243 }
1244
1245 pub fn style_root_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1248 let name = name.into();
1249 self.query(move |map| map.style().root_property_json(&name))
1250 }
1251
1252 pub fn set_style_light_property(
1254 &self,
1255 name: impl Into<String>,
1256 json: impl Into<String>,
1257 ) -> Result<Completion<Applied>, Error> {
1258 let (name, json) = (name.into(), json.into());
1259 self.command(move |map| map.edit_loaded_style(|style| style.set_light_property_json(&name, &json)))
1260 }
1261
1262 pub fn style_light_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1265 let name = name.into();
1266 self.query(move |map| Ok(map.style().light_property_json(&name)))
1267 }
1268
1269 fn camera_command(
1274 &self,
1275 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1276 ) -> Result<Completion<Applied>, Error> {
1277 self.send_camera(apply, None)
1278 }
1279
1280 fn camera_command_then(
1285 &self,
1286 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1287 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1288 ) -> Result<Completion<Applied>, Error> {
1289 let (ended, end) = self.shared.runtime.completion();
1290 ended.on_complete(on_end);
1291 self.send_camera(apply, Some(end))
1292 }
1293
1294 fn send_camera(
1297 &self,
1298 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1299 end: Option<Resolver<TransitionEnd>>,
1300 ) -> Result<Completion<Applied>, Error> {
1301 self.send(
1302 move |entry, outbox| match (apply(&mut entry.core), end) {
1303 (Ok(command), Some(end)) => {
1304 entry.camera_commands.insert(command, end);
1305 Ok(())
1306 }
1307 (Ok(_), None) => Ok(()),
1308 (Err(error), end) => {
1309 if let Some(end) = end {
1310 let generation = entry.core.generation();
1311 let cancelled =
1312 TransitionEnd { outcome: TransitionOutcome::Cancelled, generation, ..Default::default() };
1313 outbox.resolve(end, Ok(cancelled));
1314 }
1315 Err(error)
1316 }
1317 },
1318 |(), entry| entry.applied(),
1319 )
1320 }
1321
1322 pub fn update_camera(&self, update: CameraUpdate) -> Result<Completion<Applied>, Error> {
1324 self.camera_command(move |map| Ok(map.update_camera(&update)))
1325 }
1326
1327 pub fn update_camera_then(
1337 &self,
1338 update: CameraUpdate,
1339 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1340 ) -> Result<Completion<Applied>, Error> {
1341 self.camera_command_then(move |map| Ok(map.update_camera(&update)), on_end)
1342 }
1343
1344 pub fn apply_camera_delta(&self, delta: CameraDelta) -> Result<Completion<Applied>, Error> {
1348 self.camera_command(move |map| {
1349 map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string()))
1350 })
1351 }
1352
1353 pub fn apply_camera_delta_then(
1357 &self,
1358 delta: CameraDelta,
1359 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1360 ) -> Result<Completion<Applied>, Error> {
1361 self.camera_command_then(
1362 move |map| map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string())),
1363 on_end,
1364 )
1365 }
1366
1367 pub fn camera_for(
1374 &self,
1375 area: CameraFitArea,
1376 options: CameraFitOptions,
1377 ) -> Result<Completion<CameraOptions>, Error> {
1378 self.query(move |map| camera::camera_for(map, &area, &options))
1379 }
1380
1381 pub fn fit_camera(&self, area: CameraFitArea, update: CameraFitUpdate) -> Result<Completion<Applied>, Error> {
1388 self.camera_command(move |map| fit(map, &area, update))
1389 }
1390
1391 pub fn fit_camera_then(
1395 &self,
1396 area: CameraFitArea,
1397 update: CameraFitUpdate,
1398 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1399 ) -> Result<Completion<Applied>, Error> {
1400 self.camera_command_then(move |map| fit(map, &area, update), on_end)
1401 }
1402
1403 pub fn cancel_camera_transitions(&self) -> Result<Completion<Applied>, Error> {
1405 self.command(|map| {
1406 map.cancel_transitions();
1407 Ok(())
1408 })
1409 }
1410
1411 pub fn cancel_camera_transitions_with_id(&self, transition_id: u64) -> Result<Completion<Applied>, Error> {
1413 self.command(move |map| {
1414 map.cancel_transitions_with_id(transition_id);
1415 Ok(())
1416 })
1417 }
1418
1419 pub fn camera(&self) -> Result<Completion<CameraQuery>, Error> {
1421 self.send(
1422 |_, _| Ok(()),
1423 |(), entry| CameraQuery { generation: entry.core.generation(), camera: entry.core.snapshot().view.camera },
1424 )
1425 }
1426
1427 pub fn lat_lng_bounds_for_camera(&self, camera: CameraOptions) -> Result<Completion<LatLngBounds>, Error> {
1432 self.query(move |map| map.lat_lng_bounds_for_camera_unwrapped(&camera))
1433 }
1434
1435 pub fn set_bounds(&self, bounds: BoundOptions) -> Result<Completion<Applied>, Error> {
1437 self.command(move |map| map.set_bounds(&bounds))
1438 }
1439
1440 pub fn set_free_camera_options(&self, camera: FreeCameraOptions) -> Result<Completion<Applied>, Error> {
1442 self.command(move |map| {
1443 map.set_free_camera_options(&camera);
1444 Ok(())
1445 })
1446 }
1447
1448 pub fn set_viewport_options(&self, options: ViewportOptions) -> Result<Completion<Applied>, Error> {
1450 self.command(move |map| {
1451 camera::set_viewport(map, &options);
1452 Ok(())
1453 })
1454 }
1455
1456 pub fn set_tile_options(&self, options: TileOptions) -> Result<Completion<Applied>, Error> {
1458 self.command(move |map| {
1459 camera::set_tile_options(map, &options);
1460 Ok(())
1461 })
1462 }
1463
1464 pub fn set_projection_mode(&self, mode: ProjectionMode) -> Result<Completion<Applied>, Error> {
1465 self.command(move |map| {
1466 map.set_projection_mode(&mode);
1467 Ok(())
1468 })
1469 }
1470
1471 pub fn dump_debug_logs(&self) -> Result<Completion<Applied>, Error> {
1473 self.command(|map| {
1474 map.dump_debug_logs();
1475 Ok(())
1476 })
1477 }
1478}
1479
1480#[must_use = "the group ends when it drops"]
1482pub struct CommandGroup {
1483 map: Option<Map>,
1484}
1485
1486impl CommandGroup {
1487 pub fn end(mut self) -> Result<Completion<Applied>, Error> {
1489 match self.map.take() {
1490 Some(map) => map.end_command_group(),
1491 None => Err(Error::invalid_state("the group ended already")),
1492 }
1493 }
1494}
1495
1496impl Drop for CommandGroup {
1497 fn drop(&mut self) {
1498 if let Some(map) = self.map.take() {
1499 let _ = map.end_command_group();
1500 }
1501 }
1502}
1503
1504enum StyleLoad {
1505 Url(String),
1506 Json(String),
1507}
1508
1509struct PendingStyle {
1511 resolver: Resolver<Applied>,
1512 from_json: bool,
1515}
1516
1517struct SessionClaim {
1519 id: SessionId,
1520 session: Weak<SessionShared>,
1521 removal: Option<Resolver<()>>,
1523}
1524
1525fn unbind(core: &mut RuntimeCore, map_id: MapId, id: SessionId) {
1528 if let Some(entry) = core.maps.get_mut(&map_id)
1529 && entry.session.as_ref().is_some_and(|link| link.id == id)
1530 {
1531 entry.session = None;
1532 }
1533}
1534
1535pub(crate) struct SessionLink {
1537 id: SessionId,
1538 queue: SessionQueue,
1539 awaited: Arc<AtomicU64>,
1541}
1542
1543struct PendingStill {
1546 resolver: Resolver<()>,
1547 refused: Option<Result<(), Error>>,
1550}
1551
1552fn still_image_error(error: Error) -> Error {
1555 match error.kind {
1556 ErrorKind::InvalidState => error,
1557 _ => Error::native(error.message),
1558 }
1559}
1560
1561pub(crate) struct MapEntry {
1563 pub(crate) core: mln_map::Map,
1564 published: Arc<Published>,
1565 mask: EventMask,
1566 applied: u64,
1568 held_applied: Option<u64>,
1571 held_sampled: Option<u64>,
1572 pending_style: Option<PendingStyle>,
1574 pending_still: Option<PendingStill>,
1575 session: Option<SessionLink>,
1577 flush_pending: FlushFlag,
1579 camera_commands: HashMap<CameraCommandId, Resolver<TransitionEnd>>,
1581 pub(crate) callback_sources: CallbackSources,
1583 pub(crate) geojson_updates: GeoJsonUpdates,
1585 repaint: Option<(Instant, TimedTask)>,
1588}
1589
1590impl MapEntry {
1591 pub(crate) fn applied(&self) -> Applied {
1592 Applied {
1593 sequence: self.applied,
1594 generation: self.core.generation(),
1595 render_update_generation: self.core.pending_update_generation(),
1596 }
1597 }
1598}
1599
1600#[derive(Clone, Default)]
1604struct FlushFlag(Arc<AtomicBool>);
1605
1606impl FlushFlag {
1607 fn waker(&self, queue: &CoreQueue, id: MapId) -> Waker {
1611 let (flag, queue) = (self.clone(), queue.downgrade());
1612 Arc::new(move || {
1613 if !flag.0.swap(true, Ordering::SeqCst)
1614 && let Some(queue) = queue.upgrade()
1615 {
1616 let flag = flag.clone();
1617 post(&queue, move |core, outbox| {
1618 if flag.is_set() {
1619 flush(core, id, outbox);
1620 }
1621 });
1622 }
1623 })
1624 }
1625
1626 fn is_set(&self) -> bool {
1627 self.0.load(Ordering::SeqCst)
1628 }
1629
1630 fn clear(&self) {
1631 self.0.store(false, Ordering::SeqCst);
1632 }
1633}
1634
1635pub(crate) fn create(
1637 core: &mut RuntimeCore,
1638 id: MapId,
1639 options: &MapOptions,
1640 published: Arc<Published>,
1641 resolver: Resolver<Applied>,
1642 outbox: &mut Outbox,
1643) {
1644 let registry = Arc::clone(core.registry.style());
1645 let mut map = match mln_map::Map::with_registry(Arc::clone(core.loader()), options.map, registry, &core.pool) {
1646 Ok(map) => map,
1647 Err(error) => return outbox.resolve(resolver, Err(error)),
1648 };
1649 if let Some(json) = &options.fallback_font_faces {
1650 if let Err(error) = map.set_fallback_font_faces(json) {
1651 return outbox.resolve(resolver, Err(error));
1652 }
1653 } else if options.system_fonts {
1654 map.set_fallback_font_face_list(mln_system_fonts::font_face().into_iter().collect());
1655 }
1656 let _ = published.updates.set(map.update_reader());
1657 let _ = published.frame_clock.set(map.frame_clock());
1658 let flush_pending = FlushFlag::default();
1659 map.set_reports_waker(Some(flush_pending.waker(&core.queue, id)));
1660 published.applied.store(1, Ordering::SeqCst);
1661 core.maps.insert(
1662 id,
1663 MapEntry {
1664 core: map,
1665 published,
1666 mask: options.event_mask,
1667 applied: 1,
1668 held_applied: None,
1669 held_sampled: None,
1670 pending_style: None,
1671 pending_still: None,
1672 session: None,
1673 flush_pending,
1674 camera_commands: HashMap::default(),
1675 callback_sources: CallbackSources::default(),
1676 geojson_updates: GeoJsonUpdates::default(),
1677 repaint: None,
1678 },
1679 );
1680 flush(core, id, outbox);
1681 if let Some(entry) = core.maps.get(&id) {
1682 outbox.resolve(resolver, Ok(entry.applied()));
1683 }
1684}
1685
1686pub(crate) fn apply_command<T>(
1694 core: &mut RuntimeCore,
1695 id: MapId,
1696 sequence: u64,
1697 outbox: &mut Outbox,
1698 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> T,
1699 after: impl FnOnce(&MapEntry, T, Applied, &mut Outbox),
1700) {
1701 if core.maps.get(&id).is_some_and(|entry| entry.flush_pending.is_set() || entry.core.has_reports()) {
1705 flush(core, id, outbox);
1706 }
1707 let Some(entry) = core.maps.get_mut(&id) else { return };
1708 let value = apply(entry, outbox);
1709 entry.applied = sequence;
1710 flush(core, id, outbox);
1711 let holding = core.holding_updates();
1712 let Some(entry) = core.maps.get_mut(&id) else { return };
1713 after(entry, value, entry.applied(), outbox);
1714 if holding {
1715 entry.held_applied = Some(sequence);
1716 } else {
1717 report_applied(entry, sequence);
1718 }
1719}
1720
1721fn report_applied(entry: &MapEntry, sequence: u64) {
1724 entry.published.applied.store(sequence, Ordering::SeqCst);
1725 if let Some(link) = &entry.session
1726 && sequence >= link.awaited.load(Ordering::SeqCst)
1727 {
1728 worker_post(&link.queue, move |worker, outbox| worker.map_applied(sequence, outbox));
1729 }
1730}
1731
1732fn report_sampled(entry: &MapEntry, sample: u64) {
1735 entry.published.sampled.fetch_max(sample, Ordering::SeqCst);
1736 if let Some(link) = &entry.session {
1737 worker_post(&link.queue, move |worker, outbox| worker.map_sampled(sample, outbox));
1738 }
1739}
1740
1741pub(crate) fn report_held(entry: &mut MapEntry) {
1744 if let Some(sequence) = entry.held_applied.take() {
1745 report_applied(entry, sequence);
1746 }
1747 if let Some(sample) = entry.held_sampled.take() {
1748 report_sampled(entry, sample);
1749 }
1750}
1751
1752fn sample_frame(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1755 let Some(entry) = core.maps.get(&id) else { return };
1756 entry.published.sample_queued.store(false, Ordering::SeqCst);
1758 let sample = entry.published.samples_requested.load(Ordering::SeqCst);
1759 if entry.flush_pending.is_set() || entry.core.has_reports() {
1760 flush(core, id, outbox);
1761 }
1762 let Some(entry) = core.maps.get_mut(&id) else { return };
1763 entry.core.sample_frame();
1764 flush(core, id, outbox);
1765 let holding = core.holding_updates();
1766 let Some(entry) = core.maps.get_mut(&id) else { return };
1767 if holding {
1768 entry.held_sampled = Some(sample);
1769 } else {
1770 report_sampled(entry, sample);
1771 }
1772}
1773
1774pub(crate) fn run_command<T, R: 'static>(
1777 core: &mut RuntimeCore,
1778 id: MapId,
1779 sequence: u64,
1780 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error>,
1781 finish: impl FnOnce(T, &MapEntry) -> R,
1782 resolver: Resolver<R>,
1783 outbox: &mut Outbox,
1784) {
1785 if !core.maps.contains_key(&id) {
1786 return outbox.resolve(resolver, Err(missing_map()));
1787 }
1788 apply_command(core, id, sequence, outbox, apply, move |entry, result, _, outbox| {
1789 outbox.resolve(resolver, result.map(|value| finish(value, entry)));
1790 });
1791}
1792
1793fn load_style(
1796 core: &mut RuntimeCore,
1797 id: MapId,
1798 sequence: u64,
1799 load: StyleLoad,
1800 resolver: Resolver<Applied>,
1801 outbox: &mut Outbox,
1802) {
1803 if !core.maps.contains_key(&id) {
1804 return outbox.resolve(resolver, Err(missing_map()));
1805 }
1806 apply_command(
1809 core,
1810 id,
1811 sequence,
1812 outbox,
1813 move |entry, outbox| {
1814 let from_json = matches!(load, StyleLoad::Json(_));
1815 if let Some(previous) = entry.pending_style.replace(PendingStyle { resolver, from_json }) {
1816 outbox.resolve(previous.resolver, Err(Error::cancelled("another style load started")));
1817 }
1818 match load {
1819 StyleLoad::Url(url) => entry.core.load_style_url(&url),
1820 StyleLoad::Json(json) => entry.core.load_style_json(&json),
1821 }
1822 },
1823 |_, (), _, _| {},
1824 );
1825}
1826
1827pub(crate) fn flush(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1832 let Some(entry) = core.maps.get_mut(&id) else { return };
1833 entry.flush_pending.clear();
1836 let events = entry.core.drain_events();
1837 let repaint_at = entry.core.repaint_at();
1838 if entry.repaint.as_ref().map(|(at, _)| *at) != repaint_at {
1839 if let Some((_, task)) = entry.repaint.take() {
1840 core.queue.cancel(task);
1841 }
1842 entry.repaint =
1843 repaint_at.map(|at| (at, post_at(&core.queue, at, move |core, outbox| repaint(core, id, outbox))));
1844 }
1845 crate::style::reconcile(entry, outbox);
1848 let generation = entry.core.generation();
1849 let ends: Vec<_> = entry
1851 .core
1852 .drain_command_ends()
1853 .filter_map(|end| Some((entry.camera_commands.remove(&end.command)?, TransitionEnd { generation, ..end.end })))
1854 .collect();
1855 let mut published = entry.published.state.lock();
1858 let snapshot = match &*published {
1859 Some(state) if state.snapshot.generation == generation => state.snapshot,
1860 _ => entry.core.snapshot(),
1861 };
1862 *published = Some(PublishedState { snapshot, ground: entry.core.ground() });
1865 drop(published);
1866
1867 let mut style_outcome = None;
1868 let from_json = entry.pending_style.as_ref().is_some_and(|pending| pending.from_json);
1869 for event in &events {
1870 match event {
1871 MapEvent::StyleLoaded => style_outcome = Some(Ok(())),
1872 MapEvent::LoadingFailed(StyleLoadError::Parse(message)) if from_json => {
1873 style_outcome = Some(Err(Error::invalid_argument(message)));
1874 }
1875 MapEvent::LoadingFailed(error) => style_outcome = Some(Err(Error::native(error.message()))),
1876 _ => {}
1877 }
1878 }
1879 let style_outcome = style_outcome.map(|outcome| (outcome, entry.pending_style.take(), entry.applied()));
1880 let still_outcome = match &mut entry.pending_still {
1881 Some(pending) => pending
1882 .refused
1883 .take()
1884 .or_else(|| entry.core.take_still_image().map(|result| result.map_err(still_image_error))),
1885 None => None,
1886 };
1887 let still = still_outcome.and_then(|outcome| Some((outcome, entry.pending_still.take()?.resolver)));
1888 let still_image = entry.pending_still.as_ref().and(entry.core.pending_still_image()).unwrap_or(0);
1891 if entry.published.still_image.swap(still_image, Ordering::SeqCst) != still_image
1892 && let Some(link) = &entry.session
1893 {
1894 worker_post(&link.queue, Worker::still_image_changed);
1895 }
1896
1897 let mask = entry.mask;
1898 let events: Vec<RuntimeEvent> = events
1899 .into_iter()
1900 .map(RuntimeEventKind::Map)
1901 .filter(|kind| mask.contains(kind.event_type()))
1902 .map(|kind| RuntimeEvent { source: EventSource::Map { id, generation }, kind })
1903 .collect();
1904 core.send_events(events, outbox);
1905 for (resolver, end) in ends {
1906 outbox.resolve(resolver, Ok(end));
1907 }
1908
1909 if let Some((outcome, Some(pending), applied)) = style_outcome {
1910 outbox.resolve(pending.resolver, outcome.map(|()| applied));
1911 }
1912 if let Some((outcome, resolver)) = still {
1913 outbox.resolve(resolver, outcome);
1914 }
1915}
1916
1917fn repaint(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1919 let Some(entry) = core.maps.get_mut(&id) else { return };
1920 entry.repaint = None;
1921 if entry.core.repaint_at().is_some() {
1922 entry.core.trigger_repaint();
1923 }
1924 flush(core, id, outbox);
1925}
1926
1927fn remove(core: &mut RuntimeCore, id: MapId, done: Option<Resolver<()>>, outbox: &mut Outbox) {
1929 flush(core, id, outbox);
1930 if let Some(mut entry) = core.maps.remove(&id) {
1931 if let Some((_, task)) = entry.repaint.take() {
1932 core.queue.cancel(task);
1933 }
1934 entry.core.set_waker(None);
1935 if let Some(state) = &mut *entry.published.state.lock() {
1937 state.ground = None;
1938 }
1939 if let Some(pending) = entry.pending_style.take() {
1940 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1941 }
1942 if let Some(pending) = entry.pending_still.take() {
1943 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1944 }
1945 crate::style::release(&mut entry, outbox);
1946 entry.core.close_camera();
1949 for end in entry.core.drain_command_ends() {
1950 if let Some(resolver) = entry.camera_commands.remove(&end.command) {
1951 outbox.resolve(resolver, Ok(end.end));
1952 }
1953 }
1954 }
1955 if let Some(done) = done {
1956 outbox.resolve(done, Ok(()));
1957 }
1958}