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_text::local_fonts::LocalGlyphs;
17use mln_util::error::{Error, ErrorKind};
18use mln_util::event_queue::Waker;
19use mln_util::geo::LatLngBounds;
20use mln_util::hash::HashMap;
21use mln_util::pool::Pool;
22use mln_util::queue::TimedTask;
23use mln_util::size::Size;
24use mln_util::time::Instant;
25use parking_lot::Mutex;
26
27use crate::camera::{self, CameraFitArea, CameraFitOptions, CameraFitUpdate, TileOptions, ViewportOptions};
28use crate::completion::{Completion, Resolver};
29use crate::event::{EventMask, EventSource, RuntimeEvent, RuntimeEventKind};
30use crate::feature_state::{FeatureState, FeatureStateSelector};
31use crate::render::{
32 Abandoner, AttachOptions, RenderSession, RenderTarget, SessionId, SessionQueue, SessionShared, Worker, worker_post,
33};
34use crate::runtime::{CoreQueue, Outbox, Runtime, RuntimeCore, RuntimeShared, post, post_at};
35use crate::style::{CallbackSources, GeoJsonUpdates};
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct MapId(pub u64);
40
41#[derive(Clone, Debug)]
43pub struct MapOptions {
44 pub map: mln_map::MapOptions,
45 pub event_mask: EventMask,
47 pub fallback_font_faces: Option<String>,
53 pub system_fonts: bool,
65 pub local_ideographs: bool,
70 pub tile_cache_enabled: bool,
73}
74
75impl Default for MapOptions {
76 fn default() -> Self {
77 MapOptions {
78 map: mln_map::MapOptions::default(),
79 event_mask: EventMask::default(),
80 fallback_font_faces: None,
81 system_fonts: true,
82 local_ideographs: true,
83 tile_cache_enabled: true,
84 }
85 }
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct Applied {
91 pub sequence: u64,
94 pub generation: u64,
97 pub render_update_generation: u64,
100}
101
102fn fit(map: &mut mln_map::Map, area: &CameraFitArea, update: CameraFitUpdate) -> Result<CameraCommandId, Error> {
104 let CameraFitUpdate { mode, fit, animation } = update;
105 let camera = camera::camera_for(map, area, &fit)?;
106 Ok(map.update_camera(&CameraUpdate { mode, camera, animation, ..CameraUpdate::default() }))
107}
108
109#[derive(Clone, Copy, Debug, PartialEq)]
111pub struct CameraQuery {
112 pub generation: u64,
113 pub camera: Camera,
114}
115
116pub(crate) struct Published {
118 snapshot: Mutex<Option<MapSnapshot>>,
119 updates: OnceLock<UpdateReader>,
121 applied: AtomicU64,
124 frame_clock: OnceLock<FrameClock>,
127 samples_requested: AtomicU64,
130 sampled: AtomicU64,
131 sample_queued: AtomicBool,
134 event_mask: AtomicU64,
135 still_image: AtomicU64,
138}
139
140impl Published {
141 pub(crate) fn applied(&self) -> u64 {
144 self.applied.load(Ordering::SeqCst)
145 }
146
147 pub(crate) fn sampled(&self) -> u64 {
149 self.sampled.load(Ordering::SeqCst)
150 }
151
152 pub(crate) fn animating(&self) -> bool {
155 self.snapshot.lock().as_ref().is_some_and(|snapshot| snapshot.transition_in_progress)
156 }
157
158 pub(crate) fn pending_still_image(&self) -> u64 {
162 self.still_image.load(Ordering::SeqCst)
163 }
164
165 pub(crate) fn new(event_mask: EventMask) -> Self {
166 Published {
167 snapshot: Mutex::new(None),
168 updates: OnceLock::new(),
169 applied: AtomicU64::new(0),
170 frame_clock: OnceLock::new(),
171 samples_requested: AtomicU64::new(0),
172 sampled: AtomicU64::new(0),
173 sample_queued: AtomicBool::new(false),
174 event_mask: AtomicU64::new(event_mask.bits()),
175 still_image: AtomicU64::new(0),
176 }
177 }
178}
179
180pub(crate) struct MapShared {
181 id: MapId,
182 runtime: Arc<RuntimeShared>,
183 mode: MapMode,
184 scale_factor: AtomicU64,
187 tile_cache_enabled: bool,
188 system_fonts: bool,
189 local_ideographs: bool,
190 session: Mutex<Option<SessionClaim>>,
193 sent: Mutex<u64>,
197 released: AtomicBool,
199 removed: AtomicBool,
201 published: Arc<Published>,
202}
203
204impl MapShared {
205 pub(crate) fn new(id: MapId, runtime: Arc<RuntimeShared>, options: &MapOptions, published: Arc<Published>) -> Self {
206 MapShared {
207 id,
208 runtime,
209 mode: options.map.map_mode,
210 scale_factor: AtomicU64::new(f64::from(options.map.pixel_ratio).to_bits()),
211 tile_cache_enabled: options.tile_cache_enabled,
212 system_fonts: options.system_fonts,
213 local_ideographs: options.local_ideographs,
214 session: Mutex::new(None),
215 sent: Mutex::new(1),
216 released: AtomicBool::new(false),
217 removed: AtomicBool::new(false),
218 published,
219 }
220 }
221
222 fn completion<R: Send + 'static>(&self, discard: Option<fn(Error)>) -> (Completion<R>, Resolver<R>) {
226 match discard {
227 Some(on_failure) => Completion::discarded(on_failure),
228 None => self.runtime.completion(),
229 }
230 }
231
232 pub(crate) fn send<R: Send + 'static>(
234 &self,
235 discard: Option<fn(Error)>,
236 command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
237 ) -> Result<Completion<R>, Error> {
238 let mut sent = self.sent.lock();
239 if self.released.load(Ordering::SeqCst) {
240 return Err(released());
241 }
242 self.runtime.check_running()?;
243 let (completion, resolver) = self.completion(discard);
244 let id = self.id;
245 *sent += 1;
246 let sequence = *sent;
247 self.runtime.post(move |core, outbox| command(core, outbox, id, sequence, resolver));
248 Ok(completion)
249 }
250
251 fn release(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
254 self.close()?;
255 self.remove(done);
256 Ok(())
257 }
258
259 fn close(&self) -> Result<(), Error> {
262 let _sent = self.sent.lock();
263 if self.released.swap(true, Ordering::SeqCst) {
264 return Err(released());
265 }
266 Ok(())
267 }
268
269 fn remove(&self, done: Option<Resolver<()>>) {
272 if self.removed.swap(true, Ordering::SeqCst) {
273 return;
274 }
275 let id = self.id;
276 self.runtime.post_or_stopped(
278 done,
279 move |core, outbox, done| remove(core, id, done, outbox),
280 |done| {
281 if let Some(done) = done {
282 done.resolve(Ok(()));
283 }
284 },
285 );
286 self.runtime.map_released();
287 }
288}
289
290impl Drop for MapShared {
291 fn drop(&mut self) {
292 let _ = self.close();
293 let deferred = self.session.get_mut().take().and_then(|claim| claim.removal);
294 self.remove(deferred);
295 }
296}
297
298#[derive(Clone)]
311pub struct Map {
312 pub(crate) shared: Arc<MapShared>,
313 discard: Option<fn(Error)>,
316}
317
318impl std::fmt::Debug for Map {
319 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320 f.debug_struct("Map").field("id", &self.shared.id).field("discards_results", &self.discard.is_some()).finish()
321 }
322}
323
324impl PartialEq for Map {
325 fn eq(&self, other: &Map) -> bool {
326 Arc::ptr_eq(&self.shared, &other.shared)
327 }
328}
329
330impl Eq for Map {}
331
332fn released() -> Error {
333 Error::invalid_state("the map was released")
334}
335
336pub(crate) fn style_not_loaded() -> Error {
337 Error::invalid_state("style is not loaded")
338}
339
340pub(crate) fn missing_map() -> Error {
343 Error::invalid_state("the map failed to be built or was released")
344}
345
346type Reply<T> = Box<dyn FnOnce(&mut Worker, Result<T, Error>, &mut Outbox) + Send>;
348
349struct SessionReply<T: Send + 'static> {
354 queue: SessionQueue,
355 reply: Option<Reply<T>>,
356}
357
358impl<T: Send + 'static> SessionReply<T> {
359 fn new(
360 queue: SessionQueue,
361 reply: impl FnOnce(&mut Worker, Result<T, Error>, &mut Outbox) + Send + 'static,
362 ) -> Self {
363 SessionReply { queue, reply: Some(Box::new(reply)) }
364 }
365
366 fn send(mut self, result: Result<T, Error>) {
367 if let Some(reply) = self.reply.take() {
368 worker_post(&self.queue, move |worker, outbox| reply(worker, result, outbox));
369 }
370 }
371}
372
373impl<T: Send + 'static> Drop for SessionReply<T> {
374 fn drop(&mut self) {
375 if let Some(reply) = self.reply.take() {
376 let error = Error::cancelled("the runtime stopped before the command ran");
377 worker_post(&self.queue, move |worker, outbox| reply(worker, Err(error), outbox));
378 }
379 }
380}
381
382impl Map {
383 pub(crate) fn new(shared: MapShared) -> Self {
384 Map { shared: Arc::new(shared), discard: None }
385 }
386
387 #[must_use]
392 pub fn discarding_results(&self, on_failure: fn(Error)) -> Map {
393 Map { shared: Arc::clone(&self.shared), discard: Some(on_failure) }
394 }
395
396 pub(crate) fn post<R: Send + 'static>(
399 &self,
400 command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
401 ) -> Result<Completion<R>, Error> {
402 self.shared.send(self.discard, command)
403 }
404
405 #[must_use]
406 pub fn id(&self) -> MapId {
407 self.shared.id
408 }
409
410 #[must_use]
412 pub fn mode(&self) -> MapMode {
413 self.shared.mode
414 }
415
416 #[must_use]
418 pub fn runtime(&self) -> Runtime {
419 Runtime { shared: Arc::clone(&self.shared.runtime) }
420 }
421
422 #[must_use]
424 pub fn sent_sequence(&self) -> u64 {
425 *self.shared.sent.lock()
426 }
427
428 #[must_use]
432 pub fn applied_sequence(&self) -> u64 {
433 self.shared.published.applied.load(Ordering::SeqCst)
434 }
435
436 pub fn snapshot(&self) -> Result<MapSnapshot, Error> {
446 if self.shared.released.load(Ordering::SeqCst) {
447 return Err(released());
448 }
449 let mut snapshot =
450 self.shared.published.snapshot.lock().ok_or_else(|| Error::invalid_state("the map isn't built"))?;
451 if let Some(updates) = self.shared.published.updates.get() {
455 snapshot.update_generation = updates.generation();
456 }
457 Ok(snapshot)
458 }
459
460 #[must_use]
462 pub fn event_mask(&self) -> EventMask {
463 EventMask::from_bits(self.shared.published.event_mask.load(Ordering::SeqCst)).unwrap_or_default()
464 }
465
466 pub(crate) fn send<T: 'static, R: Send + 'static>(
469 &self,
470 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error> + Send + 'static,
471 finish: impl FnOnce(T, &MapEntry) -> R + Send + 'static,
472 ) -> Result<Completion<R>, Error> {
473 self.post(move |core, outbox, id, sequence, resolver| {
474 run_command(core, id, sequence, apply, finish, resolver, outbox);
475 })
476 }
477
478 pub(crate) fn command(
480 &self,
481 apply: impl FnOnce(&mut mln_map::Map) -> Result<(), Error> + Send + 'static,
482 ) -> Result<Completion<Applied>, Error> {
483 self.send(move |entry, _| apply(&mut entry.core), |(), entry| entry.applied())
484 }
485
486 pub(crate) fn query<T: Send + 'static>(
488 &self,
489 read: impl FnOnce(&mut mln_map::Map) -> Result<T, Error> + Send + 'static,
490 ) -> Result<Completion<T>, Error> {
491 self.send(move |entry, _| read(&mut entry.core), |value, _| value)
492 }
493
494 pub fn with_core<R: Send + 'static>(
499 &self,
500 f: impl FnOnce(&mut mln_map::Map) -> R + Send + 'static,
501 ) -> Result<Completion<R>, Error> {
502 self.query(move |map| Ok(f(map)))
503 }
504
505 pub fn release(&self) -> Result<Completion<()>, Error> {
516 self.release_with(false)
517 }
518
519 pub fn dispose(&self) -> Result<Completion<()>, Error> {
531 self.release_with(true)
532 }
533
534 fn release_with(&self, in_any_state: bool) -> Result<Completion<()>, Error> {
535 let (completion, resolver) = self.shared.completion(self.discard);
536 let claimed = {
537 let mut claim = self.shared.session.lock();
538 match claim.as_mut() {
539 None => None,
540 Some(held) => match held.session.upgrade() {
541 Some(session) if session.is_released() => Some((held.id, Some(session))),
543 Some(_) if in_any_state => {
546 self.shared.close()?;
547 held.removal = Some(resolver);
548 return Ok(completion);
549 }
550 Some(_) => return Err(Error::invalid_state("map still has an attached render session")),
551 None => Some((held.id, None)),
553 },
554 }
555 };
556 if let Some((id, session)) = claimed {
557 if let Some(session) = session {
558 let _ = session.abandon(Abandoner::Library);
559 }
560 self.release_session_claim(id);
561 }
562 self.shared.release(Some(resolver))?;
563 Ok(completion)
564 }
565
566 pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
576 let LogicalExtent { size, scale_factor } = extent;
577 if self.shared.session.lock().is_some() {
578 return Err(Error::invalid_state("the map has a render session: resize the session instead"));
579 }
580 if size.is_empty() {
581 return Err(Error::invalid_argument("logical size dimensions must be positive"));
582 }
583 if !scale_factor.is_finite() || scale_factor <= 0.0 {
584 return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
585 }
586 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
588 self.command(move |map| {
589 if map.snapshot().view.extent.size != size {
590 map.set_size(size)?;
591 }
592 map.set_pixel_ratio(scale_factor as f32)
593 })
594 }
595
596 pub fn request_repaint(&self) -> Result<Completion<Applied>, Error> {
600 if self.shared.mode != MapMode::Continuous {
601 return Err(Error::invalid_state("map is not in continuous mode"));
602 }
603 self.command(|map| {
604 map.trigger_repaint();
605 Ok(())
606 })
607 }
608
609 pub fn begin_command_group(&self) -> Result<Completion<Applied>, Error> {
614 self.command(|map| {
615 map.begin_command_group();
616 Ok(())
617 })
618 }
619
620 pub fn end_command_group(&self) -> Result<Completion<Applied>, Error> {
624 self.command(mln_map::Map::end_command_group)
625 }
626
627 pub fn command_group(&self) -> Result<CommandGroup, Error> {
630 drop(self.begin_command_group()?);
631 Ok(CommandGroup { map: Some(self.clone()) })
632 }
633
634 pub fn set_event_mask(&self, mask: EventMask) -> Result<Completion<Applied>, Error> {
636 self.send(
637 move |entry, _| {
638 if entry.mask != mask {
639 entry.mask = mask;
640 entry.published.event_mask.store(mask.bits(), Ordering::SeqCst);
641 entry.core.record_change();
642 }
643 Ok(())
644 },
645 |(), entry| entry.applied(),
646 )
647 }
648
649 pub fn attach(
676 &self,
677 target: RenderTarget,
678 options: AttachOptions,
679 ) -> Result<(RenderSession, Completion<()>), Error> {
680 crate::render::attach(self, target, options, |session, attached| (session.clone(), attached))
681 }
682
683 pub fn attach_then<R>(
695 &self,
696 target: RenderTarget,
697 options: AttachOptions,
698 then: impl FnOnce(&RenderSession, Completion<()>) -> R,
699 ) -> Result<R, Error> {
700 crate::render::attach(self, target, options, then)
701 }
702
703 pub fn request_still_image(&self) -> Result<Completion<()>, Error> {
728 if self.shared.mode == MapMode::Continuous {
729 return Err(Error::invalid_state("the map is not in static or tile mode"));
730 }
731 self.post(move |core, outbox, id, sequence, resolver| {
732 if !core.maps.contains_key(&id) {
733 return outbox.resolve(resolver, Err(missing_map()));
734 }
735 apply_command(
736 core,
737 id,
738 sequence,
739 outbox,
740 move |entry, outbox| {
741 if entry.pending_still.is_some() {
742 let error = Error::invalid_state("the map is rendering a still image already");
743 return outbox.resolve(resolver, Err(error));
744 }
745 if entry.core.command_group_depth() > 0 {
747 let error = Error::invalid_state("a still image can't render while a command group is open");
748 return outbox.resolve(resolver, Err(error));
749 }
750 let refused = entry.core.render_still().err().map(|error| Err(still_image_error(error)));
751 entry.pending_still = Some(PendingStill { resolver, refused });
752 },
753 |_, (), _, _| {},
754 );
755 })
756 }
757
758 pub(crate) fn is_released(&self) -> bool {
760 self.shared.released.load(Ordering::SeqCst)
761 }
762
763 pub(crate) fn runtime_thread(&self) -> std::thread::ThreadId {
764 self.shared.runtime.thread()
765 }
766
767 #[must_use]
772 pub fn scale_factor(&self) -> f64 {
773 f64::from_bits(self.shared.scale_factor.load(Ordering::SeqCst))
774 }
775
776 pub(crate) fn tile_cache_enabled(&self) -> bool {
777 self.shared.tile_cache_enabled
778 }
779
780 pub(crate) fn local_glyphs(&self) -> LocalGlyphs {
786 let mut local = LocalGlyphs { ideographs: self.shared.local_ideographs, ..LocalGlyphs::default() };
787 if self.shared.system_fonts {
788 #[cfg(not(target_family = "wasm"))]
789 {
790 local.chooser = Some(Arc::new(mln_system_fonts::SystemFonts));
791 }
792 #[cfg(target_family = "wasm")]
793 {
794 let font_family = "sans-serif".to_owned();
795 local.rasterizer =
796 Some(Arc::new(mln_text::browser_glyph_rasterizer::BrowserGlyphRasterizer::new(font_family)));
797 }
798 }
799 local
800 }
801
802 pub(crate) fn glyph_cache(&self) -> Arc<GlyphCache> {
803 Arc::clone(&self.shared.runtime.glyph_cache)
804 }
805
806 pub(crate) fn pool(&self) -> Pool {
808 self.shared.runtime.pool.clone()
809 }
810
811 pub(crate) fn font_face_engine(&self) -> Arc<dyn FontFaceEngine> {
813 Arc::clone(&self.shared.runtime.font_face_engine)
814 }
815
816 #[must_use]
821 pub fn registry(&self) -> &Arc<Registry> {
822 &self.shared.runtime.registry
823 }
824
825 pub(crate) fn claim_session(&self, id: SessionId, session: Weak<SessionShared>) -> Result<(), Error> {
827 let mut claim = self.shared.session.lock();
828 if self.shared.released.load(Ordering::SeqCst) {
829 return Err(released());
830 }
831 if claim.is_some() {
832 return Err(Error::invalid_state("the map already has an attached render session"));
833 }
834 *claim = Some(SessionClaim { id, session, removal: None });
835 Ok(())
836 }
837
838 pub(crate) fn release_session_claim(&self, id: SessionId) {
841 let claim = {
842 let mut session = self.shared.session.lock();
843 if session.as_ref().is_some_and(|claim| claim.id == id) { session.take() } else { None }
844 };
845 if let Some(removal) = claim.and_then(|claim| claim.removal) {
846 self.shared.remove(Some(removal));
847 }
848 }
849
850 pub(crate) fn bind_session(
855 &self,
856 id: SessionId,
857 queue: SessionQueue,
858 awaited: Arc<AtomicU64>,
859 size: Size,
860 ) -> Result<(), Error> {
861 let reply = SessionReply::new(queue.clone(), |worker, bound, outbox| match bound {
862 Ok((sequence, reader, events, published)) => worker.bound(sequence, reader, events, published, outbox),
863 Err(error) => worker.bind_failed(error, outbox),
864 });
865 let sent = self.shared.send(Some(drop), move |core, outbox, map_id, sequence, resolver: Resolver<()>| {
866 drop(resolver);
867 if !core.maps.contains_key(&map_id) {
868 return reply.send(Err(missing_map()));
869 }
870 let link = SessionLink { id, queue, awaited };
871 apply_command(
872 core,
873 map_id,
874 sequence,
875 outbox,
876 move |entry, _| {
877 entry.session = Some(link);
878 let resized = entry.core.set_size(size);
879 (resized, entry.core.update_reader(), entry.core.renderer_events(), Arc::clone(&entry.published))
880 },
881 move |_, (resized, reader, events, published), _, _| {
882 reply.send(resized.map(|()| (sequence, reader, events, published)));
883 },
884 );
885 });
886 sent.map(drop)
887 }
888
889 pub(crate) fn unbind_session(&self, id: SessionId) {
892 let map_id = self.shared.id;
893 self.shared.runtime.post_or((), move |core, _, ()| unbind(core, map_id, id), |()| {});
895 }
896
897 pub(crate) fn unbind_session_then(
900 &self,
901 id: SessionId,
902 queue: SessionQueue,
903 then: impl FnOnce(&mut Worker, &mut Outbox) + Send + 'static,
904 ) {
905 let map_id = self.shared.id;
906 let reply = SessionReply::new(queue, move |worker, _: Result<(), Error>, outbox| then(worker, outbox));
907 self.shared.runtime.post_or(
910 reply,
911 move |core, _, reply| {
912 unbind(core, map_id, id);
913 reply.send(Ok(()));
914 },
915 drop,
916 );
917 }
918
919 pub(crate) fn frame_demanded(&self) -> u64 {
925 let published = &self.shared.published;
926 if let Some(clock) = published.frame_clock.get() {
927 clock.set(Some(Instant::now()));
928 }
929 if self.shared.mode != MapMode::Continuous || !published.animating() {
932 return 0;
933 }
934 let sample = published.samples_requested.fetch_add(1, Ordering::SeqCst) + 1;
935 if !published.sample_queued.swap(true, Ordering::SeqCst) {
936 let id = self.shared.id;
937 self.shared.runtime.post_apart(move |core, outbox| sample_frame(core, id, outbox));
938 }
939 sample
940 }
941
942 pub(crate) fn resize_for_session(
946 &self,
947 size: Size,
948 scale_factor: f64,
949 queue: SessionQueue,
950 resize: impl FnOnce(&mut Worker, Result<Applied, Error>, &mut Outbox) + Send + 'static,
951 ) -> Result<(), Error> {
952 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
954 let reply = SessionReply::new(queue, resize);
955 let sent = self.shared.send(Some(drop), move |core, outbox, id, sequence, resolver: Resolver<()>| {
956 drop(resolver);
957 if !core.maps.contains_key(&id) {
958 return reply.send(Err(missing_map()));
959 }
960 apply_command(
961 core,
962 id,
963 sequence,
964 outbox,
965 move |entry, _| {
966 let pixel_ratio = scale_factor as f32;
970 let extent = entry.core.snapshot().view.extent;
971 if extent.size == size && extent.scale_factor == f64::from(pixel_ratio) {
972 return Ok(());
973 }
974 entry.core.set_size(size)?;
975 entry.core.set_pixel_ratio(pixel_ratio)
976 },
977 move |_, resized, applied, _| reply.send(resized.map(|()| applied)),
978 );
979 });
980 sent.map(drop)
981 }
982
983 pub fn set_feature_state(
1004 &self,
1005 selector: &FeatureStateSelector,
1006 state: FeatureState,
1007 ) -> Result<Completion<Applied>, Error> {
1008 let key = selector.key(true)?;
1009 self.command(move |map| {
1010 let feature_id = key.feature_id.as_deref().unwrap_or_default();
1011 map.set_feature_state(&key.source_id, Some(&key.source_layer_id), feature_id, state);
1012 Ok(())
1013 })
1014 }
1015
1016 pub fn feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<FeatureState>, Error> {
1020 let key = selector.key(true)?;
1021 self.query(move |map| {
1022 let feature_id = key.feature_id.as_deref().unwrap_or_default();
1023 Ok(map.feature_state(&key.source_id, Some(&key.source_layer_id), feature_id))
1024 })
1025 }
1026
1027 pub fn remove_feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<Applied>, Error> {
1035 let key = selector.key(false)?;
1036 self.command(move |map| {
1037 map.remove_feature_state(
1038 &key.source_id,
1039 Some(&key.source_layer_id),
1040 key.feature_id.as_deref(),
1041 key.state_key.as_deref(),
1042 );
1043 Ok(())
1044 })
1045 }
1046
1047 pub fn set_style_url(&self, url: impl Into<String>) -> Result<Completion<Applied>, Error> {
1059 let url = url.into();
1060 if url.is_empty() {
1061 return Err(Error::invalid_argument("style URL must not be empty"));
1062 }
1063 self.load_style(StyleLoad::Url(url))
1064 }
1065
1066 pub fn set_style_json(&self, json: impl Into<String>) -> Result<Completion<Applied>, Error> {
1072 let json = json.into();
1073 if json.is_empty() {
1074 return Err(Error::invalid_argument("style JSON must not be empty"));
1075 }
1076 self.load_style(StyleLoad::Json(json))
1077 }
1078
1079 fn load_style(&self, load: StyleLoad) -> Result<Completion<Applied>, Error> {
1080 self.post(move |core, outbox, id, sequence, resolver| {
1081 load_style(core, id, sequence, load, resolver, outbox);
1082 })
1083 }
1084
1085 pub fn loaded_style_json(&self) -> Result<Completion<String>, Error> {
1088 self.query(|map| Ok(map.style().get_json().to_owned()))
1089 }
1090
1091 pub fn style_url(&self) -> Result<Completion<Option<String>>, Error> {
1093 self.query(|map| Ok(map.style_url().filter(|url| !url.is_empty()).map(str::to_owned)))
1094 }
1095
1096 pub fn add_style_source_json(
1099 &self,
1100 source_id: impl Into<String>,
1101 json: impl Into<String>,
1102 ) -> Result<Completion<Applied>, Error> {
1103 let (source_id, json) = (source_id.into(), json.into());
1104 self.command(move |map| map.add_source_json(&source_id, &json))
1105 }
1106
1107 pub fn remove_style_source(&self, source_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1114 let source_id = source_id.into();
1115 self.send(
1116 move |entry, _| {
1117 let map = &mut entry.core;
1118 if !map.style_document_loaded() {
1119 return Err(style_not_loaded());
1120 }
1121 if map.source(&source_id).is_none() {
1122 return Err(Error::not_found(format!("source \"{source_id}\" does not exist")));
1123 }
1124 if let Some(layer) = map.style().get_layers().find(|layer| layer.get_source_id() == source_id) {
1125 let message = format!("source \"{source_id}\" is used by layer \"{}\"", layer.get_id());
1126 return Err(Error::invalid_state(message));
1127 }
1128 map.remove_source(&source_id);
1129 entry.core.remove_source_feature_state(&source_id);
1130 Ok(())
1131 },
1132 |(), entry| entry.applied(),
1133 )
1134 }
1135
1136 pub fn add_style_layer_json(
1139 &self,
1140 json: impl Into<String>,
1141 before_layer_id: Option<String>,
1142 ) -> Result<Completion<Applied>, Error> {
1143 let json = json.into();
1144 self.command(move |map| map.edit_loaded_style(|style| style.add_layer_json(&json, before_layer_id.as_deref())))
1145 }
1146
1147 pub fn add_custom_layer(
1152 &self,
1153 layer_id: impl Into<String>,
1154 host: Arc<dyn CustomLayerHost>,
1155 before_layer_id: Option<String>,
1156 ) -> Result<Completion<Applied>, Error> {
1157 let layer_id = layer_id.into();
1158 self.command(move |map| {
1159 map.edit_loaded_style(|style| style.add_custom_layer(&layer_id, host, before_layer_id.as_deref()))
1160 })
1161 }
1162
1163 pub fn remove_style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1168 let layer_id = layer_id.into();
1169 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::RemoveLayer(layer_id))))
1170 }
1171
1172 pub fn style_layer_json(&self, layer_id: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1175 let layer_id = layer_id.into();
1176 self.query(move |map| Ok(map.style().layer_json(&layer_id)))
1177 }
1178
1179 pub fn set_style_layer_property(
1182 &self,
1183 layer_id: impl Into<String>,
1184 name: impl Into<String>,
1185 json: impl Into<String>,
1186 ) -> Result<Completion<Applied>, Error> {
1187 let (layer_id, name, json) = (layer_id.into(), name.into(), json.into());
1188 self.command(move |map| map.edit_loaded_style(|style| style.set_layer_property_json(&layer_id, &name, &json)))
1189 }
1190
1191 pub fn style_layer_property(
1194 &self,
1195 layer_id: impl Into<String>,
1196 name: impl Into<String>,
1197 ) -> Result<Completion<Option<String>>, Error> {
1198 let (layer_id, name) = (layer_id.into(), name.into());
1199 self.query(move |map| map.style().layer_property_json(&layer_id, &name))
1200 }
1201
1202 pub fn set_style_root_property(
1206 &self,
1207 name: impl Into<String>,
1208 json: impl Into<String>,
1209 ) -> Result<Completion<Applied>, Error> {
1210 let (name, json) = (name.into(), json.into());
1211 self.command(move |map| map.edit_loaded_style(|style| style.set_root_property_json(&name, &json)))
1212 }
1213
1214 pub fn style_root_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1217 let name = name.into();
1218 self.query(move |map| map.style().root_property_json(&name))
1219 }
1220
1221 pub fn set_style_light_property(
1223 &self,
1224 name: impl Into<String>,
1225 json: impl Into<String>,
1226 ) -> Result<Completion<Applied>, Error> {
1227 let (name, json) = (name.into(), json.into());
1228 self.command(move |map| map.edit_loaded_style(|style| style.set_light_property_json(&name, &json)))
1229 }
1230
1231 pub fn style_light_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1234 let name = name.into();
1235 self.query(move |map| Ok(map.style().light_property_json(&name)))
1236 }
1237
1238 fn camera_command(
1243 &self,
1244 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1245 ) -> Result<Completion<Applied>, Error> {
1246 self.send_camera(apply, None)
1247 }
1248
1249 fn camera_command_then(
1254 &self,
1255 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1256 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1257 ) -> Result<Completion<Applied>, Error> {
1258 let (ended, end) = self.shared.runtime.completion();
1259 ended.on_complete(on_end);
1260 self.send_camera(apply, Some(end))
1261 }
1262
1263 fn send_camera(
1266 &self,
1267 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1268 end: Option<Resolver<TransitionEnd>>,
1269 ) -> Result<Completion<Applied>, Error> {
1270 self.send(
1271 move |entry, outbox| match (apply(&mut entry.core), end) {
1272 (Ok(command), Some(end)) => {
1273 entry.camera_commands.insert(command, end);
1274 Ok(())
1275 }
1276 (Ok(_), None) => Ok(()),
1277 (Err(error), end) => {
1278 if let Some(end) = end {
1279 let generation = entry.core.generation();
1280 let cancelled =
1281 TransitionEnd { outcome: TransitionOutcome::Cancelled, generation, ..Default::default() };
1282 outbox.resolve(end, Ok(cancelled));
1283 }
1284 Err(error)
1285 }
1286 },
1287 |(), entry| entry.applied(),
1288 )
1289 }
1290
1291 pub fn update_camera(&self, update: CameraUpdate) -> Result<Completion<Applied>, Error> {
1293 self.camera_command(move |map| Ok(map.update_camera(&update)))
1294 }
1295
1296 pub fn update_camera_then(
1306 &self,
1307 update: CameraUpdate,
1308 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1309 ) -> Result<Completion<Applied>, Error> {
1310 self.camera_command_then(move |map| Ok(map.update_camera(&update)), on_end)
1311 }
1312
1313 pub fn apply_camera_delta(&self, delta: CameraDelta) -> Result<Completion<Applied>, Error> {
1317 self.camera_command(move |map| {
1318 map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string()))
1319 })
1320 }
1321
1322 pub fn apply_camera_delta_then(
1326 &self,
1327 delta: CameraDelta,
1328 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1329 ) -> Result<Completion<Applied>, Error> {
1330 self.camera_command_then(
1331 move |map| map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string())),
1332 on_end,
1333 )
1334 }
1335
1336 pub fn camera_for(
1343 &self,
1344 area: CameraFitArea,
1345 options: CameraFitOptions,
1346 ) -> Result<Completion<CameraOptions>, Error> {
1347 self.query(move |map| camera::camera_for(map, &area, &options))
1348 }
1349
1350 pub fn fit_camera(&self, area: CameraFitArea, update: CameraFitUpdate) -> Result<Completion<Applied>, Error> {
1357 self.camera_command(move |map| fit(map, &area, update))
1358 }
1359
1360 pub fn fit_camera_then(
1364 &self,
1365 area: CameraFitArea,
1366 update: CameraFitUpdate,
1367 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1368 ) -> Result<Completion<Applied>, Error> {
1369 self.camera_command_then(move |map| fit(map, &area, update), on_end)
1370 }
1371
1372 pub fn cancel_camera_transitions(&self) -> Result<Completion<Applied>, Error> {
1374 self.command(|map| {
1375 map.cancel_transitions();
1376 Ok(())
1377 })
1378 }
1379
1380 pub fn cancel_camera_transitions_with_id(&self, transition_id: u64) -> Result<Completion<Applied>, Error> {
1382 self.command(move |map| {
1383 map.cancel_transitions_with_id(transition_id);
1384 Ok(())
1385 })
1386 }
1387
1388 pub fn camera(&self) -> Result<Completion<CameraQuery>, Error> {
1390 self.send(
1391 |_, _| Ok(()),
1392 |(), entry| CameraQuery { generation: entry.core.generation(), camera: entry.core.snapshot().view.camera },
1393 )
1394 }
1395
1396 pub fn lat_lng_bounds_for_camera(&self, camera: CameraOptions) -> Result<Completion<LatLngBounds>, Error> {
1401 self.query(move |map| map.lat_lng_bounds_for_camera_unwrapped(&camera))
1402 }
1403
1404 pub fn set_bounds(&self, bounds: BoundOptions) -> Result<Completion<Applied>, Error> {
1406 self.command(move |map| map.set_bounds(&bounds))
1407 }
1408
1409 pub fn set_free_camera_options(&self, camera: FreeCameraOptions) -> Result<Completion<Applied>, Error> {
1411 self.command(move |map| {
1412 map.set_free_camera_options(&camera);
1413 Ok(())
1414 })
1415 }
1416
1417 pub fn set_viewport_options(&self, options: ViewportOptions) -> Result<Completion<Applied>, Error> {
1419 self.command(move |map| {
1420 camera::set_viewport(map, &options);
1421 Ok(())
1422 })
1423 }
1424
1425 pub fn set_tile_options(&self, options: TileOptions) -> Result<Completion<Applied>, Error> {
1427 self.command(move |map| {
1428 camera::set_tile_options(map, &options);
1429 Ok(())
1430 })
1431 }
1432
1433 pub fn set_projection_mode(&self, mode: ProjectionMode) -> Result<Completion<Applied>, Error> {
1434 self.command(move |map| {
1435 map.set_projection_mode(&mode);
1436 Ok(())
1437 })
1438 }
1439
1440 pub fn set_debug_flags(&self, flags: MapDebugOptions) -> Result<Completion<Applied>, Error> {
1442 self.command(move |map| {
1443 map.set_debug(flags);
1444 Ok(())
1445 })
1446 }
1447
1448 pub fn set_rendering_stats_view_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1450 self.command(move |map| {
1451 map.enable_rendering_stats_view(enabled);
1452 Ok(())
1453 })
1454 }
1455
1456 pub fn set_globe_free_bearing_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1459 self.command(move |map| {
1460 map.set_globe_free_bearing(enabled);
1461 Ok(())
1462 })
1463 }
1464
1465 pub fn dump_debug_logs(&self) -> Result<Completion<Applied>, Error> {
1467 self.command(|map| {
1468 map.dump_debug_logs();
1469 Ok(())
1470 })
1471 }
1472}
1473
1474#[must_use = "the group ends when it drops"]
1476pub struct CommandGroup {
1477 map: Option<Map>,
1478}
1479
1480impl CommandGroup {
1481 pub fn end(mut self) -> Result<Completion<Applied>, Error> {
1483 match self.map.take() {
1484 Some(map) => map.end_command_group(),
1485 None => Err(Error::invalid_state("the group ended already")),
1486 }
1487 }
1488}
1489
1490impl Drop for CommandGroup {
1491 fn drop(&mut self) {
1492 if let Some(map) = self.map.take() {
1493 let _ = map.end_command_group();
1494 }
1495 }
1496}
1497
1498enum StyleLoad {
1499 Url(String),
1500 Json(String),
1501}
1502
1503struct PendingStyle {
1505 resolver: Resolver<Applied>,
1506 from_json: bool,
1509}
1510
1511struct SessionClaim {
1513 id: SessionId,
1514 session: Weak<SessionShared>,
1515 removal: Option<Resolver<()>>,
1517}
1518
1519fn unbind(core: &mut RuntimeCore, map_id: MapId, id: SessionId) {
1522 if let Some(entry) = core.maps.get_mut(&map_id)
1523 && entry.session.as_ref().is_some_and(|link| link.id == id)
1524 {
1525 entry.session = None;
1526 }
1527}
1528
1529pub(crate) struct SessionLink {
1531 id: SessionId,
1532 queue: SessionQueue,
1533 awaited: Arc<AtomicU64>,
1535}
1536
1537struct PendingStill {
1540 resolver: Resolver<()>,
1541 refused: Option<Result<(), Error>>,
1544}
1545
1546fn still_image_error(error: Error) -> Error {
1549 match error.kind {
1550 ErrorKind::InvalidState => error,
1551 _ => Error::native(error.message),
1552 }
1553}
1554
1555pub(crate) struct MapEntry {
1557 pub(crate) core: mln_map::Map,
1558 published: Arc<Published>,
1559 mask: EventMask,
1560 applied: u64,
1562 held_applied: Option<u64>,
1565 held_sampled: Option<u64>,
1566 pending_style: Option<PendingStyle>,
1568 pending_still: Option<PendingStill>,
1569 session: Option<SessionLink>,
1571 flush_pending: FlushFlag,
1573 camera_commands: HashMap<CameraCommandId, Resolver<TransitionEnd>>,
1575 pub(crate) callback_sources: CallbackSources,
1577 pub(crate) geojson_updates: GeoJsonUpdates,
1579 repaint: Option<(Instant, TimedTask)>,
1582}
1583
1584impl MapEntry {
1585 pub(crate) fn applied(&self) -> Applied {
1586 Applied {
1587 sequence: self.applied,
1588 generation: self.core.generation(),
1589 render_update_generation: self.core.pending_update_generation(),
1590 }
1591 }
1592}
1593
1594#[derive(Clone, Default)]
1598struct FlushFlag(Arc<AtomicBool>);
1599
1600impl FlushFlag {
1601 fn waker(&self, queue: &CoreQueue, id: MapId) -> Waker {
1605 let (flag, queue) = (self.clone(), queue.downgrade());
1606 Arc::new(move || {
1607 if !flag.0.swap(true, Ordering::SeqCst)
1608 && let Some(queue) = queue.upgrade()
1609 {
1610 let flag = flag.clone();
1611 post(&queue, move |core, outbox| {
1612 if flag.is_set() {
1613 flush(core, id, outbox);
1614 }
1615 });
1616 }
1617 })
1618 }
1619
1620 fn is_set(&self) -> bool {
1621 self.0.load(Ordering::SeqCst)
1622 }
1623
1624 fn clear(&self) {
1625 self.0.store(false, Ordering::SeqCst);
1626 }
1627}
1628
1629pub(crate) fn create(
1631 core: &mut RuntimeCore,
1632 id: MapId,
1633 options: &MapOptions,
1634 published: Arc<Published>,
1635 resolver: Resolver<Applied>,
1636 outbox: &mut Outbox,
1637) {
1638 let registry = Arc::clone(core.registry.style());
1639 let mut map = match mln_map::Map::with_registry(Arc::clone(core.loader()), options.map, registry, &core.pool) {
1640 Ok(map) => map,
1641 Err(error) => return outbox.resolve(resolver, Err(error)),
1642 };
1643 if let Some(json) = &options.fallback_font_faces {
1644 if let Err(error) = map.set_fallback_font_faces(json) {
1645 return outbox.resolve(resolver, Err(error));
1646 }
1647 } else if options.system_fonts {
1648 map.set_fallback_font_face_list(mln_system_fonts::font_face().into_iter().collect());
1649 }
1650 let _ = published.updates.set(map.update_reader());
1651 let _ = published.frame_clock.set(map.frame_clock());
1652 let flush_pending = FlushFlag::default();
1653 map.set_reports_waker(Some(flush_pending.waker(&core.queue, id)));
1654 published.applied.store(1, Ordering::SeqCst);
1655 core.maps.insert(
1656 id,
1657 MapEntry {
1658 core: map,
1659 published,
1660 mask: options.event_mask,
1661 applied: 1,
1662 held_applied: None,
1663 held_sampled: None,
1664 pending_style: None,
1665 pending_still: None,
1666 session: None,
1667 flush_pending,
1668 camera_commands: HashMap::default(),
1669 callback_sources: CallbackSources::default(),
1670 geojson_updates: GeoJsonUpdates::default(),
1671 repaint: None,
1672 },
1673 );
1674 flush(core, id, outbox);
1675 if let Some(entry) = core.maps.get(&id) {
1676 outbox.resolve(resolver, Ok(entry.applied()));
1677 }
1678}
1679
1680pub(crate) fn apply_command<T>(
1688 core: &mut RuntimeCore,
1689 id: MapId,
1690 sequence: u64,
1691 outbox: &mut Outbox,
1692 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> T,
1693 after: impl FnOnce(&MapEntry, T, Applied, &mut Outbox),
1694) {
1695 if core.maps.get(&id).is_some_and(|entry| entry.flush_pending.is_set() || entry.core.has_reports()) {
1699 flush(core, id, outbox);
1700 }
1701 let Some(entry) = core.maps.get_mut(&id) else { return };
1702 let value = apply(entry, outbox);
1703 entry.applied = sequence;
1704 flush(core, id, outbox);
1705 let holding = core.holding_updates();
1706 let Some(entry) = core.maps.get_mut(&id) else { return };
1707 after(entry, value, entry.applied(), outbox);
1708 if holding {
1709 entry.held_applied = Some(sequence);
1710 } else {
1711 report_applied(entry, sequence);
1712 }
1713}
1714
1715fn report_applied(entry: &MapEntry, sequence: u64) {
1718 entry.published.applied.store(sequence, Ordering::SeqCst);
1719 if let Some(link) = &entry.session
1720 && sequence >= link.awaited.load(Ordering::SeqCst)
1721 {
1722 worker_post(&link.queue, move |worker, outbox| worker.map_applied(sequence, outbox));
1723 }
1724}
1725
1726fn report_sampled(entry: &MapEntry, sample: u64) {
1729 entry.published.sampled.fetch_max(sample, Ordering::SeqCst);
1730 if let Some(link) = &entry.session {
1731 worker_post(&link.queue, move |worker, outbox| worker.map_sampled(sample, outbox));
1732 }
1733}
1734
1735pub(crate) fn report_held(entry: &mut MapEntry) {
1738 if let Some(sequence) = entry.held_applied.take() {
1739 report_applied(entry, sequence);
1740 }
1741 if let Some(sample) = entry.held_sampled.take() {
1742 report_sampled(entry, sample);
1743 }
1744}
1745
1746fn sample_frame(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1749 let Some(entry) = core.maps.get(&id) else { return };
1750 entry.published.sample_queued.store(false, Ordering::SeqCst);
1752 let sample = entry.published.samples_requested.load(Ordering::SeqCst);
1753 if entry.flush_pending.is_set() || entry.core.has_reports() {
1754 flush(core, id, outbox);
1755 }
1756 let Some(entry) = core.maps.get_mut(&id) else { return };
1757 entry.core.sample_frame();
1758 flush(core, id, outbox);
1759 let holding = core.holding_updates();
1760 let Some(entry) = core.maps.get_mut(&id) else { return };
1761 if holding {
1762 entry.held_sampled = Some(sample);
1763 } else {
1764 report_sampled(entry, sample);
1765 }
1766}
1767
1768pub(crate) fn run_command<T, R: 'static>(
1771 core: &mut RuntimeCore,
1772 id: MapId,
1773 sequence: u64,
1774 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error>,
1775 finish: impl FnOnce(T, &MapEntry) -> R,
1776 resolver: Resolver<R>,
1777 outbox: &mut Outbox,
1778) {
1779 if !core.maps.contains_key(&id) {
1780 return outbox.resolve(resolver, Err(missing_map()));
1781 }
1782 apply_command(core, id, sequence, outbox, apply, move |entry, result, _, outbox| {
1783 outbox.resolve(resolver, result.map(|value| finish(value, entry)));
1784 });
1785}
1786
1787fn load_style(
1790 core: &mut RuntimeCore,
1791 id: MapId,
1792 sequence: u64,
1793 load: StyleLoad,
1794 resolver: Resolver<Applied>,
1795 outbox: &mut Outbox,
1796) {
1797 if !core.maps.contains_key(&id) {
1798 return outbox.resolve(resolver, Err(missing_map()));
1799 }
1800 apply_command(
1803 core,
1804 id,
1805 sequence,
1806 outbox,
1807 move |entry, outbox| {
1808 let from_json = matches!(load, StyleLoad::Json(_));
1809 if let Some(previous) = entry.pending_style.replace(PendingStyle { resolver, from_json }) {
1810 outbox.resolve(previous.resolver, Err(Error::cancelled("another style load started")));
1811 }
1812 match load {
1813 StyleLoad::Url(url) => entry.core.load_style_url(&url),
1814 StyleLoad::Json(json) => entry.core.load_style_json(&json),
1815 }
1816 },
1817 |_, (), _, _| {},
1818 );
1819}
1820
1821pub(crate) fn flush(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1826 let Some(entry) = core.maps.get_mut(&id) else { return };
1827 entry.flush_pending.clear();
1830 let events = entry.core.drain_events();
1831 let repaint_at = entry.core.repaint_at();
1832 if entry.repaint.as_ref().map(|(at, _)| *at) != repaint_at {
1833 if let Some((_, task)) = entry.repaint.take() {
1834 core.queue.cancel(task);
1835 }
1836 entry.repaint =
1837 repaint_at.map(|at| (at, post_at(&core.queue, at, move |core, outbox| repaint(core, id, outbox))));
1838 }
1839 crate::style::reconcile(entry, outbox);
1842 let generation = entry.core.generation();
1843 let ends: Vec<_> = entry
1845 .core
1846 .drain_command_ends()
1847 .filter_map(|end| Some((entry.camera_commands.remove(&end.command)?, TransitionEnd { generation, ..end.end })))
1848 .collect();
1849 let mut published = entry.published.snapshot.lock();
1852 if published.is_none_or(|snapshot| snapshot.generation != generation) {
1853 *published = Some(entry.core.snapshot());
1854 }
1855 drop(published);
1856
1857 let mut style_outcome = None;
1858 let from_json = entry.pending_style.as_ref().is_some_and(|pending| pending.from_json);
1859 for event in &events {
1860 match event {
1861 MapEvent::StyleLoaded => style_outcome = Some(Ok(())),
1862 MapEvent::LoadingFailed(StyleLoadError::Parse(message)) if from_json => {
1863 style_outcome = Some(Err(Error::invalid_argument(message)));
1864 }
1865 MapEvent::LoadingFailed(error) => style_outcome = Some(Err(Error::native(error.message()))),
1866 _ => {}
1867 }
1868 }
1869 let style_outcome = style_outcome.map(|outcome| (outcome, entry.pending_style.take(), entry.applied()));
1870 let still_outcome = match &mut entry.pending_still {
1871 Some(pending) => pending
1872 .refused
1873 .take()
1874 .or_else(|| entry.core.take_still_image().map(|result| result.map_err(still_image_error))),
1875 None => None,
1876 };
1877 let still = still_outcome.and_then(|outcome| Some((outcome, entry.pending_still.take()?.resolver)));
1878 let still_image = entry.pending_still.as_ref().and(entry.core.pending_still_image()).unwrap_or(0);
1881 if entry.published.still_image.swap(still_image, Ordering::SeqCst) != still_image
1882 && let Some(link) = &entry.session
1883 {
1884 worker_post(&link.queue, Worker::still_image_changed);
1885 }
1886
1887 let mask = entry.mask;
1888 let events: Vec<RuntimeEvent> = events
1889 .into_iter()
1890 .map(RuntimeEventKind::Map)
1891 .filter(|kind| mask.contains(kind.event_type()))
1892 .map(|kind| RuntimeEvent { source: EventSource::Map { id, generation }, kind })
1893 .collect();
1894 core.send_events(events, outbox);
1895 for (resolver, end) in ends {
1896 outbox.resolve(resolver, Ok(end));
1897 }
1898
1899 if let Some((outcome, Some(pending), applied)) = style_outcome {
1900 outbox.resolve(pending.resolver, outcome.map(|()| applied));
1901 }
1902 if let Some((outcome, resolver)) = still {
1903 outbox.resolve(resolver, outcome);
1904 }
1905}
1906
1907fn repaint(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1909 let Some(entry) = core.maps.get_mut(&id) else { return };
1910 entry.repaint = None;
1911 if entry.core.repaint_at().is_some() {
1912 entry.core.trigger_repaint();
1913 }
1914 flush(core, id, outbox);
1915}
1916
1917fn remove(core: &mut RuntimeCore, id: MapId, done: Option<Resolver<()>>, outbox: &mut Outbox) {
1919 flush(core, id, outbox);
1920 if let Some(mut entry) = core.maps.remove(&id) {
1921 if let Some((_, task)) = entry.repaint.take() {
1922 core.queue.cancel(task);
1923 }
1924 entry.core.set_waker(None);
1925 if let Some(pending) = entry.pending_style.take() {
1926 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1927 }
1928 if let Some(pending) = entry.pending_still.take() {
1929 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1930 }
1931 crate::style::release(&mut entry, outbox);
1932 entry.core.close_camera();
1935 for end in entry.core.drain_command_ends() {
1936 if let Some(resolver) = entry.camera_commands.remove(&end.command) {
1937 outbox.resolve(resolver, Ok(end.end));
1938 }
1939 }
1940 }
1941 if let Some(done) = done {
1942 outbox.resolve(done, Ok(()));
1943 }
1944}