1use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::{Arc, OnceLock, Weak};
5
6use mln_engine::camera::{
7 BoundOptions, Camera, CameraCommandId, CameraDelta, CameraFitOptions, CameraOptions, CameraUpdate, Elevation,
8 FrameClock, FreeCameraOptions, LogicalExtent, MapProjection, MapView, ProjectionMode, TransitionEnd,
9 TransitionOutcome, ViewProjection,
10};
11use mln_engine::exec::event_queue::Waker;
12use mln_engine::exec::pool::Pool;
13use mln_engine::exec::queue::TimedTask;
14use mln_engine::map::{MapEvent, MapMode, MapSnapshot};
15use mln_engine::text::GlyphCache;
16use mln_engine::text::font_face_engine::FontFaceEngine;
17use mln_engine::text::local_fonts::LocalGlyphs;
18use mln_engine::{Registry, UpdateReader};
19use mln_style::error::{Error, ErrorKind};
20use mln_style::geo::LatLngBounds;
21use mln_style::hash::HashMap;
22use mln_style::size::Size;
23use mln_style::time::Instant;
24use mln_style::types::ProjectionDefinition;
25use mln_style::{Edit, StyleLoadError};
26use parking_lot::Mutex;
27
28use crate::camera::{self, CameraFitArea, CameraFitUpdate, TileOptions, ViewportOptions};
29use crate::completion::{Completion, Resolver};
30use crate::event::{EventMask, EventSource, RuntimeEvent, RuntimeEventKind};
31use crate::feature_state::{FeatureState, FeatureStateSelector};
32use crate::render::{
33 Abandoner, AttachOptions, RenderSession, RenderTarget, SessionId, SessionQueue, SessionShared, Worker, worker_post,
34};
35use crate::runtime::{CoreQueue, Outbox, Runtime, RuntimeCore, RuntimeShared, post, post_at};
36use crate::style::{GeoJsonUpdates, HeldSources};
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
40pub struct MapId(pub u64);
41
42#[derive(Clone, Debug)]
44pub struct MapOptions {
45 pub map: mln_engine::map::MapOptions,
46 pub event_mask: EventMask,
48 pub fallback_font_faces: Option<String>,
54 pub system_fonts: bool,
66 pub local_ideographs: bool,
71 pub tile_cache_enabled: bool,
74}
75
76impl Default for MapOptions {
77 fn default() -> Self {
78 MapOptions {
79 map: mln_engine::map::MapOptions::default(),
80 event_mask: EventMask::default(),
81 fallback_font_faces: None,
82 system_fonts: true,
83 local_ideographs: true,
84 tile_cache_enabled: true,
85 }
86 }
87}
88
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct Applied {
92 pub sequence: u64,
95 pub generation: u64,
98 pub render_update_generation: u64,
101}
102
103fn fit(
105 map: &mut mln_engine::map::Map,
106 area: &CameraFitArea,
107 update: &CameraFitUpdate,
108) -> Result<CameraCommandId, Error> {
109 let CameraFitUpdate { mode, fit, animation } = *update;
110 let mut camera = camera::camera_for(map, area, &fit)?;
111 if fit.padding.is_none() && !map.center_stops_padding() {
114 camera.padding = None;
115 }
116 if fit.bearing.is_none() {
117 camera.bearing = None;
118 }
119 if fit.pitch.is_none() {
120 camera.pitch = None;
121 }
122 Ok(map.update_camera(&CameraUpdate { mode, camera, animation, ..CameraUpdate::default() }))
123}
124
125#[derive(Clone, Copy, Debug, PartialEq)]
127pub struct CameraQuery {
128 pub generation: u64,
129 pub camera: Camera,
130}
131
132pub(crate) struct Published {
134 state: Mutex<Option<PublishedState>>,
138 updates: OnceLock<UpdateReader>,
140 applied: AtomicU64,
143 frame_clock: OnceLock<FrameClock>,
146 samples_requested: AtomicU64,
149 sampled: AtomicU64,
150 sample_queued: AtomicBool,
153 event_mask: AtomicU64,
154 still_image: AtomicU64,
157}
158
159struct PublishedState {
161 snapshot: MapSnapshot,
162 ground: Option<Arc<dyn Elevation>>,
164}
165
166impl Published {
167 pub(crate) fn applied(&self) -> u64 {
170 self.applied.load(Ordering::SeqCst)
171 }
172
173 pub(crate) fn sampled(&self) -> u64 {
175 self.sampled.load(Ordering::SeqCst)
176 }
177
178 pub(crate) fn animating(&self) -> bool {
181 self.state.lock().as_ref().is_some_and(|state| state.snapshot.transition_in_progress)
182 }
183
184 pub(crate) fn pending_still_image(&self) -> u64 {
188 self.still_image.load(Ordering::SeqCst)
189 }
190
191 pub(crate) fn new(event_mask: EventMask) -> Self {
192 Published {
193 state: Mutex::new(None),
194 updates: OnceLock::new(),
195 applied: AtomicU64::new(0),
196 frame_clock: OnceLock::new(),
197 samples_requested: AtomicU64::new(0),
198 sampled: AtomicU64::new(0),
199 sample_queued: AtomicBool::new(false),
200 event_mask: AtomicU64::new(event_mask.bits()),
201 still_image: AtomicU64::new(0),
202 }
203 }
204}
205
206pub(crate) struct MapShared {
207 id: MapId,
208 runtime: Arc<RuntimeShared>,
209 mode: MapMode,
210 scale_factor: AtomicU64,
213 tile_cache_enabled: bool,
214 system_fonts: bool,
215 local_ideographs: bool,
216 session: Mutex<Option<SessionClaim>>,
219 sent: Mutex<u64>,
223 released: AtomicBool,
225 removed: AtomicBool,
227 published: Arc<Published>,
228}
229
230impl MapShared {
231 pub(crate) fn new(id: MapId, runtime: Arc<RuntimeShared>, options: &MapOptions, published: Arc<Published>) -> Self {
232 MapShared {
233 id,
234 runtime,
235 mode: options.map.map_mode,
236 scale_factor: AtomicU64::new(f64::from(options.map.pixel_ratio).to_bits()),
237 tile_cache_enabled: options.tile_cache_enabled,
238 system_fonts: options.system_fonts,
239 local_ideographs: options.local_ideographs,
240 session: Mutex::new(None),
241 sent: Mutex::new(1),
242 released: AtomicBool::new(false),
243 removed: AtomicBool::new(false),
244 published,
245 }
246 }
247
248 fn completion<R: Send + 'static>(&self, discard: Option<fn(Error)>) -> (Completion<R>, Resolver<R>) {
252 match discard {
253 Some(on_failure) => Completion::discarded(on_failure),
254 None => self.runtime.completion(),
255 }
256 }
257
258 pub(crate) fn send<R: Send + 'static>(
260 &self,
261 discard: Option<fn(Error)>,
262 command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
263 ) -> Result<Completion<R>, Error> {
264 let mut sent = self.sent.lock();
265 if self.released.load(Ordering::SeqCst) {
266 return Err(released());
267 }
268 self.runtime.check_running()?;
269 let (completion, resolver) = self.completion(discard);
270 let id = self.id;
271 *sent += 1;
272 let sequence = *sent;
273 self.runtime.post(move |core, outbox| command(core, outbox, id, sequence, resolver));
274 Ok(completion)
275 }
276
277 fn release(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
280 self.close()?;
281 self.remove(done);
282 Ok(())
283 }
284
285 fn close(&self) -> Result<(), Error> {
288 let _sent = self.sent.lock();
289 if self.released.swap(true, Ordering::SeqCst) {
290 return Err(released());
291 }
292 Ok(())
293 }
294
295 fn remove(&self, done: Option<Resolver<()>>) {
298 if self.removed.swap(true, Ordering::SeqCst) {
299 return;
300 }
301 let id = self.id;
302 self.runtime.post_or_stopped(
304 done,
305 move |core, outbox, done| remove(core, id, done, outbox),
306 |done| {
307 if let Some(done) = done {
308 done.resolve(Ok(()));
309 }
310 },
311 );
312 self.runtime.map_released();
313 }
314}
315
316impl Drop for MapShared {
317 fn drop(&mut self) {
318 let _ = self.close();
319 let deferred = self.session.get_mut().take().and_then(|claim| claim.removal);
320 self.remove(deferred);
321 }
322}
323
324#[derive(Clone)]
337pub struct Map {
338 pub(crate) shared: Arc<MapShared>,
339 discard: Option<fn(Error)>,
342}
343
344impl std::fmt::Debug for Map {
345 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346 f.debug_struct("Map").field("id", &self.shared.id).field("discards_results", &self.discard.is_some()).finish()
347 }
348}
349
350impl PartialEq for Map {
351 fn eq(&self, other: &Map) -> bool {
352 Arc::ptr_eq(&self.shared, &other.shared)
353 }
354}
355
356impl Eq for Map {}
357
358fn released() -> Error {
359 Error::invalid_state("the map was released")
360}
361
362pub(crate) fn style_not_loaded() -> Error {
363 Error::invalid_state("style is not loaded")
364}
365
366pub(crate) fn missing_map() -> Error {
369 Error::invalid_state("the map failed to be built or was released")
370}
371
372type Reply<T> = Box<dyn FnOnce(&mut Worker, Result<T, Error>, &mut Outbox) + Send>;
374
375struct SessionReply<T: Send + 'static> {
380 queue: SessionQueue,
381 reply: Option<Reply<T>>,
382}
383
384impl<T: Send + 'static> SessionReply<T> {
385 fn new(
386 queue: SessionQueue,
387 reply: impl FnOnce(&mut Worker, Result<T, Error>, &mut Outbox) + Send + 'static,
388 ) -> Self {
389 SessionReply { queue, reply: Some(Box::new(reply)) }
390 }
391
392 fn send(mut self, result: Result<T, Error>) {
393 if let Some(reply) = self.reply.take() {
394 worker_post(&self.queue, move |worker, outbox| reply(worker, result, outbox));
395 }
396 }
397}
398
399impl<T: Send + 'static> Drop for SessionReply<T> {
400 fn drop(&mut self) {
401 if let Some(reply) = self.reply.take() {
402 let error = Error::cancelled("the runtime stopped before the command ran");
403 worker_post(&self.queue, move |worker, outbox| reply(worker, Err(error), outbox));
404 }
405 }
406}
407
408impl Map {
409 pub(crate) fn new(shared: MapShared) -> Self {
410 Map { shared: Arc::new(shared), discard: None }
411 }
412
413 #[must_use]
418 pub fn discarding_results(&self, on_failure: fn(Error)) -> Map {
419 Map { shared: Arc::clone(&self.shared), discard: Some(on_failure) }
420 }
421
422 pub(crate) fn post<R: Send + 'static>(
425 &self,
426 command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
427 ) -> Result<Completion<R>, Error> {
428 self.shared.send(self.discard, command)
429 }
430
431 #[must_use]
432 pub fn id(&self) -> MapId {
433 self.shared.id
434 }
435
436 #[must_use]
438 pub fn mode(&self) -> MapMode {
439 self.shared.mode
440 }
441
442 #[must_use]
444 pub fn runtime(&self) -> Runtime {
445 Runtime { shared: Arc::clone(&self.shared.runtime) }
446 }
447
448 #[must_use]
450 pub fn sent_sequence(&self) -> u64 {
451 *self.shared.sent.lock()
452 }
453
454 #[must_use]
458 pub fn applied_sequence(&self) -> u64 {
459 self.shared.published.applied.load(Ordering::SeqCst)
460 }
461
462 pub fn snapshot(&self) -> Result<MapSnapshot, Error> {
472 let mut snapshot = self.published(|state| state.snapshot.clone())?;
473 if let Some(updates) = self.shared.published.updates.get() {
477 snapshot.update_generation = updates.generation();
478 }
479 Ok(snapshot)
480 }
481
482 pub fn projection(&self, view: Option<&MapView>) -> Result<MapProjection, Error> {
491 let (snapshot_view, ground) = self.published(|state| (state.snapshot.view.clone(), state.ground.clone()))?;
492 Ok(MapProjection::from_view(view.unwrap_or(&snapshot_view))?.with_ground(ground))
493 }
494
495 fn published<T>(&self, read: impl FnOnce(&PublishedState) -> T) -> Result<T, Error> {
499 if self.shared.released.load(Ordering::SeqCst) {
500 return Err(released());
501 }
502 self.shared.published.state.lock().as_ref().map(read).ok_or_else(|| Error::invalid_state("the map isn't built"))
503 }
504
505 #[must_use]
507 pub fn event_mask(&self) -> EventMask {
508 EventMask::from_bits(self.shared.published.event_mask.load(Ordering::SeqCst)).unwrap_or_default()
509 }
510
511 pub(crate) fn send<T: 'static, R: Send + 'static>(
514 &self,
515 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error> + Send + 'static,
516 finish: impl FnOnce(T, &MapEntry) -> R + Send + 'static,
517 ) -> Result<Completion<R>, Error> {
518 self.post(move |core, outbox, id, sequence, resolver| {
519 run_command(core, id, sequence, apply, finish, resolver, outbox);
520 })
521 }
522
523 pub(crate) fn command(
525 &self,
526 apply: impl FnOnce(&mut mln_engine::map::Map) -> Result<(), Error> + Send + 'static,
527 ) -> Result<Completion<Applied>, Error> {
528 self.send(move |entry, _| apply(&mut entry.core), |(), entry| entry.applied())
529 }
530
531 pub(crate) fn query<T: Send + 'static>(
533 &self,
534 read: impl FnOnce(&mut mln_engine::map::Map) -> Result<T, Error> + Send + 'static,
535 ) -> Result<Completion<T>, Error> {
536 self.send(move |entry, _| read(&mut entry.core), |value, _| value)
537 }
538
539 pub fn with_core<R: Send + 'static>(
544 &self,
545 f: impl FnOnce(&mut mln_engine::map::Map) -> R + Send + 'static,
546 ) -> Result<Completion<R>, Error> {
547 self.query(move |map| Ok(f(map)))
548 }
549
550 pub fn release(&self) -> Result<Completion<()>, Error> {
561 self.release_with(false)
562 }
563
564 pub fn dispose(&self) -> Result<Completion<()>, Error> {
576 self.release_with(true)
577 }
578
579 fn release_with(&self, in_any_state: bool) -> Result<Completion<()>, Error> {
580 let (completion, resolver) = self.shared.completion(self.discard);
581 let claimed = {
582 let mut claim = self.shared.session.lock();
583 match claim.as_mut() {
584 None => None,
585 Some(held) => match held.session.upgrade() {
586 Some(session) if session.is_released() => Some((held.id, Some(session))),
588 Some(_) if in_any_state => {
591 self.shared.close()?;
592 held.removal = Some(resolver);
593 return Ok(completion);
594 }
595 Some(_) => return Err(Error::invalid_state("map still has an attached render session")),
596 None => Some((held.id, None)),
598 },
599 }
600 };
601 if let Some((id, session)) = claimed {
602 if let Some(session) = session {
603 let _ = session.abandon(Abandoner::Library);
604 }
605 self.release_session_claim(id);
606 }
607 self.shared.release(Some(resolver))?;
608 Ok(completion)
609 }
610
611 pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
621 let LogicalExtent { size, scale_factor } = extent;
622 if self.shared.session.lock().is_some() {
623 return Err(Error::invalid_state("the map has a render session: resize the session instead"));
624 }
625 if size.is_empty() {
626 return Err(Error::invalid_argument("logical size dimensions must be positive"));
627 }
628 if !scale_factor.is_finite() || scale_factor <= 0.0 {
629 return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
630 }
631 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
633 self.command(move |map| {
634 if map.snapshot().view.extent.size != size {
635 map.set_size(size)?;
636 }
637 map.set_pixel_ratio(scale_factor as f32)
638 })
639 }
640
641 pub fn request_repaint(&self) -> Result<Completion<Applied>, Error> {
645 if self.shared.mode != MapMode::Continuous {
646 return Err(Error::invalid_state("map is not in continuous mode"));
647 }
648 self.command(|map| {
649 map.trigger_repaint();
650 Ok(())
651 })
652 }
653
654 pub fn begin_command_group(&self) -> Result<Completion<Applied>, Error> {
659 self.command(|map| {
660 map.begin_command_group();
661 Ok(())
662 })
663 }
664
665 pub fn end_command_group(&self) -> Result<Completion<Applied>, Error> {
669 self.command(mln_engine::map::Map::end_command_group)
670 }
671
672 pub fn command_group(&self) -> Result<CommandGroup, Error> {
675 drop(self.begin_command_group()?);
676 Ok(CommandGroup { map: Some(self.clone()) })
677 }
678
679 pub fn set_event_mask(&self, mask: EventMask) -> Result<Completion<Applied>, Error> {
681 self.send(
682 move |entry, _| {
683 if entry.mask != mask {
684 entry.mask = mask;
685 entry.published.event_mask.store(mask.bits(), Ordering::SeqCst);
686 entry.core.record_change();
687 }
688 Ok(())
689 },
690 |(), entry| entry.applied(),
691 )
692 }
693
694 pub fn attach(
721 &self,
722 target: RenderTarget,
723 options: AttachOptions,
724 ) -> Result<(RenderSession, Completion<()>), Error> {
725 crate::render::attach(self, target, options, |session, attached| (session.clone(), attached))
726 }
727
728 pub fn attach_then<R>(
740 &self,
741 target: RenderTarget,
742 options: AttachOptions,
743 then: impl FnOnce(&RenderSession, Completion<()>) -> R,
744 ) -> Result<R, Error> {
745 crate::render::attach(self, target, options, then)
746 }
747
748 pub fn request_still_image(&self) -> Result<Completion<()>, Error> {
773 if self.shared.mode == MapMode::Continuous {
774 return Err(Error::invalid_state("the map is not in static or tile mode"));
775 }
776 self.post(move |core, outbox, id, sequence, resolver| {
777 if !core.maps.contains_key(&id) {
778 return outbox.resolve(resolver, Err(missing_map()));
779 }
780 apply_command(
781 core,
782 id,
783 sequence,
784 outbox,
785 move |entry, outbox| {
786 if entry.pending_still.is_some() {
787 let error = Error::invalid_state("the map is rendering a still image already");
788 return outbox.resolve(resolver, Err(error));
789 }
790 if entry.core.command_group_depth() > 0 {
792 let error = Error::invalid_state("a still image can't render while a command group is open");
793 return outbox.resolve(resolver, Err(error));
794 }
795 let refused = entry.core.render_still().err().map(|error| Err(still_image_error(error)));
796 entry.pending_still = Some(PendingStill { resolver, refused });
797 },
798 |_, (), _, _| {},
799 );
800 })
801 }
802
803 pub(crate) fn is_released(&self) -> bool {
805 self.shared.released.load(Ordering::SeqCst)
806 }
807
808 pub(crate) fn runtime_thread(&self) -> std::thread::ThreadId {
809 self.shared.runtime.thread()
810 }
811
812 #[must_use]
817 pub fn scale_factor(&self) -> f64 {
818 f64::from_bits(self.shared.scale_factor.load(Ordering::SeqCst))
819 }
820
821 pub(crate) fn tile_cache_enabled(&self) -> bool {
822 self.shared.tile_cache_enabled
823 }
824
825 #[cfg(any(feature = "bench", feature = "testing"))]
827 pub(crate) fn hold_frame_clock(&self, time: Instant) {
828 if let Some(clock) = self.shared.published.frame_clock.get() {
829 clock.hold(Some(time));
830 }
831 }
832
833 pub(crate) fn tile_worker_instances(&self) -> usize {
836 self.shared.runtime.tile_worker_instances.load(Ordering::SeqCst)
837 }
838
839 pub(crate) fn local_glyphs(&self) -> LocalGlyphs {
845 let mut local = LocalGlyphs { ideographs: self.shared.local_ideographs, ..LocalGlyphs::default() };
846 if self.shared.system_fonts {
847 #[cfg(not(target_family = "wasm"))]
848 {
849 local.chooser = Some(Arc::new(mln_engine::text::system_fonts::SystemFonts));
850 }
851 #[cfg(target_family = "wasm")]
852 {
853 let font_family = "sans-serif".to_owned();
854 local.rasterizer = Some(Arc::new(
855 mln_engine::text::browser_glyph_rasterizer::BrowserGlyphRasterizer::new(font_family),
856 ));
857 }
858 }
859 local
860 }
861
862 pub(crate) fn glyph_cache(&self) -> Arc<GlyphCache> {
863 Arc::clone(&self.shared.runtime.glyph_cache)
864 }
865
866 pub(crate) fn pool(&self) -> Pool {
868 self.shared.runtime.pool.clone()
869 }
870
871 pub(crate) fn font_face_engine(&self) -> Arc<dyn FontFaceEngine> {
873 Arc::clone(&self.shared.runtime.font_face_engine)
874 }
875
876 #[must_use]
881 pub fn registry(&self) -> &Arc<Registry> {
882 &self.shared.runtime.registry
883 }
884
885 pub(crate) fn claim_session(&self, id: SessionId, session: Weak<SessionShared>) -> Result<(), Error> {
887 let mut claim = self.shared.session.lock();
888 if self.shared.released.load(Ordering::SeqCst) {
889 return Err(released());
890 }
891 if claim.is_some() {
892 return Err(Error::invalid_state("the map already has an attached render session"));
893 }
894 *claim = Some(SessionClaim { id, session, removal: None });
895 Ok(())
896 }
897
898 pub(crate) fn release_session_claim(&self, id: SessionId) {
901 let claim = {
902 let mut session = self.shared.session.lock();
903 if session.as_ref().is_some_and(|claim| claim.id == id) { session.take() } else { None }
904 };
905 if let Some(removal) = claim.and_then(|claim| claim.removal) {
906 self.shared.remove(Some(removal));
907 }
908 }
909
910 pub(crate) fn bind_session(
915 &self,
916 id: SessionId,
917 queue: SessionQueue,
918 awaited: Arc<AtomicU64>,
919 size: Size,
920 ) -> Result<(), Error> {
921 let reply = SessionReply::new(queue.clone(), |worker, bound, outbox| match bound {
922 Ok((sequence, reader, events, published)) => worker.bound(sequence, reader, events, published, outbox),
923 Err(error) => worker.bind_failed(error, outbox),
924 });
925 let sent = self.shared.send(Some(drop), move |core, outbox, map_id, sequence, resolver: Resolver<()>| {
926 drop(resolver);
927 if !core.maps.contains_key(&map_id) {
928 return reply.send(Err(missing_map()));
929 }
930 let link = SessionLink { id, queue, awaited };
931 apply_command(
932 core,
933 map_id,
934 sequence,
935 outbox,
936 move |entry, _| {
937 entry.session = Some(link);
938 let resized = entry.core.set_size(size);
939 (resized, entry.core.update_reader(), entry.core.renderer_events(), Arc::clone(&entry.published))
940 },
941 move |_, (resized, reader, events, published), _, _| {
942 reply.send(resized.map(|()| (sequence, reader, events, published)));
943 },
944 );
945 });
946 sent.map(drop)
947 }
948
949 pub(crate) fn unbind_session(&self, id: SessionId) {
952 let map_id = self.shared.id;
953 self.shared.runtime.post_or((), move |core, _, ()| unbind(core, map_id, id), |()| {});
955 }
956
957 pub(crate) fn unbind_session_then(
960 &self,
961 id: SessionId,
962 queue: SessionQueue,
963 then: impl FnOnce(&mut Worker, &mut Outbox) + Send + 'static,
964 ) {
965 let map_id = self.shared.id;
966 let reply = SessionReply::new(queue, move |worker, _: Result<(), Error>, outbox| then(worker, outbox));
967 self.shared.runtime.post_or(
970 reply,
971 move |core, _, reply| {
972 unbind(core, map_id, id);
973 reply.send(Ok(()));
974 },
975 drop,
976 );
977 }
978
979 pub(crate) fn frame_demanded(&self) -> u64 {
985 let published = &self.shared.published;
986 if let Some(clock) = published.frame_clock.get() {
987 clock.set(Some(Instant::now()));
988 }
989 if self.shared.mode != MapMode::Continuous || !published.animating() {
992 return 0;
993 }
994 let sample = published.samples_requested.fetch_add(1, Ordering::SeqCst) + 1;
995 if !published.sample_queued.swap(true, Ordering::SeqCst) {
996 let id = self.shared.id;
997 self.shared.runtime.post_apart(move |core, outbox| sample_frame(core, id, outbox));
998 }
999 sample
1000 }
1001
1002 pub(crate) fn resize_for_session(
1006 &self,
1007 size: Size,
1008 scale_factor: f64,
1009 queue: SessionQueue,
1010 resize: impl FnOnce(&mut Worker, Result<Applied, Error>, &mut Outbox) + Send + 'static,
1011 ) -> Result<(), Error> {
1012 self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
1014 let reply = SessionReply::new(queue, resize);
1015 let sent = self.shared.send(Some(drop), move |core, outbox, id, sequence, resolver: Resolver<()>| {
1016 drop(resolver);
1017 if !core.maps.contains_key(&id) {
1018 return reply.send(Err(missing_map()));
1019 }
1020 apply_command(
1021 core,
1022 id,
1023 sequence,
1024 outbox,
1025 move |entry, _| {
1026 let pixel_ratio = scale_factor as f32;
1030 let extent = entry.core.snapshot().view.extent;
1031 if extent.size == size && extent.scale_factor == f64::from(pixel_ratio) {
1032 return Ok(());
1033 }
1034 entry.core.set_size(size)?;
1035 entry.core.set_pixel_ratio(pixel_ratio)
1036 },
1037 move |_, resized, applied, _| reply.send(resized.map(|()| applied)),
1038 );
1039 });
1040 sent.map(drop)
1041 }
1042
1043 pub fn set_feature_state(
1064 &self,
1065 selector: &FeatureStateSelector,
1066 state: FeatureState,
1067 ) -> Result<Completion<Applied>, Error> {
1068 let key = selector.key(true)?;
1069 self.command(move |map| {
1070 let feature_id = key.feature_id.as_deref().unwrap_or_default();
1071 map.set_feature_state(&key.source_id, Some(&key.source_layer_id), feature_id, state);
1072 Ok(())
1073 })
1074 }
1075
1076 pub fn feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<FeatureState>, Error> {
1080 let key = selector.key(true)?;
1081 self.query(move |map| {
1082 let feature_id = key.feature_id.as_deref().unwrap_or_default();
1083 Ok(map.feature_state(&key.source_id, Some(&key.source_layer_id), feature_id))
1084 })
1085 }
1086
1087 pub fn remove_feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<Applied>, Error> {
1095 let key = selector.key(false)?;
1096 self.command(move |map| {
1097 map.remove_feature_state(
1098 &key.source_id,
1099 Some(&key.source_layer_id),
1100 key.feature_id.as_deref(),
1101 key.state_key.as_deref(),
1102 );
1103 Ok(())
1104 })
1105 }
1106
1107 pub fn set_style_url(&self, url: impl Into<String>) -> Result<Completion<Applied>, Error> {
1119 let url = url.into();
1120 if url.is_empty() {
1121 return Err(Error::invalid_argument("style URL must not be empty"));
1122 }
1123 self.load_style(StyleLoad::Url(url))
1124 }
1125
1126 pub fn set_style_json(&self, json: impl Into<String>) -> Result<Completion<Applied>, Error> {
1132 let json = json.into();
1133 if json.is_empty() {
1134 return Err(Error::invalid_argument("style JSON must not be empty"));
1135 }
1136 self.load_style(StyleLoad::Json(json))
1137 }
1138
1139 fn load_style(&self, load: StyleLoad) -> Result<Completion<Applied>, Error> {
1140 self.post(move |core, outbox, id, sequence, resolver| {
1141 load_style(core, id, sequence, load, resolver, outbox);
1142 })
1143 }
1144
1145 pub fn loaded_style_json(&self) -> Result<Completion<String>, Error> {
1148 self.query(|map| Ok(map.style().json().to_owned()))
1149 }
1150
1151 pub fn style_url(&self) -> Result<Completion<Option<String>>, Error> {
1153 self.query(|map| Ok(map.style_url().filter(|url| !url.is_empty()).map(str::to_owned)))
1154 }
1155
1156 pub fn add_style_source_json(
1159 &self,
1160 source_id: impl Into<String>,
1161 json: impl Into<String>,
1162 ) -> Result<Completion<Applied>, Error> {
1163 let (source_id, json) = (source_id.into(), json.into());
1164 self.command(move |map| map.add_source_json(&source_id, &json))
1165 }
1166
1167 pub fn remove_style_source(&self, source_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1174 let source_id = source_id.into();
1175 self.send(
1176 move |entry, _| {
1177 let map = &mut entry.core;
1178 if !map.style_document_loaded() {
1179 return Err(style_not_loaded());
1180 }
1181 if map.source(&source_id).is_none() {
1182 return Err(Error::not_found(format!("source \"{source_id}\" does not exist")));
1183 }
1184 if let Some(layer) = map.style().layers().find(|layer| layer.source_id() == source_id) {
1185 let message = format!("source \"{source_id}\" is used by layer \"{}\"", layer.id());
1186 return Err(Error::invalid_state(message));
1187 }
1188 map.remove_source(&source_id);
1189 entry.core.remove_source_feature_state(&source_id);
1190 Ok(())
1191 },
1192 |(), entry| entry.applied(),
1193 )
1194 }
1195
1196 pub fn add_style_layer_json(
1199 &self,
1200 json: impl Into<String>,
1201 before_layer_id: Option<String>,
1202 ) -> Result<Completion<Applied>, Error> {
1203 let json = json.into();
1204 self.command(move |map| map.edit_loaded_style(|style| style.add_layer_json(&json, before_layer_id.as_deref())))
1205 }
1206
1207 pub fn add_style_layer(
1213 &self,
1214 layer: mln_style::layer::Layer,
1215 before_layer_id: Option<String>,
1216 ) -> Result<Completion<Applied>, Error> {
1217 self.command(move |map| map.edit_loaded_style(|style| style.add_layer(layer, before_layer_id.as_deref())))
1218 }
1219
1220 pub fn remove_style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1225 let layer_id = layer_id.into();
1226 self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::RemoveLayer(layer_id))))
1227 }
1228
1229 pub fn style_layer_json(&self, layer_id: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1232 let layer_id = layer_id.into();
1233 self.query(move |map| Ok(map.style().layer_json(&layer_id)))
1234 }
1235
1236 pub fn set_style_layer_property(
1239 &self,
1240 layer_id: impl Into<String>,
1241 name: impl Into<String>,
1242 json: impl Into<String>,
1243 ) -> Result<Completion<Applied>, Error> {
1244 let (layer_id, name, json) = (layer_id.into(), name.into(), json.into());
1245 self.command(move |map| map.edit_loaded_style(|style| style.set_layer_property_json(&layer_id, &name, &json)))
1246 }
1247
1248 pub fn style_layer_property(
1251 &self,
1252 layer_id: impl Into<String>,
1253 name: impl Into<String>,
1254 ) -> Result<Completion<Option<String>>, Error> {
1255 let (layer_id, name) = (layer_id.into(), name.into());
1256 self.query(move |map| map.style().layer_property_json(&layer_id, &name))
1257 }
1258
1259 pub fn set_style_root_property(
1263 &self,
1264 name: impl Into<String>,
1265 json: impl Into<String>,
1266 ) -> Result<Completion<Applied>, Error> {
1267 let (name, json) = (name.into(), json.into());
1268 self.command(move |map| map.edit_loaded_style(|style| style.set_root_property_json(&name, &json)))
1269 }
1270
1271 pub fn style_root_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1274 let name = name.into();
1275 self.query(move |map| map.style().root_property_json(&name))
1276 }
1277
1278 pub fn set_style_light_property(
1280 &self,
1281 name: impl Into<String>,
1282 json: impl Into<String>,
1283 ) -> Result<Completion<Applied>, Error> {
1284 let (name, json) = (name.into(), json.into());
1285 self.command(move |map| map.edit_loaded_style(|style| style.set_light_property_json(&name, &json)))
1286 }
1287
1288 pub fn style_light_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1291 let name = name.into();
1292 self.query(move |map| Ok(map.style().light_property_json(&name)))
1293 }
1294
1295 fn camera_command(
1300 &self,
1301 apply: impl FnOnce(&mut mln_engine::map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1302 ) -> Result<Completion<Applied>, Error> {
1303 self.send_camera(apply, None)
1304 }
1305
1306 fn camera_command_then(
1311 &self,
1312 apply: impl FnOnce(&mut mln_engine::map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1313 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1314 ) -> Result<Completion<Applied>, Error> {
1315 let (ended, end) = self.shared.runtime.completion();
1316 ended.on_complete(on_end);
1317 self.send_camera(apply, Some(end))
1318 }
1319
1320 fn send_camera(
1323 &self,
1324 apply: impl FnOnce(&mut mln_engine::map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1325 end: Option<Resolver<TransitionEnd>>,
1326 ) -> Result<Completion<Applied>, Error> {
1327 self.send(
1328 move |entry, outbox| match (apply(&mut entry.core), end) {
1329 (Ok(command), Some(end)) => {
1330 entry.camera_commands.insert(command, end);
1331 Ok(())
1332 }
1333 (Ok(_), None) => Ok(()),
1334 (Err(error), end) => {
1335 if let Some(end) = end {
1336 let generation = entry.core.generation();
1337 let cancelled =
1338 TransitionEnd { outcome: TransitionOutcome::Cancelled, generation, ..Default::default() };
1339 outbox.resolve(end, Ok(cancelled));
1340 }
1341 Err(error)
1342 }
1343 },
1344 |(), entry| entry.applied(),
1345 )
1346 }
1347
1348 pub fn update_camera(&self, update: CameraUpdate) -> Result<Completion<Applied>, Error> {
1350 self.camera_command(move |map| Ok(map.update_camera(&update)))
1351 }
1352
1353 pub fn update_camera_then(
1363 &self,
1364 update: CameraUpdate,
1365 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1366 ) -> Result<Completion<Applied>, Error> {
1367 self.camera_command_then(move |map| Ok(map.update_camera(&update)), on_end)
1368 }
1369
1370 pub fn apply_camera_delta(&self, delta: CameraDelta) -> Result<Completion<Applied>, Error> {
1374 self.camera_command(move |map| {
1375 map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string()))
1376 })
1377 }
1378
1379 pub fn apply_camera_delta_then(
1383 &self,
1384 delta: CameraDelta,
1385 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1386 ) -> Result<Completion<Applied>, Error> {
1387 self.camera_command_then(
1388 move |map| map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string())),
1389 on_end,
1390 )
1391 }
1392
1393 pub fn camera_for(
1400 &self,
1401 area: CameraFitArea,
1402 options: CameraFitOptions,
1403 ) -> Result<Completion<CameraOptions>, Error> {
1404 self.query(move |map| camera::camera_for(map, &area, &options))
1405 }
1406
1407 pub fn fit_camera(&self, area: CameraFitArea, update: CameraFitUpdate) -> Result<Completion<Applied>, Error> {
1414 self.camera_command(move |map| fit(map, &area, &update))
1415 }
1416
1417 pub fn fit_camera_then(
1421 &self,
1422 area: CameraFitArea,
1423 update: CameraFitUpdate,
1424 on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1425 ) -> Result<Completion<Applied>, Error> {
1426 self.camera_command_then(move |map| fit(map, &area, &update), on_end)
1427 }
1428
1429 pub fn cancel_camera_transitions(&self) -> Result<Completion<Applied>, Error> {
1431 self.command(|map| {
1432 map.cancel_transitions();
1433 Ok(())
1434 })
1435 }
1436
1437 pub fn cancel_camera_transitions_with_id(&self, transition_id: u64) -> Result<Completion<Applied>, Error> {
1439 self.command(move |map| {
1440 map.cancel_transitions_with_id(transition_id);
1441 Ok(())
1442 })
1443 }
1444
1445 pub fn camera(&self) -> Result<Completion<CameraQuery>, Error> {
1447 self.send(
1448 |_, _| Ok(()),
1449 |(), entry| CameraQuery { generation: entry.core.generation(), camera: entry.core.snapshot().view.camera },
1450 )
1451 }
1452
1453 pub fn lat_lng_bounds_for_camera(&self, camera: CameraOptions) -> Result<Completion<LatLngBounds>, Error> {
1458 self.query(move |map| map.lat_lng_bounds_for_camera_unwrapped(&camera))
1459 }
1460
1461 pub fn set_bounds(&self, bounds: BoundOptions) -> Result<Completion<Applied>, Error> {
1463 self.command(move |map| map.set_bounds(&bounds))
1464 }
1465
1466 pub fn set_free_camera_options(&self, camera: FreeCameraOptions) -> Result<Completion<Applied>, Error> {
1468 self.command(move |map| {
1469 map.set_free_camera_options(&camera);
1470 Ok(())
1471 })
1472 }
1473
1474 pub fn set_viewport_options(&self, options: ViewportOptions) -> Result<Completion<Applied>, Error> {
1476 self.command(move |map| {
1477 camera::set_viewport(map, &options);
1478 Ok(())
1479 })
1480 }
1481
1482 pub fn set_tile_options(&self, options: TileOptions) -> Result<Completion<Applied>, Error> {
1484 self.command(move |map| {
1485 camera::set_tile_options(map, &options);
1486 Ok(())
1487 })
1488 }
1489
1490 pub fn set_projection_mode(&self, mode: ProjectionMode) -> Result<Completion<Applied>, Error> {
1491 self.command(move |map| {
1492 map.set_projection_mode(&mode);
1493 Ok(())
1494 })
1495 }
1496
1497 pub fn dump_debug_logs(&self) -> Result<Completion<Applied>, Error> {
1499 self.command(|map| {
1500 map.dump_debug_logs();
1501 Ok(())
1502 })
1503 }
1504}
1505
1506#[must_use = "the group ends when it drops"]
1508pub struct CommandGroup {
1509 map: Option<Map>,
1510}
1511
1512impl CommandGroup {
1513 pub fn end(mut self) -> Result<Completion<Applied>, Error> {
1515 match self.map.take() {
1516 Some(map) => map.end_command_group(),
1517 None => Err(Error::invalid_state("the group ended already")),
1518 }
1519 }
1520}
1521
1522impl Drop for CommandGroup {
1523 fn drop(&mut self) {
1524 if let Some(map) = self.map.take() {
1525 let _ = map.end_command_group();
1526 }
1527 }
1528}
1529
1530enum StyleLoad {
1531 Url(String),
1532 Json(String),
1533}
1534
1535struct PendingStyle {
1537 resolver: Resolver<Applied>,
1538 from_json: bool,
1541}
1542
1543struct SessionClaim {
1545 id: SessionId,
1546 session: Weak<SessionShared>,
1547 removal: Option<Resolver<()>>,
1549}
1550
1551fn unbind(core: &mut RuntimeCore, map_id: MapId, id: SessionId) {
1554 if let Some(entry) = core.maps.get_mut(&map_id)
1555 && entry.session.as_ref().is_some_and(|link| link.id == id)
1556 {
1557 entry.session = None;
1558 }
1559}
1560
1561pub(crate) struct SessionLink {
1563 id: SessionId,
1564 queue: SessionQueue,
1565 awaited: Arc<AtomicU64>,
1567}
1568
1569struct PendingStill {
1572 resolver: Resolver<()>,
1573 refused: Option<Result<(), Error>>,
1576}
1577
1578fn still_image_error(error: Error) -> Error {
1581 match error.kind {
1582 ErrorKind::InvalidState => error,
1583 _ => Error::failed(error.message),
1584 }
1585}
1586
1587pub(crate) struct MapEntry {
1589 pub(crate) core: mln_engine::map::Map,
1590 published: Arc<Published>,
1591 mask: EventMask,
1592 applied: u64,
1594 held_applied: Option<u64>,
1597 held_sampled: Option<u64>,
1598 pending_style: Option<PendingStyle>,
1600 pending_still: Option<PendingStill>,
1601 session: Option<SessionLink>,
1603 flush_pending: FlushFlag,
1605 camera_commands: HashMap<CameraCommandId, Resolver<TransitionEnd>>,
1607 pub(crate) held_sources: HeldSources,
1609 pub(crate) geojson_updates: GeoJsonUpdates,
1611 repaint: Option<(Instant, TimedTask)>,
1614}
1615
1616impl MapEntry {
1617 pub(crate) fn applied(&self) -> Applied {
1618 Applied {
1619 sequence: self.applied,
1620 generation: self.core.generation(),
1621 render_update_generation: self.core.pending_update_generation(),
1622 }
1623 }
1624}
1625
1626#[derive(Clone, Default)]
1630struct FlushFlag(Arc<AtomicBool>);
1631
1632impl FlushFlag {
1633 fn waker(&self, queue: &CoreQueue, id: MapId) -> Waker {
1637 let (flag, queue) = (self.clone(), queue.downgrade());
1638 Arc::new(move || {
1639 if !flag.0.swap(true, Ordering::SeqCst)
1640 && let Some(queue) = queue.upgrade()
1641 {
1642 let flag = flag.clone();
1643 post(&queue, move |core, outbox| {
1644 if flag.is_set() {
1645 flush(core, id, outbox);
1646 }
1647 });
1648 }
1649 })
1650 }
1651
1652 fn is_set(&self) -> bool {
1653 self.0.load(Ordering::SeqCst)
1654 }
1655
1656 fn clear(&self) {
1657 self.0.store(false, Ordering::SeqCst);
1658 }
1659}
1660
1661pub(crate) fn create(
1663 core: &mut RuntimeCore,
1664 id: MapId,
1665 options: &MapOptions,
1666 published: Arc<Published>,
1667 resolver: Resolver<Applied>,
1668 outbox: &mut Outbox,
1669) {
1670 let registry = Arc::clone(&core.registry);
1671 let mut map =
1672 match mln_engine::map::Map::with_file_source(Arc::clone(core.loader()), options.map, registry, &core.pool) {
1673 Ok(map) => map,
1674 Err(error) => return outbox.resolve(resolver, Err(error)),
1675 };
1676 if let Some(json) = &options.fallback_font_faces {
1677 if let Err(error) = map.set_fallback_font_faces(json) {
1678 return outbox.resolve(resolver, Err(error));
1679 }
1680 } else if options.system_fonts {
1681 map.set_fallback_font_face_list(mln_engine::text::system_fonts::font_face().into_iter().collect());
1682 }
1683 let _ = published.updates.set(map.update_reader());
1684 let _ = published.frame_clock.set(map.frame_clock());
1685 let flush_pending = FlushFlag::default();
1686 map.set_reports_waker(Some(flush_pending.waker(&core.queue, id)));
1687 published.applied.store(1, Ordering::SeqCst);
1688 core.maps.insert(
1689 id,
1690 MapEntry {
1691 core: map,
1692 published,
1693 mask: options.event_mask,
1694 applied: 1,
1695 held_applied: None,
1696 held_sampled: None,
1697 pending_style: None,
1698 pending_still: None,
1699 session: None,
1700 flush_pending,
1701 camera_commands: HashMap::default(),
1702 held_sources: HeldSources::default(),
1703 geojson_updates: GeoJsonUpdates::default(),
1704 repaint: None,
1705 },
1706 );
1707 flush(core, id, outbox);
1708 if let Some(entry) = core.maps.get(&id) {
1709 outbox.resolve(resolver, Ok(entry.applied()));
1710 }
1711}
1712
1713pub(crate) fn apply_command<T>(
1721 core: &mut RuntimeCore,
1722 id: MapId,
1723 sequence: u64,
1724 outbox: &mut Outbox,
1725 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> T,
1726 after: impl FnOnce(&MapEntry, T, Applied, &mut Outbox),
1727) {
1728 if core.maps.get(&id).is_some_and(|entry| entry.flush_pending.is_set() || entry.core.has_reports()) {
1732 flush(core, id, outbox);
1733 }
1734 let Some(entry) = core.maps.get_mut(&id) else { return };
1735 let value = apply(entry, outbox);
1736 entry.applied = sequence;
1737 flush(core, id, outbox);
1738 let holding = core.holding_updates();
1739 let Some(entry) = core.maps.get_mut(&id) else { return };
1740 after(entry, value, entry.applied(), outbox);
1741 if holding {
1742 entry.held_applied = Some(sequence);
1743 } else {
1744 report_applied(entry, sequence);
1745 }
1746}
1747
1748fn report_applied(entry: &MapEntry, sequence: u64) {
1751 entry.published.applied.store(sequence, Ordering::SeqCst);
1752 if let Some(link) = &entry.session
1753 && sequence >= link.awaited.load(Ordering::SeqCst)
1754 {
1755 worker_post(&link.queue, move |worker, outbox| worker.map_applied(sequence, outbox));
1756 }
1757}
1758
1759fn report_sampled(entry: &MapEntry, sample: u64) {
1762 entry.published.sampled.fetch_max(sample, Ordering::SeqCst);
1763 if let Some(link) = &entry.session {
1764 worker_post(&link.queue, move |worker, outbox| worker.map_sampled(sample, outbox));
1765 }
1766}
1767
1768pub(crate) fn report_held(entry: &mut MapEntry) {
1771 if let Some(sequence) = entry.held_applied.take() {
1772 report_applied(entry, sequence);
1773 }
1774 if let Some(sample) = entry.held_sampled.take() {
1775 report_sampled(entry, sample);
1776 }
1777}
1778
1779fn sample_frame(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1782 let Some(entry) = core.maps.get(&id) else { return };
1783 entry.published.sample_queued.store(false, Ordering::SeqCst);
1785 let sample = entry.published.samples_requested.load(Ordering::SeqCst);
1786 if entry.flush_pending.is_set() || entry.core.has_reports() {
1787 flush(core, id, outbox);
1788 }
1789 let Some(entry) = core.maps.get_mut(&id) else { return };
1790 entry.core.sample_frame();
1791 flush(core, id, outbox);
1792 let holding = core.holding_updates();
1793 let Some(entry) = core.maps.get_mut(&id) else { return };
1794 if holding {
1795 entry.held_sampled = Some(sample);
1796 } else {
1797 report_sampled(entry, sample);
1798 }
1799}
1800
1801pub(crate) fn run_command<T, R: 'static>(
1804 core: &mut RuntimeCore,
1805 id: MapId,
1806 sequence: u64,
1807 apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error>,
1808 finish: impl FnOnce(T, &MapEntry) -> R,
1809 resolver: Resolver<R>,
1810 outbox: &mut Outbox,
1811) {
1812 if !core.maps.contains_key(&id) {
1813 return outbox.resolve(resolver, Err(missing_map()));
1814 }
1815 apply_command(core, id, sequence, outbox, apply, move |entry, result, _, outbox| {
1816 outbox.resolve(resolver, result.map(|value| finish(value, entry)));
1817 });
1818}
1819
1820fn load_style(
1823 core: &mut RuntimeCore,
1824 id: MapId,
1825 sequence: u64,
1826 load: StyleLoad,
1827 resolver: Resolver<Applied>,
1828 outbox: &mut Outbox,
1829) {
1830 if !core.maps.contains_key(&id) {
1831 return outbox.resolve(resolver, Err(missing_map()));
1832 }
1833 apply_command(
1836 core,
1837 id,
1838 sequence,
1839 outbox,
1840 move |entry, outbox| {
1841 let from_json = matches!(load, StyleLoad::Json(_));
1842 if let Some(previous) = entry.pending_style.replace(PendingStyle { resolver, from_json }) {
1843 outbox.resolve(previous.resolver, Err(Error::cancelled("another style load started")));
1844 }
1845 match load {
1846 StyleLoad::Url(url) => entry.core.load_style_url(&url),
1847 StyleLoad::Json(json) => entry.core.load_style_json(&json),
1848 }
1849 },
1850 |_, (), _, _| {},
1851 );
1852}
1853
1854pub(crate) fn flush(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1859 let Some(entry) = core.maps.get_mut(&id) else { return };
1860 entry.flush_pending.clear();
1863 let events = entry.core.drain_events();
1864 let repaint_at = entry.core.repaint_at().filter(|_| entry.core.frame_clock().held().is_none());
1867 if entry.repaint.as_ref().map(|(at, _)| *at) != repaint_at {
1868 if let Some((_, task)) = entry.repaint.take() {
1869 core.queue.cancel(task);
1870 }
1871 entry.repaint =
1872 repaint_at.map(|at| (at, post_at(&core.queue, at, move |core, outbox| repaint(core, id, outbox))));
1873 }
1874 crate::style::reconcile(entry, outbox);
1877 let generation = entry.core.generation();
1878 let ends: Vec<_> = entry
1880 .core
1881 .drain_command_ends()
1882 .filter_map(|end| Some((entry.camera_commands.remove(&end.command)?, TransitionEnd { generation, ..end.end })))
1883 .collect();
1884 let mut published = entry.published.state.lock();
1887 let snapshot = match &*published {
1888 Some(state) if state.snapshot.generation == generation => state.snapshot.clone(),
1889 _ => entry.core.snapshot(),
1890 };
1891 *published = Some(PublishedState { snapshot, ground: entry.core.ground() });
1894 drop(published);
1895
1896 let mut style_outcome = None;
1897 let from_json = entry.pending_style.as_ref().is_some_and(|pending| pending.from_json);
1898 for event in &events {
1899 match event {
1900 MapEvent::StyleLoaded => style_outcome = Some(Ok(())),
1901 MapEvent::LoadingFailed(StyleLoadError::Parse(message)) if from_json => {
1902 style_outcome = Some(Err(Error::invalid_argument(message)));
1903 }
1904 MapEvent::LoadingFailed(error) => style_outcome = Some(Err(Error::failed(error.message()))),
1905 _ => {}
1906 }
1907 }
1908 let style_outcome = style_outcome.map(|outcome| (outcome, entry.pending_style.take(), entry.applied()));
1909 let still_outcome = match &mut entry.pending_still {
1910 Some(pending) => pending
1911 .refused
1912 .take()
1913 .or_else(|| entry.core.take_still_image().map(|result| result.map_err(still_image_error))),
1914 None => None,
1915 };
1916 let still = still_outcome.and_then(|outcome| Some((outcome, entry.pending_still.take()?.resolver)));
1917 let still_image = entry.pending_still.as_ref().and(entry.core.pending_still_image()).unwrap_or(0);
1920 if entry.published.still_image.swap(still_image, Ordering::SeqCst) != still_image
1921 && let Some(link) = &entry.session
1922 {
1923 worker_post(&link.queue, Worker::still_image_changed);
1924 }
1925
1926 let mask = entry.mask;
1927 let events: Vec<RuntimeEvent> = events
1928 .into_iter()
1929 .map(RuntimeEventKind::Map)
1930 .filter(|kind| mask.contains(kind.event_type()))
1931 .map(|kind| RuntimeEvent { source: EventSource::Map { id, generation }, kind })
1932 .collect();
1933 core.send_events(events, outbox);
1934 for (resolver, end) in ends {
1935 outbox.resolve(resolver, Ok(end));
1936 }
1937
1938 if let Some((outcome, Some(pending), applied)) = style_outcome {
1939 outbox.resolve(pending.resolver, outcome.map(|()| applied));
1940 }
1941 if let Some((outcome, resolver)) = still {
1942 outbox.resolve(resolver, outcome);
1943 }
1944}
1945
1946fn repaint(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1948 let Some(entry) = core.maps.get_mut(&id) else { return };
1949 entry.repaint = None;
1950 if entry.core.repaint_at().is_some() && entry.core.frame_clock().held().is_none() {
1952 entry.core.trigger_repaint();
1953 }
1954 flush(core, id, outbox);
1955}
1956
1957fn remove(core: &mut RuntimeCore, id: MapId, done: Option<Resolver<()>>, outbox: &mut Outbox) {
1959 flush(core, id, outbox);
1960 if let Some(mut entry) = core.maps.remove(&id) {
1961 if let Some((_, task)) = entry.repaint.take() {
1962 core.queue.cancel(task);
1963 }
1964 entry.core.set_waker(None);
1965 if let Some(state) = &mut *entry.published.state.lock() {
1968 state.ground = None;
1969 state.snapshot.view.projection = ViewProjection::BuiltIn(ProjectionDefinition::default());
1970 }
1971 if let Some(pending) = entry.pending_style.take() {
1972 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1973 }
1974 if let Some(pending) = entry.pending_still.take() {
1975 outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1976 }
1977 crate::style::release(&mut entry, outbox);
1978 entry.core.close_camera();
1981 for end in entry.core.drain_command_ends() {
1982 if let Some(resolver) = entry.camera_commands.remove(&end.command) {
1983 outbox.resolve(resolver, Ok(end.end));
1984 }
1985 }
1986 }
1987 if let Some(done) = done {
1988 outbox.resolve(done, Ok(()));
1989 }
1990}