Skip to main content

mln_runtime/
map.rs

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