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, 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/// The ID of a map, unique within its runtime.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
40pub struct MapId(pub u64);
41
42/// How to create a map.
43#[derive(Clone, Debug)]
44pub struct MapOptions {
45    pub map: mln_engine::map::MapOptions,
46    /// The events that the map reports.
47    pub event_mask: EventMask,
48    /// JSON text of the font faces that the map falls back to for the text
49    /// that the style's fonts don't draw, as `Map::set_fallback_font_faces`
50    /// takes it: the text that glyph PBFs can't shape, all the text of a
51    /// style without them, and the glyphs that come from local fonts, before
52    /// the system's. With it, the map shapes no text with the system's fonts.
53    pub fallback_font_faces: Option<String>,
54    /// Whether the map draws from the system's fonts what the style's fonts
55    /// and `fallback_font_faces` don't. It shapes with them the scripts that
56    /// glyph PBFs can't shape, and all the text of a style without PBFs
57    /// (`mln_engine::text::system_fonts::font_face`), from the fonts the labels'
58    /// `text-font` names first; and draws from them the glyphs a style's
59    /// PBFs lack, and with `local_ideographs`, CJK
60    /// (`mln_engine::text::system_fonts::SystemFonts`). On by default. The first map that
61    /// uses them waits for the platform's font matcher to load. In the
62    /// browser, which has no font files to read, the browser draws each
63    /// glyph of that text in the font stack's families, then its sans-serif
64    /// font, as MapLibre GL JS does, unshaped.
65    pub system_fonts: bool,
66    /// Whether CJK ideographs, kana and hangul come from local fonts (the
67    /// fallback font faces, then the system's) before glyph PBFs, as
68    /// MapLibre GL JS's `localIdeographFontFamily` draws them, rather than
69    /// downloading a glyph PBF for every few characters. On by default.
70    pub local_ideographs: bool,
71    /// Whether the map's render sessions keep tiles in memory after they
72    /// leave the view, so they show again without loading. On by default.
73    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/// What a map command left behind once it ran.
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct Applied {
92    /// The command's place among the map's commands: the map's creation is
93    /// 1, and each command takes the next number when it is sent.
94    pub sequence: u64,
95    /// The map's generation after the command: a snapshot with this
96    /// generation or a later one includes the command.
97    pub generation: u64,
98    /// The map's update generation after the command: a frame that renders
99    /// this update or a later one shows the command.
100    pub render_update_generation: u64,
101}
102
103/// Moves `map`'s camera to the one that fits `area`.
104fn 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    // A fit leaves running changes of the fields it keeps alone, but carries
112    // on a change of the padding that its center stops.
113    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/// The camera, and the generation of the map that it belongs to.
126#[derive(Clone, Copy, Debug, PartialEq)]
127pub struct CameraQuery {
128    pub generation: u64,
129    pub camera: Camera,
130}
131
132/// What the runtime's thread publishes for a map's handles.
133pub(crate) struct Published {
134    /// The map's snapshot and its ground as of its last flush, `None` until
135    /// the map is built: one lock, so that a projection's view and ground
136    /// come from the same flush.
137    state: Mutex<Option<PublishedState>>,
138    /// The map's updates for its renderer, once the map is built.
139    updates: OnceLock<UpdateReader>,
140    /// The sequence number of the last command that ran and whose changes a
141    /// frame can show.
142    applied: AtomicU64,
143    /// The map's frame clock, once the map is built: each frame demand sets
144    /// it, unless it is held.
145    frame_clock: OnceLock<FrameClock>,
146    /// The frame samples that demands asked for, numbered from 1, and the
147    /// last that the map took and a frame can show.
148    samples_requested: AtomicU64,
149    sampled: AtomicU64,
150    /// Whether a sample is on its way to the runtime's thread, which takes
151    /// the demands that ask meanwhile.
152    sample_queued: AtomicBool,
153    event_mask: AtomicU64,
154    /// The still image that waits for a frame, as the
155    /// `still_image_request_id` of the updates that ask for it, or 0.
156    still_image: AtomicU64,
157}
158
159/// The map's state as of a flush.
160struct PublishedState {
161    snapshot: MapSnapshot,
162    /// The ground the map draws (`mln_engine::map::Map::ground`).
163    ground: Option<Arc<dyn Elevation>>,
164}
165
166impl Published {
167    /// The sequence number of the last command that ran and whose changes a
168    /// frame can show.
169    pub(crate) fn applied(&self) -> u64 {
170        self.applied.load(Ordering::SeqCst)
171    }
172
173    /// The last frame sample that the map took and a frame can show.
174    pub(crate) fn sampled(&self) -> u64 {
175        self.sampled.load(Ordering::SeqCst)
176    }
177
178    /// Whether a camera command was still animating as of the map's last
179    /// published state.
180    pub(crate) fn animating(&self) -> bool {
181        self.state.lock().as_ref().is_some_and(|state| state.snapshot.transition_in_progress)
182    }
183
184    /// The still image that waits for a frame, as the
185    /// `still_image_request_id` of the updates that ask for it, or 0 when
186    /// none waits.
187    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    /// The map's scale factor, an `f64`'s bits: the options' pixel ratio,
211    /// until a session's resize sends another.
212    scale_factor: AtomicU64,
213    tile_cache_enabled: bool,
214    system_fonts: bool,
215    local_ideographs: bool,
216    /// The render session attached to the map, from its attach until its
217    /// detach completes.
218    session: Mutex<Option<SessionClaim>>,
219    /// The sequence number of the last command sent. It stays locked while
220    /// a command is numbered and posted, so the runtime's thread runs the
221    /// map's commands in the order of their numbers.
222    sent: Mutex<u64>,
223    /// Whether the handles refuse commands.
224    released: AtomicBool,
225    /// Whether the map's removal was posted to the runtime's thread.
226    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    /// A completion that the runtime's thread resolves, or with
249    /// `discard`, one whose result is discarded, as
250    /// [`Completion::discarded`] makes it.
251    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    /// Numbers a command and posts it to the runtime's thread.
259    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    /// Releases the map: no command is sent after its removal. Fails when
278    /// the map was released already.
279    fn release(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
280        self.close()?;
281        self.remove(done);
282        Ok(())
283    }
284
285    /// Refuses the commands sent from now on. Fails when the map was
286    /// released already.
287    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    /// Removes the closed map from its runtime's thread, after the commands
296    /// sent before, once.
297    fn remove(&self, done: Option<Resolver<()>>) {
298        if self.removed.swap(true, Ordering::SeqCst) {
299            return;
300        }
301        let id = self.id;
302        // A runtime that a panic stopped let go of the map already.
303        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/// A handle to a map, which lives on its runtime's thread.
325///
326/// Each command takes the next sequence number when it is sent and runs on
327/// the runtime's thread after every command sent before it, to this map,
328/// another map or the runtime. It returns a [`Completion`] of its result, or
329/// an error when it can't be sent, and then never completes. A command sent
330/// before the map is built waits for it. `Clone` is another handle to the
331/// same map, and any thread may use one.
332///
333/// The map lives until [`release`](Self::release) or until its last handle
334/// drops. A command on a released map fails with
335/// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind).
336#[derive(Clone)]
337pub struct Map {
338    pub(crate) shared: Arc<MapShared>,
339    /// Where the failures of the handle's commands go when it discards
340    /// their results.
341    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
366/// The error of a command whose map failed to be built, or was released
367/// while the command was on its way.
368pub(crate) fn missing_map() -> Error {
369    Error::invalid_state("the map failed to be built or was released")
370}
371
372/// What a render session runs with the outcome of a command it waits for.
373type Reply<T> = Box<dyn FnOnce(&mut Worker, Result<T, Error>, &mut Outbox) + Send>;
374
375/// What a render session waits for from a command on the runtime's thread:
376/// `reply` runs on the session's thread with the command's outcome, or with
377/// an error if the command drops without one, as when a panic stopped the
378/// runtime.
379struct 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    /// A handle to the same map whose commands discard their results, for a
414    /// caller that doesn't need them: each command's completion acts as one
415    /// whose result was taken, and costs no allocation, and a failure,
416    /// cancellations included, goes to `on_failure` on the runtime's thread.
417    #[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    /// Numbers a command and posts it to the runtime's thread, with a
423    /// completion as the handle makes them.
424    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    /// When the map renders, as its options set it.
437    #[must_use]
438    pub fn mode(&self) -> MapMode {
439        self.shared.mode
440    }
441
442    /// The runtime that the map lives on.
443    #[must_use]
444    pub fn runtime(&self) -> Runtime {
445        Runtime { shared: Arc::clone(&self.shared.runtime) }
446    }
447
448    /// The sequence number of the last command sent to the map.
449    #[must_use]
450    pub fn sent_sequence(&self) -> u64 {
451        *self.shared.sent.lock()
452    }
453
454    /// The sequence number of the last command that ran. While the
455    /// runtime's thread runs several queued commands as one burst, they
456    /// count once the frame that shows them all can.
457    #[must_use]
458    pub fn applied_sequence(&self) -> u64 {
459        self.shared.published.applied.load(Ordering::SeqCst)
460    }
461
462    /// The map's state after the last command that ran, without waiting for
463    /// the commands still on their way. To read the state after them, send a
464    /// command and read the snapshot once it completes, or use a query such
465    /// as [`camera`](Self::camera). Its `update_generation` counts the
466    /// renderer's updates as they are when it is read, which can be later
467    /// than the rest of the state.
468    ///
469    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) until the
470    /// map is built, and after it is released.
471    pub fn snapshot(&self) -> Result<MapSnapshot, Error> {
472        let mut snapshot = self.published(|state| state.snapshot.clone())?;
473        // The map publishes an update, which the renderer may draw at once,
474        // before it copies the snapshot: count the updates as they are now, so
475        // a frame never shows a later update than the snapshot.
476        if let Some(updates) = self.shared.published.updates.get() {
477            snapshot.update_generation = updates.generation();
478        }
479        Ok(snapshot)
480    }
481
482    /// A projection of `view`, or of the map's view as of
483    /// [`snapshot`](Self::snapshot) for `None`, on the ground the map drew
484    /// then (`mln_engine::map::Map::ground`): it converts as the map does, in
485    /// the view's projection, over terrain on the ground the renderer drew,
486    /// else on the flat map. It is the caller's, and doesn't follow the map.
487    ///
488    /// Fails as [`snapshot`](Self::snapshot) does, and for `view` as
489    /// [`MapView::to_state`](mln_engine::camera::MapView::to_state).
490    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    /// What `read` takes from the map's last flush. Fails with
496    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) until the map is
497    /// built, and after it is released.
498    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    /// The events that the map reports, as of the last command that ran.
506    #[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    /// Sends a command that runs `apply` on the map's entry, and completes
512    /// with what `finish` makes of its result and the map after it.
513    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    /// A command that changes the map.
524    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    /// A command that reads the map.
532    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    /// Runs `f` on the map itself, on the runtime's thread, in its place
540    /// among the map's commands. It sees the effects of the commands sent
541    /// before it. The map handles what `f` changed, and reports its events,
542    /// before the completion.
543    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    /// Releases the map. The completion reports when the runtime has let go
551    /// of it. A render session that was released, but hasn't let go of the
552    /// map yet, is abandoned, as
553    /// [`RenderSession::abandon`](crate::RenderSession::abandon) does: a
554    /// caller-driven one that the host stopped servicing would otherwise
555    /// hold the map for good.
556    ///
557    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the
558    /// map was released already, or while a render session that wasn't
559    /// released is attached to it.
560    pub fn release(&self) -> Result<Completion<()>, Error> {
561        self.release_with(false)
562    }
563
564    /// Releases the map whatever its state, as dropping its last handle
565    /// does, and lets the runtime finish in the background: the completion
566    /// reports when the runtime has let go of it, and may be dropped. Every
567    /// command fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
568    /// from now on. A render session that is attached and wasn't released
569    /// keeps drawing the map's last update, and the runtime lets go of the
570    /// map once the session detaches or is abandoned. A released one is
571    /// abandoned, as [`release`](Self::release) does.
572    ///
573    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the
574    /// map was released already.
575    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                    // Abandoned now, or ended already and about to let go.
587                    Some(session) if session.is_released() => Some((held.id, Some(session))),
588                    // The session lets go of the map when it ends, and the
589                    // map is removed then.
590                    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                    // The session is gone without letting go of the map.
597                    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    // MARK: - Map
612
613    /// Sets the map's size and scale factor. The map keeps its tiles, and a
614    /// resize to the extent the map has changes nothing, so it renders
615    /// nothing. Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
616    /// while a render session is attached, since the session sizes the map
617    /// to its target: resize the session instead. Fails with
618    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an empty size,
619    /// or a scale factor that isn't finite and positive.
620    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        // The scale factor that a session attached later renders at.
632        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    /// Renders a new frame of a continuous map, even when nothing changed.
642    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a
643    /// static or tile map, which renders only still images.
644    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    /// Holds the map's changes back from rendering until the matching
655    /// [`end_command_group`](Self::end_command_group), so that they show in
656    /// the same frame. Groups nest, and the changes show when the outermost
657    /// group ends.
658    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    /// Ends the group that [`begin_command_group`](Self::begin_command_group)
666    /// began. Completes with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
667    /// when no group is open.
668    pub fn end_command_group(&self) -> Result<Completion<Applied>, Error> {
669        self.command(mln_engine::map::Map::end_command_group)
670    }
671
672    /// Begins a command group that ends when the guard drops, or with
673    /// [`CommandGroup::end`].
674    pub fn command_group(&self) -> Result<CommandGroup, Error> {
675        drop(self.begin_command_group()?);
676        Ok(CommandGroup { map: Some(self.clone()) })
677    }
678
679    /// Selects the events that the map reports.
680    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    // MARK: - Rendering
695
696    /// Attaches a render session, which renders the map into `target`, and
697    /// sizes the map to the target. A map has one session at a time. The
698    /// session takes frame demands and other work at once, and runs them
699    /// once the completion reports it ready.
700    ///
701    /// The session renders on a thread of its own, or, with
702    /// [`Driver::CallerThread`](crate::Driver::CallerThread), on the thread
703    /// that takes its [`DriverWork`](crate::DriverWork): the attach completes
704    /// in that thread's first service.
705    ///
706    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the
707    /// map already has a session or was released, or a window is minimized
708    /// or has no client area, and with
709    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an empty
710    /// target, a [`Surface::wgpu`](crate::Surface::wgpu) without the
711    /// host's device, or a Win32 window with a pixel format of its own that
712    /// OpenGL would present to. The completion fails as
713    /// [`Device::new`](crate::Device::new) does when the
714    /// session has to create its device and can't, with
715    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the window or
716    /// surface had no area to present to by then, with
717    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when no GPU can present
718    /// to a window, and with [`ErrorKind::Failed`](mln_style::error::ErrorKind) when
719    /// the window has no surface to give.
720    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    /// Attaches a render session as [`attach`](Self::attach) does, and calls
729    /// `then` with it and the attach's completion before the session's
730    /// thread may deliver the attach's result. A callback that `then`
731    /// attaches with [`Completion::on_complete`] runs where the session
732    /// delivers it: on the session's thread, inside its driver call, even
733    /// when the session attaches before `then` runs. One attached after
734    /// `attach` returned would run at once on this thread instead.
735    ///
736    /// `then` keeps the session with a clone of it: the session is released
737    /// once its last handle drops. Fails as `attach` does, before `then`
738    /// runs.
739    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    /// Renders a still image of a static or tile map, once every resource
749    /// that it needs has loaded. The map's render session draws it, and
750    /// [`RenderSession::read_texture`] reads its pixels once the completion
751    /// reports success.
752    ///
753    /// While the image waits, the session has a demand of its own for it,
754    /// whose [`FrameResult`](crate::FrameResult) has no token. The demand
755    /// waits for the map to load what the image needs, and parks while a
756    /// borrowed ring has no texture to render into. It finishes with the
757    /// image's frame, which completes the image once its result is queued:
758    /// a frame of the host's demands completes none. The host's demands
759    /// neither replace it nor are replaced by it. When the session ends its
760    /// demands, by a barrier, a target's release or a detach, the demand
761    /// ends too, and the image waits for the next one: once the barrier ran,
762    /// the target came back, or the next session attached.
763    ///
764    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a
765    /// continuous map. Completes with
766    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) while another image
767    /// is on its way or a command group is open,
768    /// [`ErrorKind::Failed`](mln_style::error::ErrorKind) when the
769    /// style or a resource that the image needs fails to load, and
770    /// [`ErrorKind::Cancelled`](mln_style::error::ErrorKind) when the map is released
771    /// first.
772    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                    // The group holds back the update that the image needs.
791                    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    /// Whether the map was released or disposed.
804    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    /// The map's scale factor: device pixels per logical pixel. It is the
813    /// pixel ratio of the map's options until a render session's
814    /// [`resize`](crate::RenderSession::resize) sets another, and the map's
815    /// next session renders at it.
816    #[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    /// Holds the map's frame clock at `time` (see [`FrameClock::hold`]).
826    #[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    /// How many worker instances behind the worker codec the tile workers
834    /// of a session's renderer run in, or 0 for the runtime's pool.
835    pub(crate) fn tile_worker_instances(&self) -> usize {
836        self.shared.runtime.tile_worker_instances.load(Ordering::SeqCst)
837    }
838
839    /// How the map's renderers draw glyphs from local fonts: with system
840    /// fonts, from the fonts the system chooses, or in the browser, which
841    /// has no font files, from the browser's canvas, falling back to its
842    /// sans-serif font as MapLibre GL JS's `localIdeographFontFamily`
843    /// defaults to.
844    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    /// Where the runtime's background work runs.
867    pub(crate) fn pool(&self) -> Pool {
868        self.shared.runtime.pool.clone()
869    }
870
871    /// What the renderers of the runtime's maps load font faces with.
872    pub(crate) fn font_face_engine(&self) -> Arc<dyn FontFaceEngine> {
873        Arc::clone(&self.shared.runtime.font_face_engine)
874    }
875
876    /// What the map parses its style against, its renderer draws and its
877    /// tile workers lay out: its runtime's
878    /// [`registry`](crate::Runtime::registry). A filter for a query parses
879    /// against its functions.
880    #[must_use]
881    pub fn registry(&self) -> &Arc<Registry> {
882        &self.shared.runtime.registry
883    }
884
885    /// Reserves the map for the session `id`.
886    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    /// Lets another session attach once the session `id` is gone, and
899    /// removes the map when a dispose waited for the session.
900    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    /// Sends the command that binds the session `id`, whose thread runs
911    /// `queue`, to the map: it sizes the map to `size`, and hands the
912    /// session the map's updates. The map tells the session of the commands
913    /// it runs from `awaited` on.
914    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    /// Unbinds the session `id` from the map on the runtime's thread, after
950    /// the commands sent before.
951    pub(crate) fn unbind_session(&self, id: SessionId) {
952        let map_id = self.shared.id;
953        // A runtime that shut down has no map to unbind from.
954        self.shared.runtime.post_or((), move |core, _, ()| unbind(core, map_id, id), |()| {});
955    }
956
957    /// Unbinds the session `id` as [`unbind_session`](Self::unbind_session)
958    /// does, then runs `then` on the session's thread.
959    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        // A runtime that shut down or stopped has no map to unbind from, and
968        // the reply's drop runs `then`.
969        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    /// For a frame demanded now: sets the map's frame clock, which its
980    /// animations sample at and its camera commands start from, and while
981    /// an animation runs, has the map sample it at this time. Returns the
982    /// sample that the frame waits for, or 0 for none. The demands that ask
983    /// before the runtime's thread takes a sample share it.
984    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        // A still map has nothing to sample, and its frames don't wait for
990        // the runtime's thread.
991        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    /// Sends a command that resizes the map to `size` at `scale_factor`,
1003    /// then runs `resize` with its outcome on the thread of the session that
1004    /// `queue` runs, before the session learns of any later command.
1005    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        // The scale factor that a session attached later renders at.
1013        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                    // A host may hand the session the target it has, such as
1027                    // on every frame. That changes nothing, so it publishes
1028                    // no update, which a demand sent before would draw.
1029                    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    // MARK: - Feature state
1044
1045    /// Merges `state` into the state of the feature that `selector` names:
1046    /// its keys replace the same keys of the feature's state, and the other
1047    /// keys stay.
1048    ///
1049    /// The map keeps the state until it is removed, its source leaves the
1050    /// style, or a style loads: [`remove_style_source`](Self::remove_style_source)
1051    /// removes the state of the source's features, and a style that loads
1052    /// removes the state of every source. To set state for a new style's
1053    /// sources, wait until [`set_style_url`](Self::set_style_url) or
1054    /// [`set_style_json`](Self::set_style_json) completes.
1055    ///
1056    /// The map's next update for its render session carries the state, so a
1057    /// frame shows it, and a rendered query reads it, once the frame renders
1058    /// that update. A command that changes no state publishes no update: an
1059    /// empty `state` merges nothing.
1060    ///
1061    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
1062    /// selector without a feature.
1063    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    /// The state of the feature that `selector` names, empty when it has
1077    /// none. Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind)
1078    /// for a selector without a feature.
1079    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    /// Removes the state that `selector` selects: one key of a feature, all
1088    /// of a feature's state, or that of every feature in a source layer.
1089    /// The removal reaches the render session as
1090    /// [`set_feature_state`](Self::set_feature_state) describes, and a
1091    /// removal of no state publishes no update. Fails with
1092    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a state key
1093    /// without a feature.
1094    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    // MARK: - Style
1108
1109    /// Loads the map's style from `url`.
1110    ///
1111    /// Completes once the style document has loaded and parsed, with
1112    /// [`ErrorKind::Failed`](mln_style::error::ErrorKind) when it fails to, and with
1113    /// [`ErrorKind::Cancelled`](mln_style::error::ErrorKind) when another style load
1114    /// starts or the map is released first. The style's sources, sprites and
1115    /// glyphs then load in the background. Commands that change the style
1116    /// fail with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) until the
1117    /// document has parsed.
1118    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    /// Loads the map's style from JSON text. Completes as
1127    /// [`set_style_url`](Self::set_style_url) does, once the style has
1128    /// parsed, but with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind)
1129    /// for JSON that isn't a valid style. A style that fails to parse leaves
1130    /// the map's style as it was.
1131    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    /// The JSON of the style that the map loaded, without the changes made
1146    /// since.
1147    pub fn loaded_style_json(&self) -> Result<Completion<String>, Error> {
1148        self.query(|map| Ok(map.style().json().to_owned()))
1149    }
1150
1151    /// The URL of the map's style, or `None` for a style loaded from JSON.
1152    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    /// Adds a source to the style from its JSON. See
1157    /// `mln_engine::map::Map::add_source_json` for the errors.
1158    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    /// Removes a source from the style. Completes with
1168    /// [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when the style has no
1169    /// such source, and [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
1170    /// when a layer uses it or the style isn't loaded. The source's features
1171    /// lose their state, and a value held for the source drops before the
1172    /// completion.
1173    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    /// Adds a layer to the style from its JSON, below `before_layer_id` or
1197    /// above every layer. See `Style::add_layer_json` for the errors.
1198    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    /// Adds `layer` to the style, below `before_layer_id` or above every
1208    /// layer: one of a type that isn't made from JSON, or one that holds a
1209    /// value for as long as the style has it
1210    /// ([`Layer::from_style_holding`](mln_style::layer::Layer::from_style_holding)).
1211    /// See `Style::add_layer` for the errors.
1212    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    /// Removes a layer from the style. Completes with
1221    /// [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when the style has no
1222    /// such layer, and [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
1223    /// while the style isn't loaded.
1224    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    /// A layer of the style as JSON, or `None` when the style has no such
1230    /// layer.
1231    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    /// Sets a property of a layer to a JSON value. See
1237    /// `Style::set_layer_property_json` for the errors.
1238    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    /// A property of a layer as JSON, or `None` when the layer doesn't set
1249    /// it. See `Style::layer_property_json` for the errors.
1250    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    /// Sets a root property of the style to a JSON value, without
1260    /// reloading the style. See `Style::set_root_property_json` for the
1261    /// properties that change and the errors.
1262    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    /// A root property of the style as JSON, or `None` when neither the
1272    /// style nor the map sets it. See `Style::root_property_json`.
1273    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    /// Sets a property of the style's light to a JSON value.
1279    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    /// A property of the style's light as JSON, or `None` when the light
1289    /// doesn't set it.
1290    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    // MARK: - Camera
1296
1297    /// A command that moves the camera: `apply` starts a camera command,
1298    /// whose end nobody waits for.
1299    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    /// A command that moves the camera, whose end `on_end` receives. `on_end`
1307    /// is in place before the command is sent, so it runs on the runtime's
1308    /// thread, or on this one with
1309    /// [`ErrorKind::Cancelled`](mln_style::error::ErrorKind) when the send fails.
1310    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    /// Sends a camera command, and `end`, if any, the command's end: a
1321    /// failure ends it as cancelled.
1322    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    /// Moves the camera to absolute values, by a jump, an ease or a flight.
1349    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    /// Moves the camera as [`update_camera`](Self::update_camera) does, and
1354    /// calls `on_end` with how the change ended, on the runtime's thread:
1355    /// once the map has published the snapshot that shows where the change
1356    /// left the camera, whose generation the end reports, and before the
1357    /// returned completion when the change ends within the command. A
1358    /// command that fails ends as cancelled, and one that the map's release
1359    /// ends as closed, with generation 0. `on_end` runs on this thread only
1360    /// with [`ErrorKind::Cancelled`](mln_style::error::ErrorKind), when the send
1361    /// fails.
1362    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    /// Moves the camera relative to where it is, as a gesture does.
1371    /// Completes with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for
1372    /// a delta that the camera can't apply.
1373    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    /// Applies `delta` as [`apply_camera_delta`](Self::apply_camera_delta)
1380    /// does, and calls `on_end` with how the change ended, as
1381    /// [`update_camera_then`](Self::update_camera_then) does.
1382    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    /// The camera that fits `area` in the map's view, after the commands
1394    /// sent before, as [`mln_engine::map::Map::camera_for_lat_lngs`] fits
1395    /// it. Its zoom stays within the map's zoom limits.
1396    ///
1397    /// Completes with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for
1398    /// an empty area, and for padding and margin that leave no room for it.
1399    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    /// Moves the camera to the one that [`camera_for`](Self::camera_for)
1408    /// finds once the commands sent before have run, as
1409    /// [`update_camera`](Self::update_camera) moves it.
1410    ///
1411    /// Completes as `camera_for` fails, and then leaves the camera where it
1412    /// is and ends the animation as cancelled.
1413    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    /// Fits the camera as [`fit_camera`](Self::fit_camera) does, and calls
1418    /// `on_end` with how the change ended, as
1419    /// [`update_camera_then`](Self::update_camera_then) does.
1420    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    /// Stops every camera animation.
1430    pub fn cancel_camera_transitions(&self) -> Result<Completion<Applied>, Error> {
1431        self.command(|map| {
1432            map.cancel_transitions();
1433            Ok(())
1434        })
1435    }
1436
1437    /// Stops the camera animations whose transition ID is `transition_id`.
1438    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    /// The camera after the commands sent before.
1446    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    /// The area that `camera` would show, with the fields that `camera`
1454    /// leaves out from the map's camera. It holds every corner of a rotated
1455    /// view, and its longitudes can pass ±180, so a view across the
1456    /// antimeridian gives one continuous range.
1457    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    /// Sets the limits on the camera.
1462    pub fn set_bounds(&self, bounds: BoundOptions) -> Result<Completion<Applied>, Error> {
1463        self.command(move |map| map.set_bounds(&bounds))
1464    }
1465
1466    /// Sets the camera's position and orientation in three dimensions.
1467    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    /// Sets how the map orients and constrains its view.
1475    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    /// Sets how the map picks the tiles to load.
1483    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    /// Logs the style's sources and their state.
1498    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/// A command group of a map that ends when it drops.
1507#[must_use = "the group ends when it drops"]
1508pub struct CommandGroup {
1509    map: Option<Map>,
1510}
1511
1512impl CommandGroup {
1513    /// Ends the group, as [`Map::end_command_group`] does.
1514    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
1535/// A style load that hasn't completed.
1536struct PendingStyle {
1537    resolver: Resolver<Applied>,
1538    /// Whether the caller passed the style document, which then is the
1539    /// argument that fails to parse.
1540    from_json: bool,
1541}
1542
1543/// The render session that a map is reserved for.
1544struct SessionClaim {
1545    id: SessionId,
1546    session: Weak<SessionShared>,
1547    /// The completion of a dispose that waits for the session to end.
1548    removal: Option<Resolver<()>>,
1549}
1550
1551/// Forgets the session `id` on the runtime's thread, unless the map has
1552/// bound another since.
1553fn 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
1561/// The render session bound to a map, as the runtime's thread knows it.
1562pub(crate) struct SessionLink {
1563    id: SessionId,
1564    queue: SessionQueue,
1565    /// The session's `awaited_command`.
1566    awaited: Arc<AtomicU64>,
1567}
1568
1569/// A still image on its way, whose outcome the next flush that finds it
1570/// reports.
1571struct PendingStill {
1572    resolver: Resolver<()>,
1573    /// Why the map refused the image, which the flush after the command
1574    /// reports.
1575    refused: Option<Result<(), Error>>,
1576}
1577
1578/// A still image's error as the handle reports it: a load failure is the
1579/// library's, whatever the core called it.
1580fn still_image_error(error: Error) -> Error {
1581    match error.kind {
1582        ErrorKind::InvalidState => error,
1583        _ => Error::failed(error.message),
1584    }
1585}
1586
1587/// A map on the runtime's thread.
1588pub(crate) struct MapEntry {
1589    pub(crate) core: mln_engine::map::Map,
1590    published: Arc<Published>,
1591    mask: EventMask,
1592    /// The sequence number of the last command that ran.
1593    applied: u64,
1594    /// The last command and frame sample that ran while a burst held the
1595    /// map's updates back, which the session learns of once they show.
1596    held_applied: Option<u64>,
1597    held_sampled: Option<u64>,
1598    /// The style load in progress.
1599    pending_style: Option<PendingStyle>,
1600    pending_still: Option<PendingStill>,
1601    /// The render session that draws the map.
1602    session: Option<SessionLink>,
1603    /// Set while the map has reported something that no flush has taken.
1604    flush_pending: FlushFlag,
1605    /// The camera commands whose change hasn't ended.
1606    camera_commands: HashMap<CameraCommandId, Resolver<TransitionEnd>>,
1607    /// The values held for the sources that commands added with them.
1608    pub(crate) held_sources: HeldSources,
1609    /// The GeoJSON data that commands set and that is still being built.
1610    pub(crate) geojson_updates: GeoJsonUpdates,
1611    /// The repaint posted for when the map changes next on its own
1612    /// ([`mln_engine::map::Map::repaint_at`]).
1613    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/// Whether a map reported something that no flush has taken: what its
1627/// reports waker sets. Reports that come before the flush they posted runs
1628/// share it.
1629#[derive(Clone, Default)]
1630struct FlushFlag(Arc<AtomicBool>);
1631
1632impl FlushFlag {
1633    /// The map `id`'s reports waker: it sets the flag, and posts a flush to
1634    /// `queue` when the flag was clear. The posted flush does nothing once
1635    /// another flush took the reports.
1636    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
1661/// Builds the map `id` on the runtime's thread.
1662pub(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
1713/// Runs a command on the map `id`, which must be there: handles what came
1714/// before it, applies it, publishes the map's state, sends its events, and
1715/// runs `after` with what `apply` returned. Then it tells the map's render
1716/// session that the command ran, so `after` can send the session what the
1717/// session must see first. While a burst holds the map's updates back, it
1718/// tells the session once they show, so that no frame that waits for the
1719/// command draws the update before it.
1720pub(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    // What the runtime's calls change, a flush in the same task takes. What
1729    // came since then, the map reported: the report posted a flush, or is
1730    // queued with its waker still on its way.
1731    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
1748/// Tells the map's session that the command `sequence` ran, once a frame can
1749/// show it.
1750fn 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
1759/// Tells the map's session that the map took the frame sample `sample`, once
1760/// a frame can show it.
1761fn 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
1768/// Tells the map's session what ran while a burst held the map's updates
1769/// back, now that they show.
1770pub(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
1779/// Has the map `id` sample its animations at its frame clock's time for the
1780/// frame samples that demands asked for.
1781fn sample_frame(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1782    let Some(entry) = core.maps.get(&id) else { return };
1783    // A demand from now on asks for another sample.
1784    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
1801/// Runs a command on the map `id` and completes with what `finish` makes of
1802/// its result and the map after it.
1803pub(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
1820/// Starts a style load on the map `id`. Its completion waits for the load's
1821/// outcome, which a flush finds among the map's events.
1822fn 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    // The flush before the load sends the outcomes of earlier loads to their
1834    // own completions.
1835    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
1854/// Handles what the map's style and renderer reported, publishes its state
1855/// if it changed, and sends its events. A flush with nothing to handle and no
1856/// change to publish costs little, so callers flush whenever they may need
1857/// to.
1858pub(crate) fn flush(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1859    let Some(entry) = core.maps.get_mut(&id) else { return };
1860    // The flush takes what the map reported so far, and what it reports from
1861    // now on posts another.
1862    entry.flush_pending.clear();
1863    let events = entry.core.drain_events();
1864    // A held clock moves only when its holder moves it, so the system's
1865    // clock doesn't repaint the map.
1866    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    // The sources that left the style, by a command or a style load, let go
1875    // of what they held before anything reports the change.
1876    crate::style::reconcile(entry, outbox);
1877    let generation = entry.core.generation();
1878    // The camera commands that ended report the snapshot that shows them.
1879    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    // Each change to the state grows the generation, so a snapshot of the
1885    // same generation shows the state as it is.
1886    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    // The renderer's ground changes the map's conversions, though not
1892    // always its state.
1893    *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    // The session demands a frame for the image while it waits, and lets
1918    // the demand go once it doesn't.
1919    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
1946/// Draws the map `id` once its last frame's time to change came.
1947fn 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    // A timer set before the clock was held doesn't move the held map.
1951    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
1957/// Lets go of the map `id`, after sending the events it still had.
1958fn 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        // The handles, which may outlive the map, keep no ground or
1966        // registered projection alive.
1967        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        // The map's camera changes end as closed as it drops, with no
1979        // snapshot to show them.
1980        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}