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