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_glyph_rasterizer::{LocalGlyphRasterizer, 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 {
785 let rasterizer = self.shared.system_fonts.then(system_glyph_rasterizer);
786 LocalGlyphs { ideographs: self.shared.local_ideographs, rasterizer }
787 }
788
789 pub(crate) fn glyph_cache(&self) -> Arc<GlyphCache> {
790 Arc::clone(&self.shared.runtime.glyph_cache)
791 }
792
793 pub(crate) fn pool(&self) -> Pool {
795 self.shared.runtime.pool.clone()
796 }
797
798 pub(crate) fn font_face_engine(&self) -> Arc<dyn FontFaceEngine> {
800 Arc::clone(&self.shared.runtime.font_face_engine)
801 }
802
803 #[must_use]
808 pub fn registry(&self) -> &Arc<Registry> {
809 &self.shared.runtime.registry
810 }
811
812 pub(crate) fn claim_session(&self, id: SessionId, session: Weak<SessionShared>) -> Result<(), Error> {
814 let mut claim = self.shared.session.lock();
815 if self.shared.released.load(Ordering::SeqCst) {
816 return Err(released());
817 }
818 if claim.is_some() {
819 return Err(Error::invalid_state("the map already has an attached render session"));
820 }
821 *claim = Some(SessionClaim { id, session, removal: None });
822 Ok(())
823 }
824
825 pub(crate) fn release_session_claim(&self, id: SessionId) {
828 let claim = {
829 let mut session = self.shared.session.lock();
830 if session.as_ref().is_some_and(|claim| claim.id == id) { session.take() } else { None }
831 };
832 if let Some(removal) = claim.and_then(|claim| claim.removal) {
833 self.shared.remove(Some(removal));
834 }
835 }
836
837 pub(crate) fn bind_session(
842 &self,
843 id: SessionId,
844 queue: SessionQueue,
845 awaited: Arc<AtomicU64>,
846 size: Size,
847 ) -> Result<(), Error> {
848 let reply = SessionReply::new(queue.clone(), |worker, bound, outbox| match bound {
849 Ok((sequence, reader, events, published)) => worker.bound(sequence, reader, events, published, outbox),
850 Err(error) => worker.bind_failed(error, outbox),
851 });
852 let sent = self.shared.send(Some(drop), move |core, outbox, map_id, sequence, resolver: Resolver<()>| {
853 drop(resolver);
854 if !core.maps.contains_key(&map_id) {
855 return reply.send(Err(missing_map()));
856 }
857 let link = SessionLink { id, queue, awaited };
858 apply_command(
859 core,
860 map_id,
861 sequence,
862 outbox,
863 move |entry, _| {
864 entry.session = Some(link);
865 let resized = entry.core.set_size(size);
866 (resized, entry.core.update_reader(), entry.core.renderer_events(), Arc::clone(&entry.published))
867 },
868 move |_, (resized, reader, events, published), _, _| {
869 reply.send(resized.map(|()| (sequence, reader, events, published)));
870 },
871 );
872 });
873 sent.map(drop)
874 }
875
876 pub(crate) fn unbind_session(&self, id: SessionId) {
879 let map_id = self.shared.id;
880 self.shared.runtime.post_or((), move |core, _, ()| unbind(core, map_id, id), |()| {});
882 }
883
884 pub(crate) fn unbind_session_then(
887 &self,
888 id: SessionId,
889 queue: SessionQueue,
890 then: impl FnOnce(&mut Worker, &mut Outbox) + Send + 'static,
891 ) {
892 let map_id = self.shared.id;
893 let reply = SessionReply::new(queue, move |worker, _: Result<(), Error>, outbox| then(worker, outbox));
894 self.shared.runtime.post_or(
897 reply,
898 move |core, _, reply| {
899 unbind(core, map_id, id);
900 reply.send(Ok(()));
901 },
902 drop,
903 );
904 }
905
906 pub(crate) fn frame_demanded(&self) -> u64 {
912 let published = &self.shared.published;
913 if let Some(clock) = published.frame_clock.get() {
914 clock.set(Some(Instant::now()));
915 }
916 if self.shared.mode != MapMode::Continuous || !published.animating() {
919 return 0;
920 }
921 let sample = published.samples_requested.fetch_add(1, Ordering::SeqCst) + 1;
922 if !published.sample_queued.swap(true, Ordering::SeqCst) {
923 let id = self.shared.id;
924 self.shared.runtime.post_apart(move |core, outbox| sample_frame(core, id, outbox));
925 }
926 sample
927 }
928
929 pub(crate) fn resize_for_session(
933 &self,
934 size: Size,
935 scale_factor: f64,
936 queue: SessionQueue,
937 resize: impl FnOnce(&mut Worker, Result<Applied, Error>, &mut Outbox) + Send + 'static,
938 ) -> Result<(), Error> {
939 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
941 let reply = SessionReply::new(queue, resize);
942 let sent = self.shared.send(Some(drop), move |core, outbox, id, sequence, resolver: Resolver<()>| {
943 drop(resolver);
944 if !core.maps.contains_key(&id) {
945 return reply.send(Err(missing_map()));
946 }
947 apply_command(
948 core,
949 id,
950 sequence,
951 outbox,
952 move |entry, _| {
953 let pixel_ratio = scale_factor as f32;
957 let extent = entry.core.snapshot().view.extent;
958 if extent.size == size && extent.scale_factor == f64::from(pixel_ratio) {
959 return Ok(());
960 }
961 entry.core.set_size(size)?;
962 entry.core.set_pixel_ratio(pixel_ratio)
963 },
964 move |_, resized, applied, _| reply.send(resized.map(|()| applied)),
965 );
966 });
967 sent.map(drop)
968 }
969
970 pub fn set_feature_state(
991 &self,
992 selector: &FeatureStateSelector,
993 state: FeatureState,
994 ) -> Result<Completion<Applied>, Error> {
995 let key = selector.key(true)?;
996 self.command(move |map| {
997 let feature_id = key.feature_id.as_deref().unwrap_or_default();
998 map.set_feature_state(&key.source_id, Some(&key.source_layer_id), feature_id, state);
999 Ok(())
1000 })
1001 }
1002
1003 pub fn feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<FeatureState>, Error> {
1007 let key = selector.key(true)?;
1008 self.query(move |map| {
1009 let feature_id = key.feature_id.as_deref().unwrap_or_default();
1010 Ok(map.feature_state(&key.source_id, Some(&key.source_layer_id), feature_id))
1011 })
1012 }
1013
1014 pub fn remove_feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<Applied>, Error> {
1022 let key = selector.key(false)?;
1023 self.command(move |map| {
1024 map.remove_feature_state(
1025 &key.source_id,
1026 Some(&key.source_layer_id),
1027 key.feature_id.as_deref(),
1028 key.state_key.as_deref(),
1029 );
1030 Ok(())
1031 })
1032 }
1033
1034 pub fn set_style_url(&self, url: impl Into<String>) -> Result<Completion<Applied>, Error> {
1046 let url = url.into();
1047 if url.is_empty() {
1048 return Err(Error::invalid_argument("style URL must not be empty"));
1049 }
1050 self.load_style(StyleLoad::Url(url))
1051 }
1052
1053 pub fn set_style_json(&self, json: impl Into<String>) -> Result<Completion<Applied>, Error> {
1059 let json = json.into();
1060 if json.is_empty() {
1061 return Err(Error::invalid_argument("style JSON must not be empty"));
1062 }
1063 self.load_style(StyleLoad::Json(json))
1064 }
1065
1066 fn load_style(&self, load: StyleLoad) -> Result<Completion<Applied>, Error> {
1067 self.post(move |core, outbox, id, sequence, resolver| {
1068 load_style(core, id, sequence, load, resolver, outbox);
1069 })
1070 }
1071
1072 pub fn loaded_style_json(&self) -> Result<Completion<String>, Error> {
1075 self.query(|map| Ok(map.style().get_json().to_owned()))
1076 }
1077
1078 pub fn style_url(&self) -> Result<Completion<Option<String>>, Error> {
1080 self.query(|map| Ok(map.style_url().filter(|url| !url.is_empty()).map(str::to_owned)))
1081 }
1082
1083 pub fn add_style_source_json(
1086 &self,
1087 source_id: impl Into<String>,
1088 json: impl Into<String>,
1089 ) -> Result<Completion<Applied>, Error> {
1090 let (source_id, json) = (source_id.into(), json.into());
1091 self.command(move |map| map.add_source_json(&source_id, &json))
1092 }
1093
1094 pub fn remove_style_source(&self, source_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1101 let source_id = source_id.into();
1102 self.send(
1103 move |entry, _| {
1104 let map = &mut entry.core;
1105 if !map.style_document_loaded() {
1106 return Err(style_not_loaded());
1107 }
1108 if map.source(&source_id).is_none() {
1109 return Err(Error::not_found(format!("source \"{source_id}\" does not exist")));
1110 }
1111 if let Some(layer) = map.style().get_layers().find(|layer| layer.get_source_id() == source_id) {
1112 let message = format!("source \"{source_id}\" is used by layer \"{}\"", layer.get_id());
1113 return Err(Error::invalid_state(message));
1114 }
1115 map.remove_source(&source_id);
1116 entry.core.remove_source_feature_state(&source_id);
1117 Ok(())
1118 },
1119 |(), entry| entry.applied(),
1120 )
1121 }
1122
1123 pub fn add_style_layer_json(
1126 &self,
1127 json: impl Into<String>,
1128 before_layer_id: Option<String>,
1129 ) -> Result<Completion<Applied>, Error> {
1130 let json = json.into();
1131 self.command(move |map| map.edit_loaded_style(|style| style.add_layer_json(&json, before_layer_id.as_deref())))
1132 }
1133
1134 pub fn add_custom_layer(
1139 &self,
1140 layer_id: impl Into<String>,
1141 host: Arc<dyn CustomLayerHost>,
1142 before_layer_id: Option<String>,
1143 ) -> Result<Completion<Applied>, Error> {
1144 let layer_id = layer_id.into();
1145 self.command(move |map| {
1146 map.edit_loaded_style(|style| style.add_custom_layer(&layer_id, host, before_layer_id.as_deref()))
1147 })
1148 }
1149
1150 pub fn remove_style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1155 let layer_id = layer_id.into();
1156 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::RemoveLayer(layer_id))))
1157 }
1158
1159 pub fn style_layer_json(&self, layer_id: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1162 let layer_id = layer_id.into();
1163 self.query(move |map| Ok(map.style().layer_json(&layer_id)))
1164 }
1165
1166 pub fn set_style_layer_property(
1169 &self,
1170 layer_id: impl Into<String>,
1171 name: impl Into<String>,
1172 json: impl Into<String>,
1173 ) -> Result<Completion<Applied>, Error> {
1174 let (layer_id, name, json) = (layer_id.into(), name.into(), json.into());
1175 self.command(move |map| map.edit_loaded_style(|style| style.set_layer_property_json(&layer_id, &name, &json)))
1176 }
1177
1178 pub fn style_layer_property(
1181 &self,
1182 layer_id: impl Into<String>,
1183 name: impl Into<String>,
1184 ) -> Result<Completion<Option<String>>, Error> {
1185 let (layer_id, name) = (layer_id.into(), name.into());
1186 self.query(move |map| map.style().layer_property_json(&layer_id, &name))
1187 }
1188
1189 pub fn set_style_root_property(
1193 &self,
1194 name: impl Into<String>,
1195 json: impl Into<String>,
1196 ) -> Result<Completion<Applied>, Error> {
1197 let (name, json) = (name.into(), json.into());
1198 self.command(move |map| map.edit_loaded_style(|style| style.set_root_property_json(&name, &json)))
1199 }
1200
1201 pub fn style_root_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1204 let name = name.into();
1205 self.query(move |map| map.style().root_property_json(&name))
1206 }
1207
1208 pub fn set_style_light_property(
1210 &self,
1211 name: impl Into<String>,
1212 json: impl Into<String>,
1213 ) -> Result<Completion<Applied>, Error> {
1214 let (name, json) = (name.into(), json.into());
1215 self.command(move |map| map.edit_loaded_style(|style| style.set_light_property_json(&name, &json)))
1216 }
1217
1218 pub fn style_light_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1221 let name = name.into();
1222 self.query(move |map| Ok(map.style().light_property_json(&name)))
1223 }
1224
1225 fn camera_command(
1230 &self,
1231 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1232 ) -> Result<Completion<Applied>, Error> {
1233 self.send_camera(apply, None)
1234 }
1235
1236 fn camera_command_then(
1241 &self,
1242 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1243 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1244 ) -> Result<Completion<Applied>, Error> {
1245 let (ended, end) = self.shared.runtime.completion();
1246 ended.on_complete(on_end);
1247 self.send_camera(apply, Some(end))
1248 }
1249
1250 fn send_camera(
1253 &self,
1254 apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1255 end: Option<Resolver<TransitionEnd>>,
1256 ) -> Result<Completion<Applied>, Error> {
1257 self.send(
1258 move |entry, outbox| match (apply(&mut entry.core), end) {
1259 (Ok(command), Some(end)) => {
1260 entry.camera_commands.insert(command, end);
1261 Ok(())
1262 }
1263 (Ok(_), None) => Ok(()),
1264 (Err(error), end) => {
1265 if let Some(end) = end {
1266 let generation = entry.core.generation();
1267 let cancelled =
1268 TransitionEnd { outcome: TransitionOutcome::Cancelled, generation, ..Default::default() };
1269 outbox.resolve(end, Ok(cancelled));
1270 }
1271 Err(error)
1272 }
1273 },
1274 |(), entry| entry.applied(),
1275 )
1276 }
1277
1278 pub fn update_camera(&self, update: CameraUpdate) -> Result<Completion<Applied>, Error> {
1280 self.camera_command(move |map| Ok(map.update_camera(&update)))
1281 }
1282
1283 pub fn update_camera_then(
1293 &self,
1294 update: CameraUpdate,
1295 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1296 ) -> Result<Completion<Applied>, Error> {
1297 self.camera_command_then(move |map| Ok(map.update_camera(&update)), on_end)
1298 }
1299
1300 pub fn apply_camera_delta(&self, delta: CameraDelta) -> Result<Completion<Applied>, Error> {
1304 self.camera_command(move |map| {
1305 map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string()))
1306 })
1307 }
1308
1309 pub fn apply_camera_delta_then(
1313 &self,
1314 delta: CameraDelta,
1315 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1316 ) -> Result<Completion<Applied>, Error> {
1317 self.camera_command_then(
1318 move |map| map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string())),
1319 on_end,
1320 )
1321 }
1322
1323 pub fn camera_for(
1330 &self,
1331 area: CameraFitArea,
1332 options: CameraFitOptions,
1333 ) -> Result<Completion<CameraOptions>, Error> {
1334 self.query(move |map| camera::camera_for(map, &area, &options))
1335 }
1336
1337 pub fn fit_camera(&self, area: CameraFitArea, update: CameraFitUpdate) -> Result<Completion<Applied>, Error> {
1344 self.camera_command(move |map| fit(map, &area, update))
1345 }
1346
1347 pub fn fit_camera_then(
1351 &self,
1352 area: CameraFitArea,
1353 update: CameraFitUpdate,
1354 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1355 ) -> Result<Completion<Applied>, Error> {
1356 self.camera_command_then(move |map| fit(map, &area, update), on_end)
1357 }
1358
1359 pub fn cancel_camera_transitions(&self) -> Result<Completion<Applied>, Error> {
1361 self.command(|map| {
1362 map.cancel_transitions();
1363 Ok(())
1364 })
1365 }
1366
1367 pub fn cancel_camera_transitions_with_id(&self, transition_id: u64) -> Result<Completion<Applied>, Error> {
1369 self.command(move |map| {
1370 map.cancel_transitions_with_id(transition_id);
1371 Ok(())
1372 })
1373 }
1374
1375 pub fn camera(&self) -> Result<Completion<CameraQuery>, Error> {
1377 self.send(
1378 |_, _| Ok(()),
1379 |(), entry| CameraQuery { generation: entry.core.generation(), camera: entry.core.snapshot().view.camera },
1380 )
1381 }
1382
1383 pub fn lat_lng_bounds_for_camera(&self, camera: CameraOptions) -> Result<Completion<LatLngBounds>, Error> {
1388 self.query(move |map| map.lat_lng_bounds_for_camera_unwrapped(&camera))
1389 }
1390
1391 pub fn set_bounds(&self, bounds: BoundOptions) -> Result<Completion<Applied>, Error> {
1393 self.command(move |map| map.set_bounds(&bounds))
1394 }
1395
1396 pub fn set_free_camera_options(&self, camera: FreeCameraOptions) -> Result<Completion<Applied>, Error> {
1398 self.command(move |map| {
1399 map.set_free_camera_options(&camera);
1400 Ok(())
1401 })
1402 }
1403
1404 pub fn set_viewport_options(&self, options: ViewportOptions) -> Result<Completion<Applied>, Error> {
1406 self.command(move |map| {
1407 camera::set_viewport(map, &options);
1408 Ok(())
1409 })
1410 }
1411
1412 pub fn set_tile_options(&self, options: TileOptions) -> Result<Completion<Applied>, Error> {
1414 self.command(move |map| {
1415 camera::set_tile_options(map, &options);
1416 Ok(())
1417 })
1418 }
1419
1420 pub fn set_projection_mode(&self, mode: ProjectionMode) -> Result<Completion<Applied>, Error> {
1421 self.command(move |map| {
1422 map.set_projection_mode(&mode);
1423 Ok(())
1424 })
1425 }
1426
1427 pub fn set_debug_flags(&self, flags: MapDebugOptions) -> Result<Completion<Applied>, Error> {
1429 self.command(move |map| {
1430 map.set_debug(flags);
1431 Ok(())
1432 })
1433 }
1434
1435 pub fn set_rendering_stats_view_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1437 self.command(move |map| {
1438 map.enable_rendering_stats_view(enabled);
1439 Ok(())
1440 })
1441 }
1442
1443 pub fn set_globe_free_bearing_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1446 self.command(move |map| {
1447 map.set_globe_free_bearing(enabled);
1448 Ok(())
1449 })
1450 }
1451
1452 pub fn dump_debug_logs(&self) -> Result<Completion<Applied>, Error> {
1454 self.command(|map| {
1455 map.dump_debug_logs();
1456 Ok(())
1457 })
1458 }
1459}
1460
1461#[must_use = "the group ends when it drops"]
1463pub struct CommandGroup {
1464 map: Option<Map>,
1465}
1466
1467impl CommandGroup {
1468 pub fn end(mut self) -> Result<Completion<Applied>, Error> {
1470 match self.map.take() {
1471 Some(map) => map.end_command_group(),
1472 None => Err(Error::invalid_state("the group ended already")),
1473 }
1474 }
1475}
1476
1477impl Drop for CommandGroup {
1478 fn drop(&mut self) {
1479 if let Some(map) = self.map.take() {
1480 let _ = map.end_command_group();
1481 }
1482 }
1483}
1484
1485enum StyleLoad {
1486 Url(String),
1487 Json(String),
1488}
1489
1490struct PendingStyle {
1492 resolver: Resolver<Applied>,
1493 from_json: bool,
1496}
1497
1498struct SessionClaim {
1500 id: SessionId,
1501 session: Weak<SessionShared>,
1502 removal: Option<Resolver<()>>,
1504}
1505
1506fn unbind(core: &mut RuntimeCore, map_id: MapId, id: SessionId) {
1509 if let Some(entry) = core.maps.get_mut(&map_id)
1510 && entry.session.as_ref().is_some_and(|link| link.id == id)
1511 {
1512 entry.session = None;
1513 }
1514}
1515
1516pub(crate) struct SessionLink {
1518 id: SessionId,
1519 queue: SessionQueue,
1520 awaited: Arc<AtomicU64>,
1522}
1523
1524struct PendingStill {
1527 resolver: Resolver<()>,
1528 refused: Option<Result<(), Error>>,
1531}
1532
1533fn still_image_error(error: Error) -> Error {
1536 match error.kind {
1537 ErrorKind::InvalidState => error,
1538 _ => Error::native(error.message),
1539 }
1540}
1541
1542pub(crate) struct MapEntry {
1544 pub(crate) core: mln_map::Map,
1545 published: Arc<Published>,
1546 mask: EventMask,
1547 applied: u64,
1549 held_applied: Option<u64>,
1552 held_sampled: Option<u64>,
1553 pending_style: Option<PendingStyle>,
1555 pending_still: Option<PendingStill>,
1556 session: Option<SessionLink>,
1558 flush_pending: FlushFlag,
1560 camera_commands: HashMap<CameraCommandId, Resolver<TransitionEnd>>,
1562 pub(crate) callback_sources: CallbackSources,
1564 pub(crate) geojson_updates: GeoJsonUpdates,
1566 repaint: Option<(Instant, TimedTask)>,
1569}
1570
1571impl MapEntry {
1572 pub(crate) fn applied(&self) -> Applied {
1573 Applied {
1574 sequence: self.applied,
1575 generation: self.core.generation(),
1576 render_update_generation: self.core.pending_update_generation(),
1577 }
1578 }
1579}
1580
1581#[derive(Clone, Default)]
1585struct FlushFlag(Arc<AtomicBool>);
1586
1587impl FlushFlag {
1588 fn waker(&self, queue: &CoreQueue, id: MapId) -> Waker {
1592 let (flag, queue) = (self.clone(), queue.downgrade());
1593 Arc::new(move || {
1594 if !flag.0.swap(true, Ordering::SeqCst)
1595 && let Some(queue) = queue.upgrade()
1596 {
1597 let flag = flag.clone();
1598 post(&queue, move |core, outbox| {
1599 if flag.is_set() {
1600 flush(core, id, outbox);
1601 }
1602 });
1603 }
1604 })
1605 }
1606
1607 fn is_set(&self) -> bool {
1608 self.0.load(Ordering::SeqCst)
1609 }
1610
1611 fn clear(&self) {
1612 self.0.store(false, Ordering::SeqCst);
1613 }
1614}
1615
1616#[cfg(not(target_family = "wasm"))]
1618fn system_glyph_rasterizer() -> Arc<dyn LocalGlyphRasterizer> {
1619 Arc::new(mln_system_fonts::SystemGlyphRasterizer)
1620}
1621
1622#[cfg(target_family = "wasm")]
1624fn system_glyph_rasterizer() -> Arc<dyn LocalGlyphRasterizer> {
1625 Arc::new(mln_text::browser_glyph_rasterizer::BrowserGlyphRasterizer::new("sans-serif".to_owned()))
1626}
1627
1628pub(crate) fn create(
1630 core: &mut RuntimeCore,
1631 id: MapId,
1632 options: &MapOptions,
1633 published: Arc<Published>,
1634 resolver: Resolver<Applied>,
1635 outbox: &mut Outbox,
1636) {
1637 let registry = Arc::clone(core.registry.style());
1638 let mut map = match mln_map::Map::with_registry(Arc::clone(core.loader()), options.map, registry, &core.pool) {
1639 Ok(map) => map,
1640 Err(error) => return outbox.resolve(resolver, Err(error)),
1641 };
1642 if let Some(json) = &options.fallback_font_faces {
1643 if let Err(error) = map.set_fallback_font_faces(json) {
1644 return outbox.resolve(resolver, Err(error));
1645 }
1646 } else if options.system_fonts {
1647 map.set_fallback_font_face_list(mln_system_fonts::font_face().into_iter().collect());
1648 }
1649 let _ = published.updates.set(map.update_reader());
1650 let _ = published.frame_clock.set(map.frame_clock());
1651 let flush_pending = FlushFlag::default();
1652 map.set_reports_waker(Some(flush_pending.waker(&core.queue, id)));
1653 published.applied.store(1, Ordering::SeqCst);
1654 core.maps.insert(
1655 id,
1656 MapEntry {
1657 core: map,
1658 published,
1659 mask: options.event_mask,
1660 applied: 1,
1661 held_applied: None,
1662 held_sampled: None,
1663 pending_style: None,
1664 pending_still: None,
1665 session: None,
1666 flush_pending,
1667 camera_commands: HashMap::default(),
1668 callback_sources: CallbackSources::default(),
1669 geojson_updates: GeoJsonUpdates::default(),
1670 repaint: None,
1671 },
1672 );
1673 flush(core, id, outbox);
1674 if let Some(entry) = core.maps.get(&id) {
1675 outbox.resolve(resolver, Ok(entry.applied()));
1676 }
1677}
1678
1679pub(crate) fn apply_command<T>(
1687 core: &mut RuntimeCore,
1688 id: MapId,
1689 sequence: u64,
1690 outbox: &mut Outbox,
1691 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> T,
1692 after: impl FnOnce(&MapEntry, T, Applied, &mut Outbox),
1693) {
1694 if core.maps.get(&id).is_some_and(|entry| entry.flush_pending.is_set() || entry.core.has_reports()) {
1698 flush(core, id, outbox);
1699 }
1700 let Some(entry) = core.maps.get_mut(&id) else { return };
1701 let value = apply(entry, outbox);
1702 entry.applied = sequence;
1703 flush(core, id, outbox);
1704 let holding = core.holding_updates();
1705 let Some(entry) = core.maps.get_mut(&id) else { return };
1706 after(entry, value, entry.applied(), outbox);
1707 if holding {
1708 entry.held_applied = Some(sequence);
1709 } else {
1710 report_applied(entry, sequence);
1711 }
1712}
1713
1714fn report_applied(entry: &MapEntry, sequence: u64) {
1717 entry.published.applied.store(sequence, Ordering::SeqCst);
1718 if let Some(link) = &entry.session
1719 && sequence >= link.awaited.load(Ordering::SeqCst)
1720 {
1721 worker_post(&link.queue, move |worker, outbox| worker.map_applied(sequence, outbox));
1722 }
1723}
1724
1725fn report_sampled(entry: &MapEntry, sample: u64) {
1728 entry.published.sampled.fetch_max(sample, Ordering::SeqCst);
1729 if let Some(link) = &entry.session {
1730 worker_post(&link.queue, move |worker, outbox| worker.map_sampled(sample, outbox));
1731 }
1732}
1733
1734pub(crate) fn report_held(entry: &mut MapEntry) {
1737 if let Some(sequence) = entry.held_applied.take() {
1738 report_applied(entry, sequence);
1739 }
1740 if let Some(sample) = entry.held_sampled.take() {
1741 report_sampled(entry, sample);
1742 }
1743}
1744
1745fn sample_frame(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1748 let Some(entry) = core.maps.get(&id) else { return };
1749 entry.published.sample_queued.store(false, Ordering::SeqCst);
1751 let sample = entry.published.samples_requested.load(Ordering::SeqCst);
1752 if entry.flush_pending.is_set() || entry.core.has_reports() {
1753 flush(core, id, outbox);
1754 }
1755 let Some(entry) = core.maps.get_mut(&id) else { return };
1756 entry.core.sample_frame();
1757 flush(core, id, outbox);
1758 let holding = core.holding_updates();
1759 let Some(entry) = core.maps.get_mut(&id) else { return };
1760 if holding {
1761 entry.held_sampled = Some(sample);
1762 } else {
1763 report_sampled(entry, sample);
1764 }
1765}
1766
1767pub(crate) fn run_command<T, R: 'static>(
1770 core: &mut RuntimeCore,
1771 id: MapId,
1772 sequence: u64,
1773 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error>,
1774 finish: impl FnOnce(T, &MapEntry) -> R,
1775 resolver: Resolver<R>,
1776 outbox: &mut Outbox,
1777) {
1778 if !core.maps.contains_key(&id) {
1779 return outbox.resolve(resolver, Err(missing_map()));
1780 }
1781 apply_command(core, id, sequence, outbox, apply, move |entry, result, _, outbox| {
1782 outbox.resolve(resolver, result.map(|value| finish(value, entry)));
1783 });
1784}
1785
1786fn load_style(
1789 core: &mut RuntimeCore,
1790 id: MapId,
1791 sequence: u64,
1792 load: StyleLoad,
1793 resolver: Resolver<Applied>,
1794 outbox: &mut Outbox,
1795) {
1796 if !core.maps.contains_key(&id) {
1797 return outbox.resolve(resolver, Err(missing_map()));
1798 }
1799 apply_command(
1802 core,
1803 id,
1804 sequence,
1805 outbox,
1806 move |entry, outbox| {
1807 let from_json = matches!(load, StyleLoad::Json(_));
1808 if let Some(previous) = entry.pending_style.replace(PendingStyle { resolver, from_json }) {
1809 outbox.resolve(previous.resolver, Err(Error::cancelled("another style load started")));
1810 }
1811 match load {
1812 StyleLoad::Url(url) => entry.core.load_style_url(&url),
1813 StyleLoad::Json(json) => entry.core.load_style_json(&json),
1814 }
1815 },
1816 |_, (), _, _| {},
1817 );
1818}
1819
1820pub(crate) fn flush(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1825 let Some(entry) = core.maps.get_mut(&id) else { return };
1826 entry.flush_pending.clear();
1829 let events = entry.core.drain_events();
1830 let repaint_at = entry.core.repaint_at();
1831 if entry.repaint.as_ref().map(|(at, _)| *at) != repaint_at {
1832 if let Some((_, task)) = entry.repaint.take() {
1833 core.queue.cancel(task);
1834 }
1835 entry.repaint =
1836 repaint_at.map(|at| (at, post_at(&core.queue, at, move |core, outbox| repaint(core, id, outbox))));
1837 }
1838 crate::style::reconcile(entry, outbox);
1841 let generation = entry.core.generation();
1842 let ends: Vec<_> = entry
1844 .core
1845 .drain_command_ends()
1846 .filter_map(|end| Some((entry.camera_commands.remove(&end.command)?, TransitionEnd { generation, ..end.end })))
1847 .collect();
1848 let mut published = entry.published.snapshot.lock();
1851 if published.is_none_or(|snapshot| snapshot.generation != generation) {
1852 *published = Some(entry.core.snapshot());
1853 }
1854 drop(published);
1855
1856 let mut style_outcome = None;
1857 let from_json = entry.pending_style.as_ref().is_some_and(|pending| pending.from_json);
1858 for event in &events {
1859 match event {
1860 MapEvent::StyleLoaded => style_outcome = Some(Ok(())),
1861 MapEvent::LoadingFailed(StyleLoadError::Parse(message)) if from_json => {
1862 style_outcome = Some(Err(Error::invalid_argument(message)));
1863 }
1864 MapEvent::LoadingFailed(error) => style_outcome = Some(Err(Error::native(error.message()))),
1865 _ => {}
1866 }
1867 }
1868 let style_outcome = style_outcome.map(|outcome| (outcome, entry.pending_style.take(), entry.applied()));
1869 let still_outcome = match &mut entry.pending_still {
1870 Some(pending) => pending
1871 .refused
1872 .take()
1873 .or_else(|| entry.core.take_still_image().map(|result| result.map_err(still_image_error))),
1874 None => None,
1875 };
1876 let still = still_outcome.and_then(|outcome| Some((outcome, entry.pending_still.take()?.resolver)));
1877 let still_image = entry.pending_still.as_ref().and(entry.core.pending_still_image()).unwrap_or(0);
1880 if entry.published.still_image.swap(still_image, Ordering::SeqCst) != still_image
1881 && let Some(link) = &entry.session
1882 {
1883 worker_post(&link.queue, Worker::still_image_changed);
1884 }
1885
1886 let mask = entry.mask;
1887 let events: Vec<RuntimeEvent> = events
1888 .into_iter()
1889 .map(RuntimeEventKind::Map)
1890 .filter(|kind| mask.contains(kind.event_type()))
1891 .map(|kind| RuntimeEvent { source: EventSource::Map { id, generation }, kind })
1892 .collect();
1893 core.send_events(events, outbox);
1894 for (resolver, end) in ends {
1895 outbox.resolve(resolver, Ok(end));
1896 }
1897
1898 if let Some((outcome, Some(pending), applied)) = style_outcome {
1899 outbox.resolve(pending.resolver, outcome.map(|()| applied));
1900 }
1901 if let Some((outcome, resolver)) = still {
1902 outbox.resolve(resolver, outcome);
1903 }
1904}
1905
1906fn repaint(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1908 let Some(entry) = core.maps.get_mut(&id) else { return };
1909 entry.repaint = None;
1910 if entry.core.repaint_at().is_some() {
1911 entry.core.trigger_repaint();
1912 }
1913 flush(core, id, outbox);
1914}
1915
1916fn remove(core: &mut RuntimeCore, id: MapId, done: Option<Resolver<()>>, outbox: &mut Outbox) {
1918 flush(core, id, outbox);
1919 if let Some(mut entry) = core.maps.remove(&id) {
1920 if let Some((_, task)) = entry.repaint.take() {
1921 core.queue.cancel(task);
1922 }
1923 entry.core.set_waker(None);
1924 if let Some(pending) = entry.pending_style.take() {
1925 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1926 }
1927 if let Some(pending) = entry.pending_still.take() {
1928 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1929 }
1930 crate::style::release(&mut entry, outbox);
1931 entry.core.close_camera();
1934 for end in entry.core.drain_command_ends() {
1935 if let Some(resolver) = entry.camera_commands.remove(&end.command) {
1936 outbox.resolve(resolver, Ok(end.end));
1937 }
1938 }
1939 }
1940 if let Some(done) = done {
1941 outbox.resolve(done, Ok(()));
1942 }
1943}