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