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