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