Skip to main content

mln_runtime/
map.rs

1//! A handle to a map that lives on its runtime's thread.
2
3use 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,
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::{Edit, StyleLoadError};
25use parking_lot::Mutex;
26
27use crate::camera::{self, CameraFitArea, 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::{GeoJsonUpdates, HeldSources};
36
37/// The ID of a map, unique within its runtime.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct MapId(pub u64);
40
41/// How to create a map.
42#[derive(Clone, Debug)]
43pub struct MapOptions {
44    pub map: mln_engine::map::MapOptions,
45    /// The events that the map reports.
46    pub event_mask: EventMask,
47    /// JSON text of the font faces that the map falls back to for the text
48    /// that the style's fonts don't draw, as `Map::set_fallback_font_faces`
49    /// takes it: the text that glyph PBFs can't shape, all the text of a
50    /// style without them, and the glyphs that come from local fonts, before
51    /// the system's. With it, the map shapes no text with the system's fonts.
52    pub fallback_font_faces: Option<String>,
53    /// Whether the map draws from the system's fonts what the style's fonts
54    /// and `fallback_font_faces` don't. It shapes with them the scripts that
55    /// glyph PBFs can't shape, and all the text of a style without PBFs
56    /// (`mln_engine::text::system_fonts::font_face`), from the fonts the labels'
57    /// `text-font` names first; and draws from them the glyphs a style's
58    /// PBFs lack, and with `local_ideographs`, CJK
59    /// (`mln_engine::text::system_fonts::SystemFonts`). On by default. The first map that
60    /// uses them waits for the platform's font matcher to load. In the
61    /// browser, which has no font files to read, the browser draws each
62    /// glyph of that text in the font stack's families, then its sans-serif
63    /// font, as MapLibre GL JS does, unshaped.
64    pub system_fonts: bool,
65    /// Whether CJK ideographs, kana and hangul come from local fonts (the
66    /// fallback font faces, then the system's) before glyph PBFs, as
67    /// MapLibre GL JS's `localIdeographFontFamily` draws them, rather than
68    /// downloading a glyph PBF for every few characters. On by default.
69    pub local_ideographs: bool,
70    /// Whether the map's render sessions keep tiles in memory after they
71    /// leave the view, so they show again without loading. On by default.
72    pub tile_cache_enabled: bool,
73}
74
75impl Default for MapOptions {
76    fn default() -> Self {
77        MapOptions {
78            map: mln_engine::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/// What a map command left behind once it ran.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct Applied {
91    /// The command's place among the map's commands: the map's creation is
92    /// 1, and each command takes the next number when it is sent.
93    pub sequence: u64,
94    /// The map's generation after the command: a snapshot with this
95    /// generation or a later one includes the command.
96    pub generation: u64,
97    /// The map's update generation after the command: a frame that renders
98    /// this update or a later one shows the command.
99    pub render_update_generation: u64,
100}
101
102/// Moves `map`'s camera to the one that fits `area`.
103fn fit(
104    map: &mut mln_engine::map::Map,
105    area: &CameraFitArea,
106    update: &CameraFitUpdate,
107) -> Result<CameraCommandId, Error> {
108    let CameraFitUpdate { mode, fit, animation } = *update;
109    let mut camera = camera::camera_for(map, area, &fit)?;
110    // A fit leaves running changes of the fields it keeps alone, but carries
111    // on a change of the padding that its center stops.
112    if fit.padding.is_none() && !map.center_stops_padding() {
113        camera.padding = None;
114    }
115    if fit.bearing.is_none() {
116        camera.bearing = None;
117    }
118    if fit.pitch.is_none() {
119        camera.pitch = None;
120    }
121    Ok(map.update_camera(&CameraUpdate { mode, camera, animation, ..CameraUpdate::default() }))
122}
123
124/// The camera, and the generation of the map that it belongs to.
125#[derive(Clone, Copy, Debug, PartialEq)]
126pub struct CameraQuery {
127    pub generation: u64,
128    pub camera: Camera,
129}
130
131/// What the runtime's thread publishes for a map's handles.
132pub(crate) struct Published {
133    /// The map's snapshot and its ground as of its last flush, `None` until
134    /// the map is built: one lock, so that a projection's view and ground
135    /// come from the same flush.
136    state: Mutex<Option<PublishedState>>,
137    /// The map's updates for its renderer, once the map is built.
138    updates: OnceLock<UpdateReader>,
139    /// The sequence number of the last command that ran and whose changes a
140    /// frame can show.
141    applied: AtomicU64,
142    /// The map's frame clock, once the map is built: each frame demand sets
143    /// it.
144    frame_clock: OnceLock<FrameClock>,
145    /// Whether the frame clock holds the time that the benchmarks set
146    /// (`bench::hold_frame_clock`), which frame demands leave as it is.
147    #[cfg(feature = "bench")]
148    frame_clock_held: AtomicBool,
149    /// The frame samples that demands asked for, numbered from 1, and the
150    /// last that the map took and a frame can show.
151    samples_requested: AtomicU64,
152    sampled: AtomicU64,
153    /// Whether a sample is on its way to the runtime's thread, which takes
154    /// the demands that ask meanwhile.
155    sample_queued: AtomicBool,
156    event_mask: AtomicU64,
157    /// The still image that waits for a frame, as the
158    /// `still_image_request_id` of the updates that ask for it, or 0.
159    still_image: AtomicU64,
160}
161
162/// The map's state as of a flush.
163struct PublishedState {
164    snapshot: MapSnapshot,
165    /// The ground the map draws (`mln_engine::map::Map::ground`).
166    ground: Option<Arc<dyn Elevation>>,
167}
168
169impl Published {
170    /// The sequence number of the last command that ran and whose changes a
171    /// frame can show.
172    pub(crate) fn applied(&self) -> u64 {
173        self.applied.load(Ordering::SeqCst)
174    }
175
176    /// The last frame sample that the map took and a frame can show.
177    pub(crate) fn sampled(&self) -> u64 {
178        self.sampled.load(Ordering::SeqCst)
179    }
180
181    /// Whether a camera command was still animating as of the map's last
182    /// published state.
183    pub(crate) fn animating(&self) -> bool {
184        self.state.lock().as_ref().is_some_and(|state| state.snapshot.transition_in_progress)
185    }
186
187    /// The still image that waits for a frame, as the
188    /// `still_image_request_id` of the updates that ask for it, or 0 when
189    /// none waits.
190    pub(crate) fn pending_still_image(&self) -> u64 {
191        self.still_image.load(Ordering::SeqCst)
192    }
193
194    pub(crate) fn new(event_mask: EventMask) -> Self {
195        Published {
196            state: Mutex::new(None),
197            updates: OnceLock::new(),
198            applied: AtomicU64::new(0),
199            frame_clock: OnceLock::new(),
200            #[cfg(feature = "bench")]
201            frame_clock_held: AtomicBool::new(false),
202            samples_requested: AtomicU64::new(0),
203            sampled: AtomicU64::new(0),
204            sample_queued: AtomicBool::new(false),
205            event_mask: AtomicU64::new(event_mask.bits()),
206            still_image: AtomicU64::new(0),
207        }
208    }
209}
210
211pub(crate) struct MapShared {
212    id: MapId,
213    runtime: Arc<RuntimeShared>,
214    mode: MapMode,
215    /// The map's scale factor, an `f64`'s bits: the options' pixel ratio,
216    /// until a session's resize sends another.
217    scale_factor: AtomicU64,
218    tile_cache_enabled: bool,
219    system_fonts: bool,
220    local_ideographs: bool,
221    /// The render session attached to the map, from its attach until its
222    /// detach completes.
223    session: Mutex<Option<SessionClaim>>,
224    /// The sequence number of the last command sent. It stays locked while
225    /// a command is numbered and posted, so the runtime's thread runs the
226    /// map's commands in the order of their numbers.
227    sent: Mutex<u64>,
228    /// Whether the handles refuse commands.
229    released: AtomicBool,
230    /// Whether the map's removal was posted to the runtime's thread.
231    removed: AtomicBool,
232    published: Arc<Published>,
233}
234
235impl MapShared {
236    pub(crate) fn new(id: MapId, runtime: Arc<RuntimeShared>, options: &MapOptions, published: Arc<Published>) -> Self {
237        MapShared {
238            id,
239            runtime,
240            mode: options.map.map_mode,
241            scale_factor: AtomicU64::new(f64::from(options.map.pixel_ratio).to_bits()),
242            tile_cache_enabled: options.tile_cache_enabled,
243            system_fonts: options.system_fonts,
244            local_ideographs: options.local_ideographs,
245            session: Mutex::new(None),
246            sent: Mutex::new(1),
247            released: AtomicBool::new(false),
248            removed: AtomicBool::new(false),
249            published,
250        }
251    }
252
253    /// A completion that the runtime's thread resolves, or with
254    /// `discard`, one whose result is discarded, as
255    /// [`Completion::discarded`] makes it.
256    fn completion<R: Send + 'static>(&self, discard: Option<fn(Error)>) -> (Completion<R>, Resolver<R>) {
257        match discard {
258            Some(on_failure) => Completion::discarded(on_failure),
259            None => self.runtime.completion(),
260        }
261    }
262
263    /// Numbers a command and posts it to the runtime's thread.
264    pub(crate) fn send<R: Send + 'static>(
265        &self,
266        discard: Option<fn(Error)>,
267        command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
268    ) -> Result<Completion<R>, Error> {
269        let mut sent = self.sent.lock();
270        if self.released.load(Ordering::SeqCst) {
271            return Err(released());
272        }
273        self.runtime.check_running()?;
274        let (completion, resolver) = self.completion(discard);
275        let id = self.id;
276        *sent += 1;
277        let sequence = *sent;
278        self.runtime.post(move |core, outbox| command(core, outbox, id, sequence, resolver));
279        Ok(completion)
280    }
281
282    /// Releases the map: no command is sent after its removal. Fails when
283    /// the map was released already.
284    fn release(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
285        self.close()?;
286        self.remove(done);
287        Ok(())
288    }
289
290    /// Refuses the commands sent from now on. Fails when the map was
291    /// released already.
292    fn close(&self) -> Result<(), Error> {
293        let _sent = self.sent.lock();
294        if self.released.swap(true, Ordering::SeqCst) {
295            return Err(released());
296        }
297        Ok(())
298    }
299
300    /// Removes the closed map from its runtime's thread, after the commands
301    /// sent before, once.
302    fn remove(&self, done: Option<Resolver<()>>) {
303        if self.removed.swap(true, Ordering::SeqCst) {
304            return;
305        }
306        let id = self.id;
307        // A runtime that a panic stopped let go of the map already.
308        self.runtime.post_or_stopped(
309            done,
310            move |core, outbox, done| remove(core, id, done, outbox),
311            |done| {
312                if let Some(done) = done {
313                    done.resolve(Ok(()));
314                }
315            },
316        );
317        self.runtime.map_released();
318    }
319}
320
321impl Drop for MapShared {
322    fn drop(&mut self) {
323        let _ = self.close();
324        let deferred = self.session.get_mut().take().and_then(|claim| claim.removal);
325        self.remove(deferred);
326    }
327}
328
329/// A handle to a map, which lives on its runtime's thread.
330///
331/// Each command takes the next sequence number when it is sent and runs on
332/// the runtime's thread after every command sent before it, to this map,
333/// another map or the runtime. It returns a [`Completion`] of its result, or
334/// an error when it can't be sent, and then never completes. A command sent
335/// before the map is built waits for it. `Clone` is another handle to the
336/// same map, and any thread may use one.
337///
338/// The map lives until [`release`](Self::release) or until its last handle
339/// drops. A command on a released map fails with
340/// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind).
341#[derive(Clone)]
342pub struct Map {
343    pub(crate) shared: Arc<MapShared>,
344    /// Where the failures of the handle's commands go when it discards
345    /// their results.
346    discard: Option<fn(Error)>,
347}
348
349impl std::fmt::Debug for Map {
350    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351        f.debug_struct("Map").field("id", &self.shared.id).field("discards_results", &self.discard.is_some()).finish()
352    }
353}
354
355impl PartialEq for Map {
356    fn eq(&self, other: &Map) -> bool {
357        Arc::ptr_eq(&self.shared, &other.shared)
358    }
359}
360
361impl Eq for Map {}
362
363fn released() -> Error {
364    Error::invalid_state("the map was released")
365}
366
367pub(crate) fn style_not_loaded() -> Error {
368    Error::invalid_state("style is not loaded")
369}
370
371/// The error of a command whose map failed to be built, or was released
372/// while the command was on its way.
373pub(crate) fn missing_map() -> Error {
374    Error::invalid_state("the map failed to be built or was released")
375}
376
377/// What a render session runs with the outcome of a command it waits for.
378type Reply<T> = Box<dyn FnOnce(&mut Worker, Result<T, Error>, &mut Outbox) + Send>;
379
380/// What a render session waits for from a command on the runtime's thread:
381/// `reply` runs on the session's thread with the command's outcome, or with
382/// an error if the command drops without one, as when a panic stopped the
383/// runtime.
384struct SessionReply<T: Send + 'static> {
385    queue: SessionQueue,
386    reply: Option<Reply<T>>,
387}
388
389impl<T: Send + 'static> SessionReply<T> {
390    fn new(
391        queue: SessionQueue,
392        reply: impl FnOnce(&mut Worker, Result<T, Error>, &mut Outbox) + Send + 'static,
393    ) -> Self {
394        SessionReply { queue, reply: Some(Box::new(reply)) }
395    }
396
397    fn send(mut self, result: Result<T, Error>) {
398        if let Some(reply) = self.reply.take() {
399            worker_post(&self.queue, move |worker, outbox| reply(worker, result, outbox));
400        }
401    }
402}
403
404impl<T: Send + 'static> Drop for SessionReply<T> {
405    fn drop(&mut self) {
406        if let Some(reply) = self.reply.take() {
407            let error = Error::cancelled("the runtime stopped before the command ran");
408            worker_post(&self.queue, move |worker, outbox| reply(worker, Err(error), outbox));
409        }
410    }
411}
412
413impl Map {
414    pub(crate) fn new(shared: MapShared) -> Self {
415        Map { shared: Arc::new(shared), discard: None }
416    }
417
418    /// A handle to the same map whose commands discard their results, for a
419    /// caller that doesn't need them: each command's completion acts as one
420    /// whose result was taken, and costs no allocation, and a failure,
421    /// cancellations included, goes to `on_failure` on the runtime's thread.
422    #[must_use]
423    pub fn discarding_results(&self, on_failure: fn(Error)) -> Map {
424        Map { shared: Arc::clone(&self.shared), discard: Some(on_failure) }
425    }
426
427    /// Numbers a command and posts it to the runtime's thread, with a
428    /// completion as the handle makes them.
429    pub(crate) fn post<R: Send + 'static>(
430        &self,
431        command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
432    ) -> Result<Completion<R>, Error> {
433        self.shared.send(self.discard, command)
434    }
435
436    #[must_use]
437    pub fn id(&self) -> MapId {
438        self.shared.id
439    }
440
441    /// When the map renders, as its options set it.
442    #[must_use]
443    pub fn mode(&self) -> MapMode {
444        self.shared.mode
445    }
446
447    /// The runtime that the map lives on.
448    #[must_use]
449    pub fn runtime(&self) -> Runtime {
450        Runtime { shared: Arc::clone(&self.shared.runtime) }
451    }
452
453    /// The sequence number of the last command sent to the map.
454    #[must_use]
455    pub fn sent_sequence(&self) -> u64 {
456        *self.shared.sent.lock()
457    }
458
459    /// The sequence number of the last command that ran. While the
460    /// runtime's thread runs several queued commands as one burst, they
461    /// count once the frame that shows them all can.
462    #[must_use]
463    pub fn applied_sequence(&self) -> u64 {
464        self.shared.published.applied.load(Ordering::SeqCst)
465    }
466
467    /// The map's state after the last command that ran, without waiting for
468    /// the commands still on their way. To read the state after them, send a
469    /// command and read the snapshot once it completes, or use a query such
470    /// as [`camera`](Self::camera). Its `update_generation` counts the
471    /// renderer's updates as they are when it is read, which can be later
472    /// than the rest of the state.
473    ///
474    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) until the
475    /// map is built, and after it is released.
476    pub fn snapshot(&self) -> Result<MapSnapshot, Error> {
477        let mut snapshot = self.published(|state| state.snapshot)?;
478        // The map publishes an update, which the renderer may draw at once,
479        // before it copies the snapshot: count the updates as they are now, so
480        // a frame never shows a later update than the snapshot.
481        if let Some(updates) = self.shared.published.updates.get() {
482            snapshot.update_generation = updates.generation();
483        }
484        Ok(snapshot)
485    }
486
487    /// A projection of `view`, or of the map's view as of
488    /// [`snapshot`](Self::snapshot) for `None`, on the ground the map drew
489    /// then (`mln_engine::map::Map::ground`): it converts as the map does, over
490    /// terrain on the ground the renderer drew, else on the flat map. It is
491    /// the caller's, and doesn't follow the map.
492    ///
493    /// Fails as [`snapshot`](Self::snapshot) does, and for `view` as
494    /// [`MapView::to_state`](mln_engine::camera::MapView::to_state).
495    pub fn projection(&self, view: Option<&MapView>) -> Result<MapProjection, Error> {
496        let (snapshot_view, ground) = self.published(|state| (state.snapshot.view, state.ground.clone()))?;
497        Ok(MapProjection::from_view(view.unwrap_or(&snapshot_view))?.with_ground(ground))
498    }
499
500    /// What `read` takes from the map's last flush. Fails with
501    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) until the map is
502    /// built, and after it is released.
503    fn published<T>(&self, read: impl FnOnce(&PublishedState) -> T) -> Result<T, Error> {
504        if self.shared.released.load(Ordering::SeqCst) {
505            return Err(released());
506        }
507        self.shared.published.state.lock().as_ref().map(read).ok_or_else(|| Error::invalid_state("the map isn't built"))
508    }
509
510    /// The events that the map reports, as of the last command that ran.
511    #[must_use]
512    pub fn event_mask(&self) -> EventMask {
513        EventMask::from_bits(self.shared.published.event_mask.load(Ordering::SeqCst)).unwrap_or_default()
514    }
515
516    /// Sends a command that runs `apply` on the map's entry, and completes
517    /// with what `finish` makes of its result and the map after it.
518    pub(crate) fn send<T: 'static, R: Send + 'static>(
519        &self,
520        apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error> + Send + 'static,
521        finish: impl FnOnce(T, &MapEntry) -> R + Send + 'static,
522    ) -> Result<Completion<R>, Error> {
523        self.post(move |core, outbox, id, sequence, resolver| {
524            run_command(core, id, sequence, apply, finish, resolver, outbox);
525        })
526    }
527
528    /// A command that changes the map.
529    pub(crate) fn command(
530        &self,
531        apply: impl FnOnce(&mut mln_engine::map::Map) -> Result<(), Error> + Send + 'static,
532    ) -> Result<Completion<Applied>, Error> {
533        self.send(move |entry, _| apply(&mut entry.core), |(), entry| entry.applied())
534    }
535
536    /// A command that reads the map.
537    pub(crate) fn query<T: Send + 'static>(
538        &self,
539        read: impl FnOnce(&mut mln_engine::map::Map) -> Result<T, Error> + Send + 'static,
540    ) -> Result<Completion<T>, Error> {
541        self.send(move |entry, _| read(&mut entry.core), |value, _| value)
542    }
543
544    /// Runs `f` on the map itself, on the runtime's thread, in its place
545    /// among the map's commands. It sees the effects of the commands sent
546    /// before it. The map handles what `f` changed, and reports its events,
547    /// before the completion.
548    pub fn with_core<R: Send + 'static>(
549        &self,
550        f: impl FnOnce(&mut mln_engine::map::Map) -> R + Send + 'static,
551    ) -> Result<Completion<R>, Error> {
552        self.query(move |map| Ok(f(map)))
553    }
554
555    /// Releases the map. The completion reports when the runtime has let go
556    /// of it. A render session that was released, but hasn't let go of the
557    /// map yet, is abandoned, as
558    /// [`RenderSession::abandon`](crate::RenderSession::abandon) does: a
559    /// caller-driven one that the host stopped servicing would otherwise
560    /// hold the map for good.
561    ///
562    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the
563    /// map was released already, or while a render session that wasn't
564    /// released is attached to it.
565    pub fn release(&self) -> Result<Completion<()>, Error> {
566        self.release_with(false)
567    }
568
569    /// Releases the map whatever its state, as dropping its last handle
570    /// does, and lets the runtime finish in the background: the completion
571    /// reports when the runtime has let go of it, and may be dropped. Every
572    /// command fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
573    /// from now on. A render session that is attached and wasn't released
574    /// keeps drawing the map's last update, and the runtime lets go of the
575    /// map once the session detaches or is abandoned. A released one is
576    /// abandoned, as [`release`](Self::release) does.
577    ///
578    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the
579    /// map was released already.
580    pub fn dispose(&self) -> Result<Completion<()>, Error> {
581        self.release_with(true)
582    }
583
584    fn release_with(&self, in_any_state: bool) -> Result<Completion<()>, Error> {
585        let (completion, resolver) = self.shared.completion(self.discard);
586        let claimed = {
587            let mut claim = self.shared.session.lock();
588            match claim.as_mut() {
589                None => None,
590                Some(held) => match held.session.upgrade() {
591                    // Abandoned now, or ended already and about to let go.
592                    Some(session) if session.is_released() => Some((held.id, Some(session))),
593                    // The session lets go of the map when it ends, and the
594                    // map is removed then.
595                    Some(_) if in_any_state => {
596                        self.shared.close()?;
597                        held.removal = Some(resolver);
598                        return Ok(completion);
599                    }
600                    Some(_) => return Err(Error::invalid_state("map still has an attached render session")),
601                    // The session is gone without letting go of the map.
602                    None => Some((held.id, None)),
603                },
604            }
605        };
606        if let Some((id, session)) = claimed {
607            if let Some(session) = session {
608                let _ = session.abandon(Abandoner::Library);
609            }
610            self.release_session_claim(id);
611        }
612        self.shared.release(Some(resolver))?;
613        Ok(completion)
614    }
615
616    // MARK: - Map
617
618    /// Sets the map's size and scale factor. The map keeps its tiles, and a
619    /// resize to the extent the map has changes nothing, so it renders
620    /// nothing. Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
621    /// while a render session is attached, since the session sizes the map
622    /// to its target: resize the session instead. Fails with
623    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an empty size,
624    /// or a scale factor that isn't finite and positive.
625    pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
626        let LogicalExtent { size, scale_factor } = extent;
627        if self.shared.session.lock().is_some() {
628            return Err(Error::invalid_state("the map has a render session: resize the session instead"));
629        }
630        if size.is_empty() {
631            return Err(Error::invalid_argument("logical size dimensions must be positive"));
632        }
633        if !scale_factor.is_finite() || scale_factor <= 0.0 {
634            return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
635        }
636        // The scale factor that a session attached later renders at.
637        self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
638        self.command(move |map| {
639            if map.snapshot().view.extent.size != size {
640                map.set_size(size)?;
641            }
642            map.set_pixel_ratio(scale_factor as f32)
643        })
644    }
645
646    /// Renders a new frame of a continuous map, even when nothing changed.
647    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a
648    /// static or tile map, which renders only still images.
649    pub fn request_repaint(&self) -> Result<Completion<Applied>, Error> {
650        if self.shared.mode != MapMode::Continuous {
651            return Err(Error::invalid_state("map is not in continuous mode"));
652        }
653        self.command(|map| {
654            map.trigger_repaint();
655            Ok(())
656        })
657    }
658
659    /// Holds the map's changes back from rendering until the matching
660    /// [`end_command_group`](Self::end_command_group), so that they show in
661    /// the same frame. Groups nest, and the changes show when the outermost
662    /// group ends.
663    pub fn begin_command_group(&self) -> Result<Completion<Applied>, Error> {
664        self.command(|map| {
665            map.begin_command_group();
666            Ok(())
667        })
668    }
669
670    /// Ends the group that [`begin_command_group`](Self::begin_command_group)
671    /// began. Completes with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
672    /// when no group is open.
673    pub fn end_command_group(&self) -> Result<Completion<Applied>, Error> {
674        self.command(mln_engine::map::Map::end_command_group)
675    }
676
677    /// Begins a command group that ends when the guard drops, or with
678    /// [`CommandGroup::end`].
679    pub fn command_group(&self) -> Result<CommandGroup, Error> {
680        drop(self.begin_command_group()?);
681        Ok(CommandGroup { map: Some(self.clone()) })
682    }
683
684    /// Selects the events that the map reports.
685    pub fn set_event_mask(&self, mask: EventMask) -> Result<Completion<Applied>, Error> {
686        self.send(
687            move |entry, _| {
688                if entry.mask != mask {
689                    entry.mask = mask;
690                    entry.published.event_mask.store(mask.bits(), Ordering::SeqCst);
691                    entry.core.record_change();
692                }
693                Ok(())
694            },
695            |(), entry| entry.applied(),
696        )
697    }
698
699    // MARK: - Rendering
700
701    /// Attaches a render session, which renders the map into `target`, and
702    /// sizes the map to the target. A map has one session at a time. The
703    /// session takes frame demands and other work at once, and runs them
704    /// once the completion reports it ready.
705    ///
706    /// The session renders on a thread of its own, or, with
707    /// [`Driver::CallerThread`](crate::Driver::CallerThread), on the thread
708    /// that takes its [`DriverWork`](crate::DriverWork): the attach completes
709    /// in that thread's first service.
710    ///
711    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the
712    /// map already has a session or was released, or a window is minimized
713    /// or has no client area, and with
714    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an empty
715    /// target, a [`Surface::wgpu`](crate::Surface::wgpu) without the
716    /// host's device, or a Win32 window with a pixel format of its own that
717    /// OpenGL would present to. The completion fails as
718    /// [`Device::new`](crate::Device::new) does when the
719    /// session has to create its device and can't, with
720    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the window or
721    /// surface had no area to present to by then, with
722    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when no GPU can present
723    /// to a window, and with [`ErrorKind::Native`](mln_style::error::ErrorKind) when
724    /// the window has no surface to give.
725    pub fn attach(
726        &self,
727        target: RenderTarget,
728        options: AttachOptions,
729    ) -> Result<(RenderSession, Completion<()>), Error> {
730        crate::render::attach(self, target, options, |session, attached| (session.clone(), attached))
731    }
732
733    /// Attaches a render session as [`attach`](Self::attach) does, and calls
734    /// `then` with it and the attach's completion before the session's
735    /// thread may deliver the attach's result. A callback that `then`
736    /// attaches with [`Completion::on_complete`] runs where the session
737    /// delivers it: on the session's thread, inside its driver call, even
738    /// when the session attaches before `then` runs. One attached after
739    /// `attach` returned would run at once on this thread instead.
740    ///
741    /// `then` keeps the session with a clone of it: the session is released
742    /// once its last handle drops. Fails as `attach` does, before `then`
743    /// runs.
744    pub fn attach_then<R>(
745        &self,
746        target: RenderTarget,
747        options: AttachOptions,
748        then: impl FnOnce(&RenderSession, Completion<()>) -> R,
749    ) -> Result<R, Error> {
750        crate::render::attach(self, target, options, then)
751    }
752
753    /// Renders a still image of a static or tile map, once every resource
754    /// that it needs has loaded. The map's render session draws it, and
755    /// [`RenderSession::read_texture`] reads its pixels once the completion
756    /// reports success.
757    ///
758    /// While the image waits, the session has a demand of its own for it,
759    /// whose [`FrameResult`](crate::FrameResult) has no token. The demand
760    /// waits for the map to load what the image needs, and parks while a
761    /// borrowed ring has no texture to render into. It finishes with the
762    /// image's frame, which completes the image once its result is queued:
763    /// a frame of the host's demands completes none. The host's demands
764    /// neither replace it nor are replaced by it. When the session ends its
765    /// demands, by a barrier, a target's release or a detach, the demand
766    /// ends too, and the image waits for the next one: once the barrier ran,
767    /// the target came back, or the next session attached.
768    ///
769    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a
770    /// continuous map. Completes with
771    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) while another image
772    /// is on its way or a command group is open,
773    /// [`ErrorKind::Native`](mln_style::error::ErrorKind) when the
774    /// style or a resource that the image needs fails to load, and
775    /// [`ErrorKind::Cancelled`](mln_style::error::ErrorKind) when the map is released
776    /// first.
777    pub fn request_still_image(&self) -> Result<Completion<()>, Error> {
778        if self.shared.mode == MapMode::Continuous {
779            return Err(Error::invalid_state("the map is not in static or tile mode"));
780        }
781        self.post(move |core, outbox, id, sequence, resolver| {
782            if !core.maps.contains_key(&id) {
783                return outbox.resolve(resolver, Err(missing_map()));
784            }
785            apply_command(
786                core,
787                id,
788                sequence,
789                outbox,
790                move |entry, outbox| {
791                    if entry.pending_still.is_some() {
792                        let error = Error::invalid_state("the map is rendering a still image already");
793                        return outbox.resolve(resolver, Err(error));
794                    }
795                    // The group holds back the update that the image needs.
796                    if entry.core.command_group_depth() > 0 {
797                        let error = Error::invalid_state("a still image can't render while a command group is open");
798                        return outbox.resolve(resolver, Err(error));
799                    }
800                    let refused = entry.core.render_still().err().map(|error| Err(still_image_error(error)));
801                    entry.pending_still = Some(PendingStill { resolver, refused });
802                },
803                |_, (), _, _| {},
804            );
805        })
806    }
807
808    /// Whether the map was released or disposed.
809    pub(crate) fn is_released(&self) -> bool {
810        self.shared.released.load(Ordering::SeqCst)
811    }
812
813    pub(crate) fn runtime_thread(&self) -> std::thread::ThreadId {
814        self.shared.runtime.thread()
815    }
816
817    /// The map's scale factor: device pixels per logical pixel. It is the
818    /// pixel ratio of the map's options until a render session's
819    /// [`resize`](crate::RenderSession::resize) sets another, and the map's
820    /// next session renders at it.
821    #[must_use]
822    pub fn scale_factor(&self) -> f64 {
823        f64::from_bits(self.shared.scale_factor.load(Ordering::SeqCst))
824    }
825
826    pub(crate) fn tile_cache_enabled(&self) -> bool {
827        self.shared.tile_cache_enabled
828    }
829
830    /// How many worker instances behind the worker codec the tile workers
831    /// of a session's renderer run in, or 0 for the runtime's pool.
832    /// Holds the map's frame clock at `time`, which frame demands then
833    /// leave as it is.
834    #[cfg(feature = "bench")]
835    pub(crate) fn hold_frame_clock(&self, time: Instant) {
836        let published = &self.shared.published;
837        published.frame_clock_held.store(true, Ordering::SeqCst);
838        if let Some(clock) = published.frame_clock.get() {
839            clock.set(Some(time));
840        }
841    }
842
843    pub(crate) fn tile_worker_instances(&self) -> usize {
844        self.shared.runtime.tile_worker_instances.load(Ordering::SeqCst)
845    }
846
847    /// How the map's renderers draw glyphs from local fonts: with system
848    /// fonts, from the fonts the system chooses, or in the browser, which
849    /// has no font files, from the browser's canvas, falling back to its
850    /// sans-serif font as MapLibre GL JS's `localIdeographFontFamily`
851    /// defaults to.
852    pub(crate) fn local_glyphs(&self) -> LocalGlyphs {
853        let mut local = LocalGlyphs { ideographs: self.shared.local_ideographs, ..LocalGlyphs::default() };
854        if self.shared.system_fonts {
855            #[cfg(not(target_family = "wasm"))]
856            {
857                local.chooser = Some(Arc::new(mln_engine::text::system_fonts::SystemFonts));
858            }
859            #[cfg(target_family = "wasm")]
860            {
861                let font_family = "sans-serif".to_owned();
862                local.rasterizer = Some(Arc::new(
863                    mln_engine::text::browser_glyph_rasterizer::BrowserGlyphRasterizer::new(font_family),
864                ));
865            }
866        }
867        local
868    }
869
870    pub(crate) fn glyph_cache(&self) -> Arc<GlyphCache> {
871        Arc::clone(&self.shared.runtime.glyph_cache)
872    }
873
874    /// Where the runtime's background work runs.
875    pub(crate) fn pool(&self) -> Pool {
876        self.shared.runtime.pool.clone()
877    }
878
879    /// What the renderers of the runtime's maps load font faces with.
880    pub(crate) fn font_face_engine(&self) -> Arc<dyn FontFaceEngine> {
881        Arc::clone(&self.shared.runtime.font_face_engine)
882    }
883
884    /// What the map parses its style against, its renderer draws and its
885    /// tile workers lay out: its runtime's
886    /// [`registry`](crate::Runtime::registry). A filter for a query parses
887    /// against its functions.
888    #[must_use]
889    pub fn registry(&self) -> &Arc<Registry> {
890        &self.shared.runtime.registry
891    }
892
893    /// Reserves the map for the session `id`.
894    pub(crate) fn claim_session(&self, id: SessionId, session: Weak<SessionShared>) -> Result<(), Error> {
895        let mut claim = self.shared.session.lock();
896        if self.shared.released.load(Ordering::SeqCst) {
897            return Err(released());
898        }
899        if claim.is_some() {
900            return Err(Error::invalid_state("the map already has an attached render session"));
901        }
902        *claim = Some(SessionClaim { id, session, removal: None });
903        Ok(())
904    }
905
906    /// Lets another session attach once the session `id` is gone, and
907    /// removes the map when a dispose waited for the session.
908    pub(crate) fn release_session_claim(&self, id: SessionId) {
909        let claim = {
910            let mut session = self.shared.session.lock();
911            if session.as_ref().is_some_and(|claim| claim.id == id) { session.take() } else { None }
912        };
913        if let Some(removal) = claim.and_then(|claim| claim.removal) {
914            self.shared.remove(Some(removal));
915        }
916    }
917
918    /// Sends the command that binds the session `id`, whose thread runs
919    /// `queue`, to the map: it sizes the map to `size`, and hands the
920    /// session the map's updates. The map tells the session of the commands
921    /// it runs from `awaited` on.
922    pub(crate) fn bind_session(
923        &self,
924        id: SessionId,
925        queue: SessionQueue,
926        awaited: Arc<AtomicU64>,
927        size: Size,
928    ) -> Result<(), Error> {
929        let reply = SessionReply::new(queue.clone(), |worker, bound, outbox| match bound {
930            Ok((sequence, reader, events, published)) => worker.bound(sequence, reader, events, published, outbox),
931            Err(error) => worker.bind_failed(error, outbox),
932        });
933        let sent = self.shared.send(Some(drop), move |core, outbox, map_id, sequence, resolver: Resolver<()>| {
934            drop(resolver);
935            if !core.maps.contains_key(&map_id) {
936                return reply.send(Err(missing_map()));
937            }
938            let link = SessionLink { id, queue, awaited };
939            apply_command(
940                core,
941                map_id,
942                sequence,
943                outbox,
944                move |entry, _| {
945                    entry.session = Some(link);
946                    let resized = entry.core.set_size(size);
947                    (resized, entry.core.update_reader(), entry.core.renderer_events(), Arc::clone(&entry.published))
948                },
949                move |_, (resized, reader, events, published), _, _| {
950                    reply.send(resized.map(|()| (sequence, reader, events, published)));
951                },
952            );
953        });
954        sent.map(drop)
955    }
956
957    /// Unbinds the session `id` from the map on the runtime's thread, after
958    /// the commands sent before.
959    pub(crate) fn unbind_session(&self, id: SessionId) {
960        let map_id = self.shared.id;
961        // A runtime that shut down has no map to unbind from.
962        self.shared.runtime.post_or((), move |core, _, ()| unbind(core, map_id, id), |()| {});
963    }
964
965    /// Unbinds the session `id` as [`unbind_session`](Self::unbind_session)
966    /// does, then runs `then` on the session's thread.
967    pub(crate) fn unbind_session_then(
968        &self,
969        id: SessionId,
970        queue: SessionQueue,
971        then: impl FnOnce(&mut Worker, &mut Outbox) + Send + 'static,
972    ) {
973        let map_id = self.shared.id;
974        let reply = SessionReply::new(queue, move |worker, _: Result<(), Error>, outbox| then(worker, outbox));
975        // A runtime that shut down or stopped has no map to unbind from, and
976        // the reply's drop runs `then`.
977        self.shared.runtime.post_or(
978            reply,
979            move |core, _, reply| {
980                unbind(core, map_id, id);
981                reply.send(Ok(()));
982            },
983            drop,
984        );
985    }
986
987    /// For a frame demanded now: sets the map's frame clock, which its
988    /// animations sample at and its camera commands start from, and while
989    /// an animation runs, has the map sample it at this time. Returns the
990    /// sample that the frame waits for, or 0 for none. The demands that ask
991    /// before the runtime's thread takes a sample share it.
992    pub(crate) fn frame_demanded(&self) -> u64 {
993        let published = &self.shared.published;
994        #[cfg(feature = "bench")]
995        let held = published.frame_clock_held.load(Ordering::SeqCst);
996        #[cfg(not(feature = "bench"))]
997        let held = false;
998        if let Some(clock) = published.frame_clock.get()
999            && !held
1000        {
1001            clock.set(Some(Instant::now()));
1002        }
1003        // A still map has nothing to sample, and its frames don't wait for
1004        // the runtime's thread.
1005        if self.shared.mode != MapMode::Continuous || !published.animating() {
1006            return 0;
1007        }
1008        let sample = published.samples_requested.fetch_add(1, Ordering::SeqCst) + 1;
1009        if !published.sample_queued.swap(true, Ordering::SeqCst) {
1010            let id = self.shared.id;
1011            self.shared.runtime.post_apart(move |core, outbox| sample_frame(core, id, outbox));
1012        }
1013        sample
1014    }
1015
1016    /// Sends a command that resizes the map to `size` at `scale_factor`,
1017    /// then runs `resize` with its outcome on the thread of the session that
1018    /// `queue` runs, before the session learns of any later command.
1019    pub(crate) fn resize_for_session(
1020        &self,
1021        size: Size,
1022        scale_factor: f64,
1023        queue: SessionQueue,
1024        resize: impl FnOnce(&mut Worker, Result<Applied, Error>, &mut Outbox) + Send + 'static,
1025    ) -> Result<(), Error> {
1026        // The scale factor that a session attached later renders at.
1027        self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
1028        let reply = SessionReply::new(queue, resize);
1029        let sent = self.shared.send(Some(drop), move |core, outbox, id, sequence, resolver: Resolver<()>| {
1030            drop(resolver);
1031            if !core.maps.contains_key(&id) {
1032                return reply.send(Err(missing_map()));
1033            }
1034            apply_command(
1035                core,
1036                id,
1037                sequence,
1038                outbox,
1039                move |entry, _| {
1040                    // A host may hand the session the target it has, such as
1041                    // on every frame. That changes nothing, so it publishes
1042                    // no update, which a demand sent before would draw.
1043                    let pixel_ratio = scale_factor as f32;
1044                    let extent = entry.core.snapshot().view.extent;
1045                    if extent.size == size && extent.scale_factor == f64::from(pixel_ratio) {
1046                        return Ok(());
1047                    }
1048                    entry.core.set_size(size)?;
1049                    entry.core.set_pixel_ratio(pixel_ratio)
1050                },
1051                move |_, resized, applied, _| reply.send(resized.map(|()| applied)),
1052            );
1053        });
1054        sent.map(drop)
1055    }
1056
1057    // MARK: - Feature state
1058
1059    /// Merges `state` into the state of the feature that `selector` names:
1060    /// its keys replace the same keys of the feature's state, and the other
1061    /// keys stay.
1062    ///
1063    /// The map keeps the state until it is removed, its source leaves the
1064    /// style, or a style loads: [`remove_style_source`](Self::remove_style_source)
1065    /// removes the state of the source's features, and a style that loads
1066    /// removes the state of every source. To set state for a new style's
1067    /// sources, wait until [`set_style_url`](Self::set_style_url) or
1068    /// [`set_style_json`](Self::set_style_json) completes.
1069    ///
1070    /// The map's next update for its render session carries the state, so a
1071    /// frame shows it, and a rendered query reads it, once the frame renders
1072    /// that update. A command that changes no state publishes no update: an
1073    /// empty `state` merges nothing.
1074    ///
1075    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
1076    /// selector without a feature.
1077    pub fn set_feature_state(
1078        &self,
1079        selector: &FeatureStateSelector,
1080        state: FeatureState,
1081    ) -> Result<Completion<Applied>, Error> {
1082        let key = selector.key(true)?;
1083        self.command(move |map| {
1084            let feature_id = key.feature_id.as_deref().unwrap_or_default();
1085            map.set_feature_state(&key.source_id, Some(&key.source_layer_id), feature_id, state);
1086            Ok(())
1087        })
1088    }
1089
1090    /// The state of the feature that `selector` names, empty when it has
1091    /// none. Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind)
1092    /// for a selector without a feature.
1093    pub fn feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<FeatureState>, Error> {
1094        let key = selector.key(true)?;
1095        self.query(move |map| {
1096            let feature_id = key.feature_id.as_deref().unwrap_or_default();
1097            Ok(map.feature_state(&key.source_id, Some(&key.source_layer_id), feature_id))
1098        })
1099    }
1100
1101    /// Removes the state that `selector` selects: one key of a feature, all
1102    /// of a feature's state, or that of every feature in a source layer.
1103    /// The removal reaches the render session as
1104    /// [`set_feature_state`](Self::set_feature_state) describes, and a
1105    /// removal of no state publishes no update. Fails with
1106    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a state key
1107    /// without a feature.
1108    pub fn remove_feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<Applied>, Error> {
1109        let key = selector.key(false)?;
1110        self.command(move |map| {
1111            map.remove_feature_state(
1112                &key.source_id,
1113                Some(&key.source_layer_id),
1114                key.feature_id.as_deref(),
1115                key.state_key.as_deref(),
1116            );
1117            Ok(())
1118        })
1119    }
1120
1121    // MARK: - Style
1122
1123    /// Loads the map's style from `url`.
1124    ///
1125    /// Completes once the style document has loaded and parsed, with
1126    /// [`ErrorKind::Native`](mln_style::error::ErrorKind) when it fails to, and with
1127    /// [`ErrorKind::Cancelled`](mln_style::error::ErrorKind) when another style load
1128    /// starts or the map is released first. The style's sources, sprites and
1129    /// glyphs then load in the background. Commands that change the style
1130    /// fail with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) until the
1131    /// document has parsed.
1132    pub fn set_style_url(&self, url: impl Into<String>) -> Result<Completion<Applied>, Error> {
1133        let url = url.into();
1134        if url.is_empty() {
1135            return Err(Error::invalid_argument("style URL must not be empty"));
1136        }
1137        self.load_style(StyleLoad::Url(url))
1138    }
1139
1140    /// Loads the map's style from JSON text. Completes as
1141    /// [`set_style_url`](Self::set_style_url) does, once the style has
1142    /// parsed, but with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind)
1143    /// for JSON that isn't a valid style. A style that fails to parse leaves
1144    /// the map's style as it was.
1145    pub fn set_style_json(&self, json: impl Into<String>) -> Result<Completion<Applied>, Error> {
1146        let json = json.into();
1147        if json.is_empty() {
1148            return Err(Error::invalid_argument("style JSON must not be empty"));
1149        }
1150        self.load_style(StyleLoad::Json(json))
1151    }
1152
1153    fn load_style(&self, load: StyleLoad) -> Result<Completion<Applied>, Error> {
1154        self.post(move |core, outbox, id, sequence, resolver| {
1155            load_style(core, id, sequence, load, resolver, outbox);
1156        })
1157    }
1158
1159    /// The JSON of the style that the map loaded, without the changes made
1160    /// since.
1161    pub fn loaded_style_json(&self) -> Result<Completion<String>, Error> {
1162        self.query(|map| Ok(map.style().get_json().to_owned()))
1163    }
1164
1165    /// The URL of the map's style, or `None` for a style loaded from JSON.
1166    pub fn style_url(&self) -> Result<Completion<Option<String>>, Error> {
1167        self.query(|map| Ok(map.style_url().filter(|url| !url.is_empty()).map(str::to_owned)))
1168    }
1169
1170    /// Adds a source to the style from its JSON. See
1171    /// `mln_engine::map::Map::add_source_json` for the errors.
1172    pub fn add_style_source_json(
1173        &self,
1174        source_id: impl Into<String>,
1175        json: impl Into<String>,
1176    ) -> Result<Completion<Applied>, Error> {
1177        let (source_id, json) = (source_id.into(), json.into());
1178        self.command(move |map| map.add_source_json(&source_id, &json))
1179    }
1180
1181    /// Removes a source from the style. Completes with
1182    /// [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when the style has no
1183    /// such source, and [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
1184    /// when a layer uses it or the style isn't loaded. The source's features
1185    /// lose their state, and a value held for the source drops before the
1186    /// completion.
1187    pub fn remove_style_source(&self, source_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1188        let source_id = source_id.into();
1189        self.send(
1190            move |entry, _| {
1191                let map = &mut entry.core;
1192                if !map.style_document_loaded() {
1193                    return Err(style_not_loaded());
1194                }
1195                if map.source(&source_id).is_none() {
1196                    return Err(Error::not_found(format!("source \"{source_id}\" does not exist")));
1197                }
1198                if let Some(layer) = map.style().get_layers().find(|layer| layer.get_source_id() == source_id) {
1199                    let message = format!("source \"{source_id}\" is used by layer \"{}\"", layer.get_id());
1200                    return Err(Error::invalid_state(message));
1201                }
1202                map.remove_source(&source_id);
1203                entry.core.remove_source_feature_state(&source_id);
1204                Ok(())
1205            },
1206            |(), entry| entry.applied(),
1207        )
1208    }
1209
1210    /// Adds a layer to the style from its JSON, below `before_layer_id` or
1211    /// above every layer. See `Style::add_layer_json` for the errors.
1212    pub fn add_style_layer_json(
1213        &self,
1214        json: impl Into<String>,
1215        before_layer_id: Option<String>,
1216    ) -> Result<Completion<Applied>, Error> {
1217        let json = json.into();
1218        self.command(move |map| map.edit_loaded_style(|style| style.add_layer_json(&json, before_layer_id.as_deref())))
1219    }
1220
1221    /// Adds `layer` to the style, below `before_layer_id` or above every
1222    /// layer: one of a type that isn't made from JSON, or one that holds a
1223    /// value for as long as the style has it
1224    /// ([`Layer::from_style_holding`](mln_style::layer::Layer::from_style_holding)).
1225    /// See `Style::add_layer` for the errors.
1226    pub fn add_style_layer(
1227        &self,
1228        layer: mln_style::layer::Layer,
1229        before_layer_id: Option<String>,
1230    ) -> Result<Completion<Applied>, Error> {
1231        self.command(move |map| map.edit_loaded_style(|style| style.add_layer(layer, before_layer_id.as_deref())))
1232    }
1233
1234    /// Removes a layer from the style. Completes with
1235    /// [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when the style has no
1236    /// such layer, and [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
1237    /// while the style isn't loaded.
1238    pub fn remove_style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1239        let layer_id = layer_id.into();
1240        self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::RemoveLayer(layer_id))))
1241    }
1242
1243    /// A layer of the style as JSON, or `None` when the style has no such
1244    /// layer.
1245    pub fn style_layer_json(&self, layer_id: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1246        let layer_id = layer_id.into();
1247        self.query(move |map| Ok(map.style().layer_json(&layer_id)))
1248    }
1249
1250    /// Sets a property of a layer to a JSON value. See
1251    /// `Style::set_layer_property_json` for the errors.
1252    pub fn set_style_layer_property(
1253        &self,
1254        layer_id: impl Into<String>,
1255        name: impl Into<String>,
1256        json: impl Into<String>,
1257    ) -> Result<Completion<Applied>, Error> {
1258        let (layer_id, name, json) = (layer_id.into(), name.into(), json.into());
1259        self.command(move |map| map.edit_loaded_style(|style| style.set_layer_property_json(&layer_id, &name, &json)))
1260    }
1261
1262    /// A property of a layer as JSON, or `None` when the layer doesn't set
1263    /// it. See `Style::layer_property_json` for the errors.
1264    pub fn style_layer_property(
1265        &self,
1266        layer_id: impl Into<String>,
1267        name: impl Into<String>,
1268    ) -> Result<Completion<Option<String>>, Error> {
1269        let (layer_id, name) = (layer_id.into(), name.into());
1270        self.query(move |map| map.style().layer_property_json(&layer_id, &name))
1271    }
1272
1273    /// Sets a root property of the style to a JSON value, without
1274    /// reloading the style. See `Style::set_root_property_json` for the
1275    /// properties that change and the errors.
1276    pub fn set_style_root_property(
1277        &self,
1278        name: impl Into<String>,
1279        json: impl Into<String>,
1280    ) -> Result<Completion<Applied>, Error> {
1281        let (name, json) = (name.into(), json.into());
1282        self.command(move |map| map.edit_loaded_style(|style| style.set_root_property_json(&name, &json)))
1283    }
1284
1285    /// A root property of the style as JSON, or `None` when neither the
1286    /// style nor the map sets it. See `Style::root_property_json`.
1287    pub fn style_root_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1288        let name = name.into();
1289        self.query(move |map| map.style().root_property_json(&name))
1290    }
1291
1292    /// Sets a property of the style's light to a JSON value.
1293    pub fn set_style_light_property(
1294        &self,
1295        name: impl Into<String>,
1296        json: impl Into<String>,
1297    ) -> Result<Completion<Applied>, Error> {
1298        let (name, json) = (name.into(), json.into());
1299        self.command(move |map| map.edit_loaded_style(|style| style.set_light_property_json(&name, &json)))
1300    }
1301
1302    /// A property of the style's light as JSON, or `None` when the light
1303    /// doesn't set it.
1304    pub fn style_light_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1305        let name = name.into();
1306        self.query(move |map| Ok(map.style().light_property_json(&name)))
1307    }
1308
1309    // MARK: - Camera
1310
1311    /// A command that moves the camera: `apply` starts a camera command,
1312    /// whose end nobody waits for.
1313    fn camera_command(
1314        &self,
1315        apply: impl FnOnce(&mut mln_engine::map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1316    ) -> Result<Completion<Applied>, Error> {
1317        self.send_camera(apply, None)
1318    }
1319
1320    /// A command that moves the camera, whose end `on_end` receives. `on_end`
1321    /// is in place before the command is sent, so it runs on the runtime's
1322    /// thread, or on this one with
1323    /// [`ErrorKind::Cancelled`](mln_style::error::ErrorKind) when the send fails.
1324    fn camera_command_then(
1325        &self,
1326        apply: impl FnOnce(&mut mln_engine::map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1327        on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1328    ) -> Result<Completion<Applied>, Error> {
1329        let (ended, end) = self.shared.runtime.completion();
1330        ended.on_complete(on_end);
1331        self.send_camera(apply, Some(end))
1332    }
1333
1334    /// Sends a camera command, and `end`, if any, the command's end: a
1335    /// failure ends it as cancelled.
1336    fn send_camera(
1337        &self,
1338        apply: impl FnOnce(&mut mln_engine::map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1339        end: Option<Resolver<TransitionEnd>>,
1340    ) -> Result<Completion<Applied>, Error> {
1341        self.send(
1342            move |entry, outbox| match (apply(&mut entry.core), end) {
1343                (Ok(command), Some(end)) => {
1344                    entry.camera_commands.insert(command, end);
1345                    Ok(())
1346                }
1347                (Ok(_), None) => Ok(()),
1348                (Err(error), end) => {
1349                    if let Some(end) = end {
1350                        let generation = entry.core.generation();
1351                        let cancelled =
1352                            TransitionEnd { outcome: TransitionOutcome::Cancelled, generation, ..Default::default() };
1353                        outbox.resolve(end, Ok(cancelled));
1354                    }
1355                    Err(error)
1356                }
1357            },
1358            |(), entry| entry.applied(),
1359        )
1360    }
1361
1362    /// Moves the camera to absolute values, by a jump, an ease or a flight.
1363    pub fn update_camera(&self, update: CameraUpdate) -> Result<Completion<Applied>, Error> {
1364        self.camera_command(move |map| Ok(map.update_camera(&update)))
1365    }
1366
1367    /// Moves the camera as [`update_camera`](Self::update_camera) does, and
1368    /// calls `on_end` with how the change ended, on the runtime's thread:
1369    /// once the map has published the snapshot that shows where the change
1370    /// left the camera, whose generation the end reports, and before the
1371    /// returned completion when the change ends within the command. A
1372    /// command that fails ends as cancelled, and one that the map's release
1373    /// ends as closed, with generation 0. `on_end` runs on this thread only
1374    /// with [`ErrorKind::Cancelled`](mln_style::error::ErrorKind), when the send
1375    /// fails.
1376    pub fn update_camera_then(
1377        &self,
1378        update: CameraUpdate,
1379        on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1380    ) -> Result<Completion<Applied>, Error> {
1381        self.camera_command_then(move |map| Ok(map.update_camera(&update)), on_end)
1382    }
1383
1384    /// Moves the camera relative to where it is, as a gesture does.
1385    /// Completes with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for
1386    /// a delta that the camera can't apply.
1387    pub fn apply_camera_delta(&self, delta: CameraDelta) -> Result<Completion<Applied>, Error> {
1388        self.camera_command(move |map| {
1389            map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string()))
1390        })
1391    }
1392
1393    /// Applies `delta` as [`apply_camera_delta`](Self::apply_camera_delta)
1394    /// does, and calls `on_end` with how the change ended, as
1395    /// [`update_camera_then`](Self::update_camera_then) does.
1396    pub fn apply_camera_delta_then(
1397        &self,
1398        delta: CameraDelta,
1399        on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1400    ) -> Result<Completion<Applied>, Error> {
1401        self.camera_command_then(
1402            move |map| map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string())),
1403            on_end,
1404        )
1405    }
1406
1407    /// The camera that fits `area` in the map's view, after the commands
1408    /// sent before, as [`mln_engine::map::Map::camera_for_lat_lngs`] fits
1409    /// it. Its zoom stays within the map's zoom limits.
1410    ///
1411    /// Completes with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for
1412    /// an empty area, and for padding and margin that leave no room for it.
1413    pub fn camera_for(
1414        &self,
1415        area: CameraFitArea,
1416        options: CameraFitOptions,
1417    ) -> Result<Completion<CameraOptions>, Error> {
1418        self.query(move |map| camera::camera_for(map, &area, &options))
1419    }
1420
1421    /// Moves the camera to the one that [`camera_for`](Self::camera_for)
1422    /// finds once the commands sent before have run, as
1423    /// [`update_camera`](Self::update_camera) moves it.
1424    ///
1425    /// Completes as `camera_for` fails, and then leaves the camera where it
1426    /// is and ends the animation as cancelled.
1427    pub fn fit_camera(&self, area: CameraFitArea, update: CameraFitUpdate) -> Result<Completion<Applied>, Error> {
1428        self.camera_command(move |map| fit(map, &area, &update))
1429    }
1430
1431    /// Fits the camera as [`fit_camera`](Self::fit_camera) does, and calls
1432    /// `on_end` with how the change ended, as
1433    /// [`update_camera_then`](Self::update_camera_then) does.
1434    pub fn fit_camera_then(
1435        &self,
1436        area: CameraFitArea,
1437        update: CameraFitUpdate,
1438        on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1439    ) -> Result<Completion<Applied>, Error> {
1440        self.camera_command_then(move |map| fit(map, &area, &update), on_end)
1441    }
1442
1443    /// Stops every camera animation.
1444    pub fn cancel_camera_transitions(&self) -> Result<Completion<Applied>, Error> {
1445        self.command(|map| {
1446            map.cancel_transitions();
1447            Ok(())
1448        })
1449    }
1450
1451    /// Stops the camera animations whose transition ID is `transition_id`.
1452    pub fn cancel_camera_transitions_with_id(&self, transition_id: u64) -> Result<Completion<Applied>, Error> {
1453        self.command(move |map| {
1454            map.cancel_transitions_with_id(transition_id);
1455            Ok(())
1456        })
1457    }
1458
1459    /// The camera after the commands sent before.
1460    pub fn camera(&self) -> Result<Completion<CameraQuery>, Error> {
1461        self.send(
1462            |_, _| Ok(()),
1463            |(), entry| CameraQuery { generation: entry.core.generation(), camera: entry.core.snapshot().view.camera },
1464        )
1465    }
1466
1467    /// The area that `camera` would show, with the fields that `camera`
1468    /// leaves out from the map's camera. It holds every corner of a rotated
1469    /// view, and its longitudes can pass ±180, so a view across the
1470    /// antimeridian gives one continuous range.
1471    pub fn lat_lng_bounds_for_camera(&self, camera: CameraOptions) -> Result<Completion<LatLngBounds>, Error> {
1472        self.query(move |map| map.lat_lng_bounds_for_camera_unwrapped(&camera))
1473    }
1474
1475    /// Sets the limits on the camera.
1476    pub fn set_bounds(&self, bounds: BoundOptions) -> Result<Completion<Applied>, Error> {
1477        self.command(move |map| map.set_bounds(&bounds))
1478    }
1479
1480    /// Sets the camera's position and orientation in three dimensions.
1481    pub fn set_free_camera_options(&self, camera: FreeCameraOptions) -> Result<Completion<Applied>, Error> {
1482        self.command(move |map| {
1483            map.set_free_camera_options(&camera);
1484            Ok(())
1485        })
1486    }
1487
1488    /// Sets how the map orients and constrains its view.
1489    pub fn set_viewport_options(&self, options: ViewportOptions) -> Result<Completion<Applied>, Error> {
1490        self.command(move |map| {
1491            camera::set_viewport(map, &options);
1492            Ok(())
1493        })
1494    }
1495
1496    /// Sets how the map picks the tiles to load.
1497    pub fn set_tile_options(&self, options: TileOptions) -> Result<Completion<Applied>, Error> {
1498        self.command(move |map| {
1499            camera::set_tile_options(map, &options);
1500            Ok(())
1501        })
1502    }
1503
1504    pub fn set_projection_mode(&self, mode: ProjectionMode) -> Result<Completion<Applied>, Error> {
1505        self.command(move |map| {
1506            map.set_projection_mode(&mode);
1507            Ok(())
1508        })
1509    }
1510
1511    /// Logs the style's sources and their state.
1512    pub fn dump_debug_logs(&self) -> Result<Completion<Applied>, Error> {
1513        self.command(|map| {
1514            map.dump_debug_logs();
1515            Ok(())
1516        })
1517    }
1518}
1519
1520/// A command group of a map that ends when it drops.
1521#[must_use = "the group ends when it drops"]
1522pub struct CommandGroup {
1523    map: Option<Map>,
1524}
1525
1526impl CommandGroup {
1527    /// Ends the group, as [`Map::end_command_group`] does.
1528    pub fn end(mut self) -> Result<Completion<Applied>, Error> {
1529        match self.map.take() {
1530            Some(map) => map.end_command_group(),
1531            None => Err(Error::invalid_state("the group ended already")),
1532        }
1533    }
1534}
1535
1536impl Drop for CommandGroup {
1537    fn drop(&mut self) {
1538        if let Some(map) = self.map.take() {
1539            let _ = map.end_command_group();
1540        }
1541    }
1542}
1543
1544enum StyleLoad {
1545    Url(String),
1546    Json(String),
1547}
1548
1549/// A style load that hasn't completed.
1550struct PendingStyle {
1551    resolver: Resolver<Applied>,
1552    /// Whether the caller passed the style document, which then is the
1553    /// argument that fails to parse.
1554    from_json: bool,
1555}
1556
1557/// The render session that a map is reserved for.
1558struct SessionClaim {
1559    id: SessionId,
1560    session: Weak<SessionShared>,
1561    /// The completion of a dispose that waits for the session to end.
1562    removal: Option<Resolver<()>>,
1563}
1564
1565/// Forgets the session `id` on the runtime's thread, unless the map has
1566/// bound another since.
1567fn unbind(core: &mut RuntimeCore, map_id: MapId, id: SessionId) {
1568    if let Some(entry) = core.maps.get_mut(&map_id)
1569        && entry.session.as_ref().is_some_and(|link| link.id == id)
1570    {
1571        entry.session = None;
1572    }
1573}
1574
1575/// The render session bound to a map, as the runtime's thread knows it.
1576pub(crate) struct SessionLink {
1577    id: SessionId,
1578    queue: SessionQueue,
1579    /// The session's `awaited_command`.
1580    awaited: Arc<AtomicU64>,
1581}
1582
1583/// A still image on its way, whose outcome the next flush that finds it
1584/// reports.
1585struct PendingStill {
1586    resolver: Resolver<()>,
1587    /// Why the map refused the image, which the flush after the command
1588    /// reports.
1589    refused: Option<Result<(), Error>>,
1590}
1591
1592/// A still image's error as the handle reports it: a load failure is the
1593/// library's, whatever the core called it.
1594fn still_image_error(error: Error) -> Error {
1595    match error.kind {
1596        ErrorKind::InvalidState => error,
1597        _ => Error::native(error.message),
1598    }
1599}
1600
1601/// A map on the runtime's thread.
1602pub(crate) struct MapEntry {
1603    pub(crate) core: mln_engine::map::Map,
1604    published: Arc<Published>,
1605    mask: EventMask,
1606    /// The sequence number of the last command that ran.
1607    applied: u64,
1608    /// The last command and frame sample that ran while a burst held the
1609    /// map's updates back, which the session learns of once they show.
1610    held_applied: Option<u64>,
1611    held_sampled: Option<u64>,
1612    /// The style load in progress.
1613    pending_style: Option<PendingStyle>,
1614    pending_still: Option<PendingStill>,
1615    /// The render session that draws the map.
1616    session: Option<SessionLink>,
1617    /// Set while the map has reported something that no flush has taken.
1618    flush_pending: FlushFlag,
1619    /// The camera commands whose change hasn't ended.
1620    camera_commands: HashMap<CameraCommandId, Resolver<TransitionEnd>>,
1621    /// The values held for the sources that commands added with them.
1622    pub(crate) held_sources: HeldSources,
1623    /// The GeoJSON data that commands set and that is still being built.
1624    pub(crate) geojson_updates: GeoJsonUpdates,
1625    /// The repaint posted for when the map changes next on its own
1626    /// ([`mln_engine::map::Map::repaint_at`]).
1627    repaint: Option<(Instant, TimedTask)>,
1628}
1629
1630impl MapEntry {
1631    pub(crate) fn applied(&self) -> Applied {
1632        Applied {
1633            sequence: self.applied,
1634            generation: self.core.generation(),
1635            render_update_generation: self.core.pending_update_generation(),
1636        }
1637    }
1638}
1639
1640/// Whether a map reported something that no flush has taken: what its
1641/// reports waker sets. Reports that come before the flush they posted runs
1642/// share it.
1643#[derive(Clone, Default)]
1644struct FlushFlag(Arc<AtomicBool>);
1645
1646impl FlushFlag {
1647    /// The map `id`'s reports waker: it sets the flag, and posts a flush to
1648    /// `queue` when the flag was clear. The posted flush does nothing once
1649    /// another flush took the reports.
1650    fn waker(&self, queue: &CoreQueue, id: MapId) -> Waker {
1651        let (flag, queue) = (self.clone(), queue.downgrade());
1652        Arc::new(move || {
1653            if !flag.0.swap(true, Ordering::SeqCst)
1654                && let Some(queue) = queue.upgrade()
1655            {
1656                let flag = flag.clone();
1657                post(&queue, move |core, outbox| {
1658                    if flag.is_set() {
1659                        flush(core, id, outbox);
1660                    }
1661                });
1662            }
1663        })
1664    }
1665
1666    fn is_set(&self) -> bool {
1667        self.0.load(Ordering::SeqCst)
1668    }
1669
1670    fn clear(&self) {
1671        self.0.store(false, Ordering::SeqCst);
1672    }
1673}
1674
1675/// Builds the map `id` on the runtime's thread.
1676pub(crate) fn create(
1677    core: &mut RuntimeCore,
1678    id: MapId,
1679    options: &MapOptions,
1680    published: Arc<Published>,
1681    resolver: Resolver<Applied>,
1682    outbox: &mut Outbox,
1683) {
1684    let registry = Arc::clone(&core.registry);
1685    let mut map =
1686        match mln_engine::map::Map::with_file_source(Arc::clone(core.loader()), options.map, registry, &core.pool) {
1687            Ok(map) => map,
1688            Err(error) => return outbox.resolve(resolver, Err(error)),
1689        };
1690    if let Some(json) = &options.fallback_font_faces {
1691        if let Err(error) = map.set_fallback_font_faces(json) {
1692            return outbox.resolve(resolver, Err(error));
1693        }
1694    } else if options.system_fonts {
1695        map.set_fallback_font_face_list(mln_engine::text::system_fonts::font_face().into_iter().collect());
1696    }
1697    let _ = published.updates.set(map.update_reader());
1698    let _ = published.frame_clock.set(map.frame_clock());
1699    let flush_pending = FlushFlag::default();
1700    map.set_reports_waker(Some(flush_pending.waker(&core.queue, id)));
1701    published.applied.store(1, Ordering::SeqCst);
1702    core.maps.insert(
1703        id,
1704        MapEntry {
1705            core: map,
1706            published,
1707            mask: options.event_mask,
1708            applied: 1,
1709            held_applied: None,
1710            held_sampled: None,
1711            pending_style: None,
1712            pending_still: None,
1713            session: None,
1714            flush_pending,
1715            camera_commands: HashMap::default(),
1716            held_sources: HeldSources::default(),
1717            geojson_updates: GeoJsonUpdates::default(),
1718            repaint: None,
1719        },
1720    );
1721    flush(core, id, outbox);
1722    if let Some(entry) = core.maps.get(&id) {
1723        outbox.resolve(resolver, Ok(entry.applied()));
1724    }
1725}
1726
1727/// Runs a command on the map `id`, which must be there: handles what came
1728/// before it, applies it, publishes the map's state, sends its events, and
1729/// runs `after` with what `apply` returned. Then it tells the map's render
1730/// session that the command ran, so `after` can send the session what the
1731/// session must see first. While a burst holds the map's updates back, it
1732/// tells the session once they show, so that no frame that waits for the
1733/// command draws the update before it.
1734pub(crate) fn apply_command<T>(
1735    core: &mut RuntimeCore,
1736    id: MapId,
1737    sequence: u64,
1738    outbox: &mut Outbox,
1739    apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> T,
1740    after: impl FnOnce(&MapEntry, T, Applied, &mut Outbox),
1741) {
1742    // What the runtime's calls change, a flush in the same task takes. What
1743    // came since then, the map reported: the report posted a flush, or is
1744    // queued with its waker still on its way.
1745    if core.maps.get(&id).is_some_and(|entry| entry.flush_pending.is_set() || entry.core.has_reports()) {
1746        flush(core, id, outbox);
1747    }
1748    let Some(entry) = core.maps.get_mut(&id) else { return };
1749    let value = apply(entry, outbox);
1750    entry.applied = sequence;
1751    flush(core, id, outbox);
1752    let holding = core.holding_updates();
1753    let Some(entry) = core.maps.get_mut(&id) else { return };
1754    after(entry, value, entry.applied(), outbox);
1755    if holding {
1756        entry.held_applied = Some(sequence);
1757    } else {
1758        report_applied(entry, sequence);
1759    }
1760}
1761
1762/// Tells the map's session that the command `sequence` ran, once a frame can
1763/// show it.
1764fn report_applied(entry: &MapEntry, sequence: u64) {
1765    entry.published.applied.store(sequence, Ordering::SeqCst);
1766    if let Some(link) = &entry.session
1767        && sequence >= link.awaited.load(Ordering::SeqCst)
1768    {
1769        worker_post(&link.queue, move |worker, outbox| worker.map_applied(sequence, outbox));
1770    }
1771}
1772
1773/// Tells the map's session that the map took the frame sample `sample`, once
1774/// a frame can show it.
1775fn report_sampled(entry: &MapEntry, sample: u64) {
1776    entry.published.sampled.fetch_max(sample, Ordering::SeqCst);
1777    if let Some(link) = &entry.session {
1778        worker_post(&link.queue, move |worker, outbox| worker.map_sampled(sample, outbox));
1779    }
1780}
1781
1782/// Tells the map's session what ran while a burst held the map's updates
1783/// back, now that they show.
1784pub(crate) fn report_held(entry: &mut MapEntry) {
1785    if let Some(sequence) = entry.held_applied.take() {
1786        report_applied(entry, sequence);
1787    }
1788    if let Some(sample) = entry.held_sampled.take() {
1789        report_sampled(entry, sample);
1790    }
1791}
1792
1793/// Has the map `id` sample its animations at its frame clock's time for the
1794/// frame samples that demands asked for.
1795fn sample_frame(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1796    let Some(entry) = core.maps.get(&id) else { return };
1797    // A demand from now on asks for another sample.
1798    entry.published.sample_queued.store(false, Ordering::SeqCst);
1799    let sample = entry.published.samples_requested.load(Ordering::SeqCst);
1800    if entry.flush_pending.is_set() || entry.core.has_reports() {
1801        flush(core, id, outbox);
1802    }
1803    let Some(entry) = core.maps.get_mut(&id) else { return };
1804    entry.core.sample_frame();
1805    flush(core, id, outbox);
1806    let holding = core.holding_updates();
1807    let Some(entry) = core.maps.get_mut(&id) else { return };
1808    if holding {
1809        entry.held_sampled = Some(sample);
1810    } else {
1811        report_sampled(entry, sample);
1812    }
1813}
1814
1815/// Runs a command on the map `id` and completes with what `finish` makes of
1816/// its result and the map after it.
1817pub(crate) fn run_command<T, R: 'static>(
1818    core: &mut RuntimeCore,
1819    id: MapId,
1820    sequence: u64,
1821    apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error>,
1822    finish: impl FnOnce(T, &MapEntry) -> R,
1823    resolver: Resolver<R>,
1824    outbox: &mut Outbox,
1825) {
1826    if !core.maps.contains_key(&id) {
1827        return outbox.resolve(resolver, Err(missing_map()));
1828    }
1829    apply_command(core, id, sequence, outbox, apply, move |entry, result, _, outbox| {
1830        outbox.resolve(resolver, result.map(|value| finish(value, entry)));
1831    });
1832}
1833
1834/// Starts a style load on the map `id`. Its completion waits for the load's
1835/// outcome, which a flush finds among the map's events.
1836fn load_style(
1837    core: &mut RuntimeCore,
1838    id: MapId,
1839    sequence: u64,
1840    load: StyleLoad,
1841    resolver: Resolver<Applied>,
1842    outbox: &mut Outbox,
1843) {
1844    if !core.maps.contains_key(&id) {
1845        return outbox.resolve(resolver, Err(missing_map()));
1846    }
1847    // The flush before the load sends the outcomes of earlier loads to their
1848    // own completions.
1849    apply_command(
1850        core,
1851        id,
1852        sequence,
1853        outbox,
1854        move |entry, outbox| {
1855            let from_json = matches!(load, StyleLoad::Json(_));
1856            if let Some(previous) = entry.pending_style.replace(PendingStyle { resolver, from_json }) {
1857                outbox.resolve(previous.resolver, Err(Error::cancelled("another style load started")));
1858            }
1859            match load {
1860                StyleLoad::Url(url) => entry.core.load_style_url(&url),
1861                StyleLoad::Json(json) => entry.core.load_style_json(&json),
1862            }
1863        },
1864        |_, (), _, _| {},
1865    );
1866}
1867
1868/// Handles what the map's style and renderer reported, publishes its state
1869/// if it changed, and sends its events. A flush with nothing to handle and no
1870/// change to publish costs little, so callers flush whenever they may need
1871/// to.
1872pub(crate) fn flush(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1873    let Some(entry) = core.maps.get_mut(&id) else { return };
1874    // The flush takes what the map reported so far, and what it reports from
1875    // now on posts another.
1876    entry.flush_pending.clear();
1877    let events = entry.core.drain_events();
1878    let repaint_at = entry.core.repaint_at();
1879    if entry.repaint.as_ref().map(|(at, _)| *at) != repaint_at {
1880        if let Some((_, task)) = entry.repaint.take() {
1881            core.queue.cancel(task);
1882        }
1883        entry.repaint =
1884            repaint_at.map(|at| (at, post_at(&core.queue, at, move |core, outbox| repaint(core, id, outbox))));
1885    }
1886    // The sources that left the style, by a command or a style load, let go
1887    // of what they held before anything reports the change.
1888    crate::style::reconcile(entry, outbox);
1889    let generation = entry.core.generation();
1890    // The camera commands that ended report the snapshot that shows them.
1891    let ends: Vec<_> = entry
1892        .core
1893        .drain_command_ends()
1894        .filter_map(|end| Some((entry.camera_commands.remove(&end.command)?, TransitionEnd { generation, ..end.end })))
1895        .collect();
1896    // Each change to the state grows the generation, so a snapshot of the
1897    // same generation shows the state as it is.
1898    let mut published = entry.published.state.lock();
1899    let snapshot = match &*published {
1900        Some(state) if state.snapshot.generation == generation => state.snapshot,
1901        _ => entry.core.snapshot(),
1902    };
1903    // The renderer's ground changes the map's conversions, though not
1904    // always its state.
1905    *published = Some(PublishedState { snapshot, ground: entry.core.ground() });
1906    drop(published);
1907
1908    let mut style_outcome = None;
1909    let from_json = entry.pending_style.as_ref().is_some_and(|pending| pending.from_json);
1910    for event in &events {
1911        match event {
1912            MapEvent::StyleLoaded => style_outcome = Some(Ok(())),
1913            MapEvent::LoadingFailed(StyleLoadError::Parse(message)) if from_json => {
1914                style_outcome = Some(Err(Error::invalid_argument(message)));
1915            }
1916            MapEvent::LoadingFailed(error) => style_outcome = Some(Err(Error::native(error.message()))),
1917            _ => {}
1918        }
1919    }
1920    let style_outcome = style_outcome.map(|outcome| (outcome, entry.pending_style.take(), entry.applied()));
1921    let still_outcome = match &mut entry.pending_still {
1922        Some(pending) => pending
1923            .refused
1924            .take()
1925            .or_else(|| entry.core.take_still_image().map(|result| result.map_err(still_image_error))),
1926        None => None,
1927    };
1928    let still = still_outcome.and_then(|outcome| Some((outcome, entry.pending_still.take()?.resolver)));
1929    // The session demands a frame for the image while it waits, and lets
1930    // the demand go once it doesn't.
1931    let still_image = entry.pending_still.as_ref().and(entry.core.pending_still_image()).unwrap_or(0);
1932    if entry.published.still_image.swap(still_image, Ordering::SeqCst) != still_image
1933        && let Some(link) = &entry.session
1934    {
1935        worker_post(&link.queue, Worker::still_image_changed);
1936    }
1937
1938    let mask = entry.mask;
1939    let events: Vec<RuntimeEvent> = events
1940        .into_iter()
1941        .map(RuntimeEventKind::Map)
1942        .filter(|kind| mask.contains(kind.event_type()))
1943        .map(|kind| RuntimeEvent { source: EventSource::Map { id, generation }, kind })
1944        .collect();
1945    core.send_events(events, outbox);
1946    for (resolver, end) in ends {
1947        outbox.resolve(resolver, Ok(end));
1948    }
1949
1950    if let Some((outcome, Some(pending), applied)) = style_outcome {
1951        outbox.resolve(pending.resolver, outcome.map(|()| applied));
1952    }
1953    if let Some((outcome, resolver)) = still {
1954        outbox.resolve(resolver, outcome);
1955    }
1956}
1957
1958/// Draws the map `id` once its last frame's time to change came.
1959fn repaint(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1960    let Some(entry) = core.maps.get_mut(&id) else { return };
1961    entry.repaint = None;
1962    if entry.core.repaint_at().is_some() {
1963        entry.core.trigger_repaint();
1964    }
1965    flush(core, id, outbox);
1966}
1967
1968/// Lets go of the map `id`, after sending the events it still had.
1969fn remove(core: &mut RuntimeCore, id: MapId, done: Option<Resolver<()>>, outbox: &mut Outbox) {
1970    flush(core, id, outbox);
1971    if let Some(mut entry) = core.maps.remove(&id) {
1972        if let Some((_, task)) = entry.repaint.take() {
1973            core.queue.cancel(task);
1974        }
1975        entry.core.set_waker(None);
1976        // The handles, which may outlive the map, keep no ground alive.
1977        if let Some(state) = &mut *entry.published.state.lock() {
1978            state.ground = None;
1979        }
1980        if let Some(pending) = entry.pending_style.take() {
1981            outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1982        }
1983        if let Some(pending) = entry.pending_still.take() {
1984            outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1985        }
1986        crate::style::release(&mut entry, outbox);
1987        // The map's camera changes end as closed as it drops, with no
1988        // snapshot to show them.
1989        entry.core.close_camera();
1990        for end in entry.core.drain_command_ends() {
1991            if let Some(resolver) = entry.camera_commands.remove(&end.command) {
1992                outbox.resolve(resolver, Ok(end.end));
1993            }
1994        }
1995    }
1996    if let Some(done) = done {
1997        outbox.resolve(done, Ok(()));
1998    }
1999}