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_fonts::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::SystemFonts`). On by default. The first map that
60    /// uses them waits for the platform's font matcher to load. In the
61    /// 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: with system
781    /// fonts, from the fonts the system chooses, or in the browser, which
782    /// has no font files, from the browser's canvas, falling back to its
783    /// sans-serif font as MapLibre GL JS's `localIdeographFontFamily`
784    /// defaults to.
785    pub(crate) fn local_glyphs(&self) -> LocalGlyphs {
786        let mut local = LocalGlyphs { ideographs: self.shared.local_ideographs, ..LocalGlyphs::default() };
787        if self.shared.system_fonts {
788            #[cfg(not(target_family = "wasm"))]
789            {
790                local.chooser = Some(Arc::new(mln_system_fonts::SystemFonts));
791            }
792            #[cfg(target_family = "wasm")]
793            {
794                let font_family = "sans-serif".to_owned();
795                local.rasterizer =
796                    Some(Arc::new(mln_text::browser_glyph_rasterizer::BrowserGlyphRasterizer::new(font_family)));
797            }
798        }
799        local
800    }
801
802    pub(crate) fn glyph_cache(&self) -> Arc<GlyphCache> {
803        Arc::clone(&self.shared.runtime.glyph_cache)
804    }
805
806    /// Where the runtime's background work runs.
807    pub(crate) fn pool(&self) -> Pool {
808        self.shared.runtime.pool.clone()
809    }
810
811    /// What the renderers of the runtime's maps load font faces with.
812    pub(crate) fn font_face_engine(&self) -> Arc<dyn FontFaceEngine> {
813        Arc::clone(&self.shared.runtime.font_face_engine)
814    }
815
816    /// What the map parses its style against, its renderer draws and its
817    /// tile workers lay out: its runtime's
818    /// [`registry`](crate::Runtime::registry). A filter for a query parses
819    /// against its functions.
820    #[must_use]
821    pub fn registry(&self) -> &Arc<Registry> {
822        &self.shared.runtime.registry
823    }
824
825    /// Reserves the map for the session `id`.
826    pub(crate) fn claim_session(&self, id: SessionId, session: Weak<SessionShared>) -> Result<(), Error> {
827        let mut claim = self.shared.session.lock();
828        if self.shared.released.load(Ordering::SeqCst) {
829            return Err(released());
830        }
831        if claim.is_some() {
832            return Err(Error::invalid_state("the map already has an attached render session"));
833        }
834        *claim = Some(SessionClaim { id, session, removal: None });
835        Ok(())
836    }
837
838    /// Lets another session attach once the session `id` is gone, and
839    /// removes the map when a dispose waited for the session.
840    pub(crate) fn release_session_claim(&self, id: SessionId) {
841        let claim = {
842            let mut session = self.shared.session.lock();
843            if session.as_ref().is_some_and(|claim| claim.id == id) { session.take() } else { None }
844        };
845        if let Some(removal) = claim.and_then(|claim| claim.removal) {
846            self.shared.remove(Some(removal));
847        }
848    }
849
850    /// Sends the command that binds the session `id`, whose thread runs
851    /// `queue`, to the map: it sizes the map to `size`, and hands the
852    /// session the map's updates. The map tells the session of the commands
853    /// it runs from `awaited` on.
854    pub(crate) fn bind_session(
855        &self,
856        id: SessionId,
857        queue: SessionQueue,
858        awaited: Arc<AtomicU64>,
859        size: Size,
860    ) -> Result<(), Error> {
861        let reply = SessionReply::new(queue.clone(), |worker, bound, outbox| match bound {
862            Ok((sequence, reader, events, published)) => worker.bound(sequence, reader, events, published, outbox),
863            Err(error) => worker.bind_failed(error, outbox),
864        });
865        let sent = self.shared.send(Some(drop), move |core, outbox, map_id, sequence, resolver: Resolver<()>| {
866            drop(resolver);
867            if !core.maps.contains_key(&map_id) {
868                return reply.send(Err(missing_map()));
869            }
870            let link = SessionLink { id, queue, awaited };
871            apply_command(
872                core,
873                map_id,
874                sequence,
875                outbox,
876                move |entry, _| {
877                    entry.session = Some(link);
878                    let resized = entry.core.set_size(size);
879                    (resized, entry.core.update_reader(), entry.core.renderer_events(), Arc::clone(&entry.published))
880                },
881                move |_, (resized, reader, events, published), _, _| {
882                    reply.send(resized.map(|()| (sequence, reader, events, published)));
883                },
884            );
885        });
886        sent.map(drop)
887    }
888
889    /// Unbinds the session `id` from the map on the runtime's thread, after
890    /// the commands sent before.
891    pub(crate) fn unbind_session(&self, id: SessionId) {
892        let map_id = self.shared.id;
893        // A runtime that shut down has no map to unbind from.
894        self.shared.runtime.post_or((), move |core, _, ()| unbind(core, map_id, id), |()| {});
895    }
896
897    /// Unbinds the session `id` as [`unbind_session`](Self::unbind_session)
898    /// does, then runs `then` on the session's thread.
899    pub(crate) fn unbind_session_then(
900        &self,
901        id: SessionId,
902        queue: SessionQueue,
903        then: impl FnOnce(&mut Worker, &mut Outbox) + Send + 'static,
904    ) {
905        let map_id = self.shared.id;
906        let reply = SessionReply::new(queue, move |worker, _: Result<(), Error>, outbox| then(worker, outbox));
907        // A runtime that shut down or stopped has no map to unbind from, and
908        // the reply's drop runs `then`.
909        self.shared.runtime.post_or(
910            reply,
911            move |core, _, reply| {
912                unbind(core, map_id, id);
913                reply.send(Ok(()));
914            },
915            drop,
916        );
917    }
918
919    /// For a frame demanded now: sets the map's frame clock, which its
920    /// animations sample at and its camera commands start from, and while
921    /// an animation runs, has the map sample it at this time. Returns the
922    /// sample that the frame waits for, or 0 for none. The demands that ask
923    /// before the runtime's thread takes a sample share it.
924    pub(crate) fn frame_demanded(&self) -> u64 {
925        let published = &self.shared.published;
926        if let Some(clock) = published.frame_clock.get() {
927            clock.set(Some(Instant::now()));
928        }
929        // A still map has nothing to sample, and its frames don't wait for
930        // the runtime's thread.
931        if self.shared.mode != MapMode::Continuous || !published.animating() {
932            return 0;
933        }
934        let sample = published.samples_requested.fetch_add(1, Ordering::SeqCst) + 1;
935        if !published.sample_queued.swap(true, Ordering::SeqCst) {
936            let id = self.shared.id;
937            self.shared.runtime.post_apart(move |core, outbox| sample_frame(core, id, outbox));
938        }
939        sample
940    }
941
942    /// Sends a command that resizes the map to `size` at `scale_factor`,
943    /// then runs `resize` with its outcome on the thread of the session that
944    /// `queue` runs, before the session learns of any later command.
945    pub(crate) fn resize_for_session(
946        &self,
947        size: Size,
948        scale_factor: f64,
949        queue: SessionQueue,
950        resize: impl FnOnce(&mut Worker, Result<Applied, Error>, &mut Outbox) + Send + 'static,
951    ) -> Result<(), Error> {
952        // The scale factor that a session attached later renders at.
953        self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
954        let reply = SessionReply::new(queue, resize);
955        let sent = self.shared.send(Some(drop), move |core, outbox, id, sequence, resolver: Resolver<()>| {
956            drop(resolver);
957            if !core.maps.contains_key(&id) {
958                return reply.send(Err(missing_map()));
959            }
960            apply_command(
961                core,
962                id,
963                sequence,
964                outbox,
965                move |entry, _| {
966                    // A host may hand the session the target it has, such as
967                    // on every frame. That changes nothing, so it publishes
968                    // no update, which a demand sent before would draw.
969                    let pixel_ratio = scale_factor as f32;
970                    let extent = entry.core.snapshot().view.extent;
971                    if extent.size == size && extent.scale_factor == f64::from(pixel_ratio) {
972                        return Ok(());
973                    }
974                    entry.core.set_size(size)?;
975                    entry.core.set_pixel_ratio(pixel_ratio)
976                },
977                move |_, resized, applied, _| reply.send(resized.map(|()| applied)),
978            );
979        });
980        sent.map(drop)
981    }
982
983    // MARK: - Feature state
984
985    /// Merges `state` into the state of the feature that `selector` names:
986    /// its keys replace the same keys of the feature's state, and the other
987    /// keys stay.
988    ///
989    /// The map keeps the state until it is removed, its source leaves the
990    /// style, or a style loads: [`remove_style_source`](Self::remove_style_source)
991    /// removes the state of the source's features, and a style that loads
992    /// removes the state of every source. To set state for a new style's
993    /// sources, wait until [`set_style_url`](Self::set_style_url) or
994    /// [`set_style_json`](Self::set_style_json) completes.
995    ///
996    /// The map's next update for its render session carries the state, so a
997    /// frame shows it, and a rendered query reads it, once the frame renders
998    /// that update. A command that changes no state publishes no update: an
999    /// empty `state` merges nothing.
1000    ///
1001    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
1002    /// selector without a feature.
1003    pub fn set_feature_state(
1004        &self,
1005        selector: &FeatureStateSelector,
1006        state: FeatureState,
1007    ) -> Result<Completion<Applied>, Error> {
1008        let key = selector.key(true)?;
1009        self.command(move |map| {
1010            let feature_id = key.feature_id.as_deref().unwrap_or_default();
1011            map.set_feature_state(&key.source_id, Some(&key.source_layer_id), feature_id, state);
1012            Ok(())
1013        })
1014    }
1015
1016    /// The state of the feature that `selector` names, empty when it has
1017    /// none. Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind)
1018    /// for a selector without a feature.
1019    pub fn feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<FeatureState>, Error> {
1020        let key = selector.key(true)?;
1021        self.query(move |map| {
1022            let feature_id = key.feature_id.as_deref().unwrap_or_default();
1023            Ok(map.feature_state(&key.source_id, Some(&key.source_layer_id), feature_id))
1024        })
1025    }
1026
1027    /// Removes the state that `selector` selects: one key of a feature, all
1028    /// of a feature's state, or that of every feature in a source layer.
1029    /// The removal reaches the render session as
1030    /// [`set_feature_state`](Self::set_feature_state) describes, and a
1031    /// removal of no state publishes no update. Fails with
1032    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a state key
1033    /// without a feature.
1034    pub fn remove_feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<Applied>, Error> {
1035        let key = selector.key(false)?;
1036        self.command(move |map| {
1037            map.remove_feature_state(
1038                &key.source_id,
1039                Some(&key.source_layer_id),
1040                key.feature_id.as_deref(),
1041                key.state_key.as_deref(),
1042            );
1043            Ok(())
1044        })
1045    }
1046
1047    // MARK: - Style
1048
1049    /// Loads the map's style from `url`.
1050    ///
1051    /// Completes once the style document has loaded and parsed, with
1052    /// [`ErrorKind::Native`](mln_util::ErrorKind) when it fails to, and with
1053    /// [`ErrorKind::Cancelled`](mln_util::ErrorKind) when another style load
1054    /// starts or the map is released first. The style's sources, sprites and
1055    /// glyphs then load in the background. Commands that change the style
1056    /// fail with [`ErrorKind::InvalidState`](mln_util::ErrorKind) until the
1057    /// document has parsed.
1058    pub fn set_style_url(&self, url: impl Into<String>) -> Result<Completion<Applied>, Error> {
1059        let url = url.into();
1060        if url.is_empty() {
1061            return Err(Error::invalid_argument("style URL must not be empty"));
1062        }
1063        self.load_style(StyleLoad::Url(url))
1064    }
1065
1066    /// Loads the map's style from JSON text. Completes as
1067    /// [`set_style_url`](Self::set_style_url) does, once the style has
1068    /// parsed, but with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind)
1069    /// for JSON that isn't a valid style. A style that fails to parse leaves
1070    /// the map's style as it was.
1071    pub fn set_style_json(&self, json: impl Into<String>) -> Result<Completion<Applied>, Error> {
1072        let json = json.into();
1073        if json.is_empty() {
1074            return Err(Error::invalid_argument("style JSON must not be empty"));
1075        }
1076        self.load_style(StyleLoad::Json(json))
1077    }
1078
1079    fn load_style(&self, load: StyleLoad) -> Result<Completion<Applied>, Error> {
1080        self.post(move |core, outbox, id, sequence, resolver| {
1081            load_style(core, id, sequence, load, resolver, outbox);
1082        })
1083    }
1084
1085    /// The JSON of the style that the map loaded, without the changes made
1086    /// since.
1087    pub fn loaded_style_json(&self) -> Result<Completion<String>, Error> {
1088        self.query(|map| Ok(map.style().get_json().to_owned()))
1089    }
1090
1091    /// The URL of the map's style, or `None` for a style loaded from JSON.
1092    pub fn style_url(&self) -> Result<Completion<Option<String>>, Error> {
1093        self.query(|map| Ok(map.style_url().filter(|url| !url.is_empty()).map(str::to_owned)))
1094    }
1095
1096    /// Adds a source to the style from its JSON. See
1097    /// `mln_map::Map::add_source_json` for the errors.
1098    pub fn add_style_source_json(
1099        &self,
1100        source_id: impl Into<String>,
1101        json: impl Into<String>,
1102    ) -> Result<Completion<Applied>, Error> {
1103        let (source_id, json) = (source_id.into(), json.into());
1104        self.command(move |map| map.add_source_json(&source_id, &json))
1105    }
1106
1107    /// Removes a source from the style. Completes with
1108    /// [`ErrorKind::NotFound`](mln_util::ErrorKind) when the style has no
1109    /// such source, and [`ErrorKind::InvalidState`](mln_util::ErrorKind)
1110    /// when a layer uses it or the style isn't loaded. The source's features
1111    /// lose their state, and a custom source's callbacks drop before the
1112    /// completion.
1113    pub fn remove_style_source(&self, source_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1114        let source_id = source_id.into();
1115        self.send(
1116            move |entry, _| {
1117                let map = &mut entry.core;
1118                if !map.style_document_loaded() {
1119                    return Err(style_not_loaded());
1120                }
1121                if map.source(&source_id).is_none() {
1122                    return Err(Error::not_found(format!("source \"{source_id}\" does not exist")));
1123                }
1124                if let Some(layer) = map.style().get_layers().find(|layer| layer.get_source_id() == source_id) {
1125                    let message = format!("source \"{source_id}\" is used by layer \"{}\"", layer.get_id());
1126                    return Err(Error::invalid_state(message));
1127                }
1128                map.remove_source(&source_id);
1129                entry.core.remove_source_feature_state(&source_id);
1130                Ok(())
1131            },
1132            |(), entry| entry.applied(),
1133        )
1134    }
1135
1136    /// Adds a layer to the style from its JSON, below `before_layer_id` or
1137    /// above every layer. See `Style::add_layer_json` for the errors.
1138    pub fn add_style_layer_json(
1139        &self,
1140        json: impl Into<String>,
1141        before_layer_id: Option<String>,
1142    ) -> Result<Completion<Applied>, Error> {
1143        let json = json.into();
1144        self.command(move |map| map.edit_loaded_style(|style| style.add_layer_json(&json, before_layer_id.as_deref())))
1145    }
1146
1147    /// Adds a custom layer named `layer_id` that `host` draws, below
1148    /// `before_layer_id` or above every layer. See `Style::add_custom_layer`
1149    /// for the errors. The map lets go of `host` once the style no longer has
1150    /// the layer, and no renderer draws it.
1151    pub fn add_custom_layer(
1152        &self,
1153        layer_id: impl Into<String>,
1154        host: Arc<dyn CustomLayerHost>,
1155        before_layer_id: Option<String>,
1156    ) -> Result<Completion<Applied>, Error> {
1157        let layer_id = layer_id.into();
1158        self.command(move |map| {
1159            map.edit_loaded_style(|style| style.add_custom_layer(&layer_id, host, before_layer_id.as_deref()))
1160        })
1161    }
1162
1163    /// Removes a layer from the style. Completes with
1164    /// [`ErrorKind::NotFound`](mln_util::ErrorKind) when the style has no
1165    /// such layer, and [`ErrorKind::InvalidState`](mln_util::ErrorKind)
1166    /// while the style isn't loaded.
1167    pub fn remove_style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
1168        let layer_id = layer_id.into();
1169        self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::RemoveLayer(layer_id))))
1170    }
1171
1172    /// A layer of the style as JSON, or `None` when the style has no such
1173    /// layer.
1174    pub fn style_layer_json(&self, layer_id: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1175        let layer_id = layer_id.into();
1176        self.query(move |map| Ok(map.style().layer_json(&layer_id)))
1177    }
1178
1179    /// Sets a property of a layer to a JSON value. See
1180    /// `Style::set_layer_property_json` for the errors.
1181    pub fn set_style_layer_property(
1182        &self,
1183        layer_id: impl Into<String>,
1184        name: impl Into<String>,
1185        json: impl Into<String>,
1186    ) -> Result<Completion<Applied>, Error> {
1187        let (layer_id, name, json) = (layer_id.into(), name.into(), json.into());
1188        self.command(move |map| map.edit_loaded_style(|style| style.set_layer_property_json(&layer_id, &name, &json)))
1189    }
1190
1191    /// A property of a layer as JSON, or `None` when the layer doesn't set
1192    /// it. See `Style::layer_property_json` for the errors.
1193    pub fn style_layer_property(
1194        &self,
1195        layer_id: impl Into<String>,
1196        name: impl Into<String>,
1197    ) -> Result<Completion<Option<String>>, Error> {
1198        let (layer_id, name) = (layer_id.into(), name.into());
1199        self.query(move |map| map.style().layer_property_json(&layer_id, &name))
1200    }
1201
1202    /// Sets a root property of the style to a JSON value, without
1203    /// reloading the style. See `Style::set_root_property_json` for the
1204    /// properties that change and the errors.
1205    pub fn set_style_root_property(
1206        &self,
1207        name: impl Into<String>,
1208        json: impl Into<String>,
1209    ) -> Result<Completion<Applied>, Error> {
1210        let (name, json) = (name.into(), json.into());
1211        self.command(move |map| map.edit_loaded_style(|style| style.set_root_property_json(&name, &json)))
1212    }
1213
1214    /// A root property of the style as JSON, or `None` when neither the
1215    /// style nor the map sets it. See `Style::root_property_json`.
1216    pub fn style_root_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1217        let name = name.into();
1218        self.query(move |map| map.style().root_property_json(&name))
1219    }
1220
1221    /// Sets a property of the style's light to a JSON value.
1222    pub fn set_style_light_property(
1223        &self,
1224        name: impl Into<String>,
1225        json: impl Into<String>,
1226    ) -> Result<Completion<Applied>, Error> {
1227        let (name, json) = (name.into(), json.into());
1228        self.command(move |map| map.edit_loaded_style(|style| style.set_light_property_json(&name, &json)))
1229    }
1230
1231    /// A property of the style's light as JSON, or `None` when the light
1232    /// doesn't set it.
1233    pub fn style_light_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
1234        let name = name.into();
1235        self.query(move |map| Ok(map.style().light_property_json(&name)))
1236    }
1237
1238    // MARK: - Camera
1239
1240    /// A command that moves the camera: `apply` starts a camera command,
1241    /// whose end nobody waits for.
1242    fn camera_command(
1243        &self,
1244        apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1245    ) -> Result<Completion<Applied>, Error> {
1246        self.send_camera(apply, None)
1247    }
1248
1249    /// A command that moves the camera, whose end `on_end` receives. `on_end`
1250    /// is in place before the command is sent, so it runs on the runtime's
1251    /// thread, or on this one with
1252    /// [`ErrorKind::Cancelled`](mln_util::ErrorKind) when the send fails.
1253    fn camera_command_then(
1254        &self,
1255        apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1256        on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1257    ) -> Result<Completion<Applied>, Error> {
1258        let (ended, end) = self.shared.runtime.completion();
1259        ended.on_complete(on_end);
1260        self.send_camera(apply, Some(end))
1261    }
1262
1263    /// Sends a camera command, and `end`, if any, the command's end: a
1264    /// failure ends it as cancelled.
1265    fn send_camera(
1266        &self,
1267        apply: impl FnOnce(&mut mln_map::Map) -> Result<CameraCommandId, Error> + Send + 'static,
1268        end: Option<Resolver<TransitionEnd>>,
1269    ) -> Result<Completion<Applied>, Error> {
1270        self.send(
1271            move |entry, outbox| match (apply(&mut entry.core), end) {
1272                (Ok(command), Some(end)) => {
1273                    entry.camera_commands.insert(command, end);
1274                    Ok(())
1275                }
1276                (Ok(_), None) => Ok(()),
1277                (Err(error), end) => {
1278                    if let Some(end) = end {
1279                        let generation = entry.core.generation();
1280                        let cancelled =
1281                            TransitionEnd { outcome: TransitionOutcome::Cancelled, generation, ..Default::default() };
1282                        outbox.resolve(end, Ok(cancelled));
1283                    }
1284                    Err(error)
1285                }
1286            },
1287            |(), entry| entry.applied(),
1288        )
1289    }
1290
1291    /// Moves the camera to absolute values, by a jump, an ease or a flight.
1292    pub fn update_camera(&self, update: CameraUpdate) -> Result<Completion<Applied>, Error> {
1293        self.camera_command(move |map| Ok(map.update_camera(&update)))
1294    }
1295
1296    /// Moves the camera as [`update_camera`](Self::update_camera) does, and
1297    /// calls `on_end` with how the change ended, on the runtime's thread:
1298    /// once the map has published the snapshot that shows where the change
1299    /// left the camera, whose generation the end reports, and before the
1300    /// returned completion when the change ends within the command. A
1301    /// command that fails ends as cancelled, and one that the map's release
1302    /// ends as closed, with generation 0. `on_end` runs on this thread only
1303    /// with [`ErrorKind::Cancelled`](mln_util::ErrorKind), when the send
1304    /// fails.
1305    pub fn update_camera_then(
1306        &self,
1307        update: CameraUpdate,
1308        on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1309    ) -> Result<Completion<Applied>, Error> {
1310        self.camera_command_then(move |map| Ok(map.update_camera(&update)), on_end)
1311    }
1312
1313    /// Moves the camera relative to where it is, as a gesture does.
1314    /// Completes with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for
1315    /// a delta that the camera can't apply.
1316    pub fn apply_camera_delta(&self, delta: CameraDelta) -> Result<Completion<Applied>, Error> {
1317        self.camera_command(move |map| {
1318            map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string()))
1319        })
1320    }
1321
1322    /// Applies `delta` as [`apply_camera_delta`](Self::apply_camera_delta)
1323    /// does, and calls `on_end` with how the change ended, as
1324    /// [`update_camera_then`](Self::update_camera_then) does.
1325    pub fn apply_camera_delta_then(
1326        &self,
1327        delta: CameraDelta,
1328        on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1329    ) -> Result<Completion<Applied>, Error> {
1330        self.camera_command_then(
1331            move |map| map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string())),
1332            on_end,
1333        )
1334    }
1335
1336    /// The camera that fits `area` in the map's view, after the commands
1337    /// sent before. It keeps the map's bearing and pitch unless `options`
1338    /// sets them, and its zoom stays within the map's zoom limits.
1339    ///
1340    /// Completes with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for
1341    /// an empty area, and for padding that leaves no room for it.
1342    pub fn camera_for(
1343        &self,
1344        area: CameraFitArea,
1345        options: CameraFitOptions,
1346    ) -> Result<Completion<CameraOptions>, Error> {
1347        self.query(move |map| camera::camera_for(map, &area, &options))
1348    }
1349
1350    /// Moves the camera to the one that [`camera_for`](Self::camera_for)
1351    /// finds once the commands sent before have run, as
1352    /// [`update_camera`](Self::update_camera) moves it.
1353    ///
1354    /// Completes as `camera_for` fails, and then leaves the camera where it
1355    /// is and ends the animation as cancelled.
1356    pub fn fit_camera(&self, area: CameraFitArea, update: CameraFitUpdate) -> Result<Completion<Applied>, Error> {
1357        self.camera_command(move |map| fit(map, &area, update))
1358    }
1359
1360    /// Fits the camera as [`fit_camera`](Self::fit_camera) does, and calls
1361    /// `on_end` with how the change ended, as
1362    /// [`update_camera_then`](Self::update_camera_then) does.
1363    pub fn fit_camera_then(
1364        &self,
1365        area: CameraFitArea,
1366        update: CameraFitUpdate,
1367        on_end: impl FnOnce(Result<TransitionEnd, Error>) + Send + 'static,
1368    ) -> Result<Completion<Applied>, Error> {
1369        self.camera_command_then(move |map| fit(map, &area, update), on_end)
1370    }
1371
1372    /// Stops every camera animation.
1373    pub fn cancel_camera_transitions(&self) -> Result<Completion<Applied>, Error> {
1374        self.command(|map| {
1375            map.cancel_transitions();
1376            Ok(())
1377        })
1378    }
1379
1380    /// Stops the camera animations whose transition ID is `transition_id`.
1381    pub fn cancel_camera_transitions_with_id(&self, transition_id: u64) -> Result<Completion<Applied>, Error> {
1382        self.command(move |map| {
1383            map.cancel_transitions_with_id(transition_id);
1384            Ok(())
1385        })
1386    }
1387
1388    /// The camera after the commands sent before.
1389    pub fn camera(&self) -> Result<Completion<CameraQuery>, Error> {
1390        self.send(
1391            |_, _| Ok(()),
1392            |(), entry| CameraQuery { generation: entry.core.generation(), camera: entry.core.snapshot().view.camera },
1393        )
1394    }
1395
1396    /// The area that `camera` would show, with the fields that `camera`
1397    /// leaves out from the map's camera. It holds every corner of a rotated
1398    /// view, and its longitudes can pass ±180, so a view across the
1399    /// antimeridian gives one continuous range.
1400    pub fn lat_lng_bounds_for_camera(&self, camera: CameraOptions) -> Result<Completion<LatLngBounds>, Error> {
1401        self.query(move |map| map.lat_lng_bounds_for_camera_unwrapped(&camera))
1402    }
1403
1404    /// Sets the limits on the camera.
1405    pub fn set_bounds(&self, bounds: BoundOptions) -> Result<Completion<Applied>, Error> {
1406        self.command(move |map| map.set_bounds(&bounds))
1407    }
1408
1409    /// Sets the camera's position and orientation in three dimensions.
1410    pub fn set_free_camera_options(&self, camera: FreeCameraOptions) -> Result<Completion<Applied>, Error> {
1411        self.command(move |map| {
1412            map.set_free_camera_options(&camera);
1413            Ok(())
1414        })
1415    }
1416
1417    /// Sets how the map orients and constrains its view.
1418    pub fn set_viewport_options(&self, options: ViewportOptions) -> Result<Completion<Applied>, Error> {
1419        self.command(move |map| {
1420            camera::set_viewport(map, &options);
1421            Ok(())
1422        })
1423    }
1424
1425    /// Sets how the map picks the tiles to load.
1426    pub fn set_tile_options(&self, options: TileOptions) -> Result<Completion<Applied>, Error> {
1427        self.command(move |map| {
1428            camera::set_tile_options(map, &options);
1429            Ok(())
1430        })
1431    }
1432
1433    pub fn set_projection_mode(&self, mode: ProjectionMode) -> Result<Completion<Applied>, Error> {
1434        self.command(move |map| {
1435            map.set_projection_mode(&mode);
1436            Ok(())
1437        })
1438    }
1439
1440    /// Selects the debug overlays that the map draws.
1441    pub fn set_debug_flags(&self, flags: MapDebugOptions) -> Result<Completion<Applied>, Error> {
1442        self.command(move |map| {
1443            map.set_debug(flags);
1444            Ok(())
1445        })
1446    }
1447
1448    /// Shows or hides the rendering statistics over the map.
1449    pub fn set_rendering_stats_view_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1450        self.command(move |map| {
1451            map.enable_rendering_stats_view(enabled);
1452            Ok(())
1453        })
1454    }
1455
1456    /// Sets whether drags and zooms on a globe turn the bearing, as
1457    /// `mln_map::Map::set_globe_free_bearing` describes.
1458    pub fn set_globe_free_bearing_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1459        self.command(move |map| {
1460            map.set_globe_free_bearing(enabled);
1461            Ok(())
1462        })
1463    }
1464
1465    /// Logs the style's sources and their state.
1466    pub fn dump_debug_logs(&self) -> Result<Completion<Applied>, Error> {
1467        self.command(|map| {
1468            map.dump_debug_logs();
1469            Ok(())
1470        })
1471    }
1472}
1473
1474/// A command group of a map that ends when it drops.
1475#[must_use = "the group ends when it drops"]
1476pub struct CommandGroup {
1477    map: Option<Map>,
1478}
1479
1480impl CommandGroup {
1481    /// Ends the group, as [`Map::end_command_group`] does.
1482    pub fn end(mut self) -> Result<Completion<Applied>, Error> {
1483        match self.map.take() {
1484            Some(map) => map.end_command_group(),
1485            None => Err(Error::invalid_state("the group ended already")),
1486        }
1487    }
1488}
1489
1490impl Drop for CommandGroup {
1491    fn drop(&mut self) {
1492        if let Some(map) = self.map.take() {
1493            let _ = map.end_command_group();
1494        }
1495    }
1496}
1497
1498enum StyleLoad {
1499    Url(String),
1500    Json(String),
1501}
1502
1503/// A style load that hasn't completed.
1504struct PendingStyle {
1505    resolver: Resolver<Applied>,
1506    /// Whether the caller passed the style document, which then is the
1507    /// argument that fails to parse.
1508    from_json: bool,
1509}
1510
1511/// The render session that a map is reserved for.
1512struct SessionClaim {
1513    id: SessionId,
1514    session: Weak<SessionShared>,
1515    /// The completion of a dispose that waits for the session to end.
1516    removal: Option<Resolver<()>>,
1517}
1518
1519/// Forgets the session `id` on the runtime's thread, unless the map has
1520/// bound another since.
1521fn unbind(core: &mut RuntimeCore, map_id: MapId, id: SessionId) {
1522    if let Some(entry) = core.maps.get_mut(&map_id)
1523        && entry.session.as_ref().is_some_and(|link| link.id == id)
1524    {
1525        entry.session = None;
1526    }
1527}
1528
1529/// The render session bound to a map, as the runtime's thread knows it.
1530pub(crate) struct SessionLink {
1531    id: SessionId,
1532    queue: SessionQueue,
1533    /// The session's `awaited_command`.
1534    awaited: Arc<AtomicU64>,
1535}
1536
1537/// A still image on its way, whose outcome the next flush that finds it
1538/// reports.
1539struct PendingStill {
1540    resolver: Resolver<()>,
1541    /// Why the map refused the image, which the flush after the command
1542    /// reports.
1543    refused: Option<Result<(), Error>>,
1544}
1545
1546/// A still image's error as the handle reports it: a load failure is the
1547/// library's, whatever the core called it.
1548fn still_image_error(error: Error) -> Error {
1549    match error.kind {
1550        ErrorKind::InvalidState => error,
1551        _ => Error::native(error.message),
1552    }
1553}
1554
1555/// A map on the runtime's thread.
1556pub(crate) struct MapEntry {
1557    pub(crate) core: mln_map::Map,
1558    published: Arc<Published>,
1559    mask: EventMask,
1560    /// The sequence number of the last command that ran.
1561    applied: u64,
1562    /// The last command and frame sample that ran while a burst held the
1563    /// map's updates back, which the session learns of once they show.
1564    held_applied: Option<u64>,
1565    held_sampled: Option<u64>,
1566    /// The style load in progress.
1567    pending_style: Option<PendingStyle>,
1568    pending_still: Option<PendingStill>,
1569    /// The render session that draws the map.
1570    session: Option<SessionLink>,
1571    /// Set while the map has reported something that no flush has taken.
1572    flush_pending: FlushFlag,
1573    /// The camera commands whose change hasn't ended.
1574    camera_commands: HashMap<CameraCommandId, Resolver<TransitionEnd>>,
1575    /// The callbacks of the custom sources that commands added.
1576    pub(crate) callback_sources: CallbackSources,
1577    /// The GeoJSON data that commands set and that is still being built.
1578    pub(crate) geojson_updates: GeoJsonUpdates,
1579    /// The repaint posted for when the map changes next on its own
1580    /// ([`mln_map::Map::repaint_at`]).
1581    repaint: Option<(Instant, TimedTask)>,
1582}
1583
1584impl MapEntry {
1585    pub(crate) fn applied(&self) -> Applied {
1586        Applied {
1587            sequence: self.applied,
1588            generation: self.core.generation(),
1589            render_update_generation: self.core.pending_update_generation(),
1590        }
1591    }
1592}
1593
1594/// Whether a map reported something that no flush has taken: what its
1595/// reports waker sets. Reports that come before the flush they posted runs
1596/// share it.
1597#[derive(Clone, Default)]
1598struct FlushFlag(Arc<AtomicBool>);
1599
1600impl FlushFlag {
1601    /// The map `id`'s reports waker: it sets the flag, and posts a flush to
1602    /// `queue` when the flag was clear. The posted flush does nothing once
1603    /// another flush took the reports.
1604    fn waker(&self, queue: &CoreQueue, id: MapId) -> Waker {
1605        let (flag, queue) = (self.clone(), queue.downgrade());
1606        Arc::new(move || {
1607            if !flag.0.swap(true, Ordering::SeqCst)
1608                && let Some(queue) = queue.upgrade()
1609            {
1610                let flag = flag.clone();
1611                post(&queue, move |core, outbox| {
1612                    if flag.is_set() {
1613                        flush(core, id, outbox);
1614                    }
1615                });
1616            }
1617        })
1618    }
1619
1620    fn is_set(&self) -> bool {
1621        self.0.load(Ordering::SeqCst)
1622    }
1623
1624    fn clear(&self) {
1625        self.0.store(false, Ordering::SeqCst);
1626    }
1627}
1628
1629/// Builds the map `id` on the runtime's thread.
1630pub(crate) fn create(
1631    core: &mut RuntimeCore,
1632    id: MapId,
1633    options: &MapOptions,
1634    published: Arc<Published>,
1635    resolver: Resolver<Applied>,
1636    outbox: &mut Outbox,
1637) {
1638    let registry = Arc::clone(core.registry.style());
1639    let mut map = match mln_map::Map::with_registry(Arc::clone(core.loader()), options.map, registry, &core.pool) {
1640        Ok(map) => map,
1641        Err(error) => return outbox.resolve(resolver, Err(error)),
1642    };
1643    if let Some(json) = &options.fallback_font_faces {
1644        if let Err(error) = map.set_fallback_font_faces(json) {
1645            return outbox.resolve(resolver, Err(error));
1646        }
1647    } else if options.system_fonts {
1648        map.set_fallback_font_face_list(mln_system_fonts::font_face().into_iter().collect());
1649    }
1650    let _ = published.updates.set(map.update_reader());
1651    let _ = published.frame_clock.set(map.frame_clock());
1652    let flush_pending = FlushFlag::default();
1653    map.set_reports_waker(Some(flush_pending.waker(&core.queue, id)));
1654    published.applied.store(1, Ordering::SeqCst);
1655    core.maps.insert(
1656        id,
1657        MapEntry {
1658            core: map,
1659            published,
1660            mask: options.event_mask,
1661            applied: 1,
1662            held_applied: None,
1663            held_sampled: None,
1664            pending_style: None,
1665            pending_still: None,
1666            session: None,
1667            flush_pending,
1668            camera_commands: HashMap::default(),
1669            callback_sources: CallbackSources::default(),
1670            geojson_updates: GeoJsonUpdates::default(),
1671            repaint: None,
1672        },
1673    );
1674    flush(core, id, outbox);
1675    if let Some(entry) = core.maps.get(&id) {
1676        outbox.resolve(resolver, Ok(entry.applied()));
1677    }
1678}
1679
1680/// Runs a command on the map `id`, which must be there: handles what came
1681/// before it, applies it, publishes the map's state, sends its events, and
1682/// runs `after` with what `apply` returned. Then it tells the map's render
1683/// session that the command ran, so `after` can send the session what the
1684/// session must see first. While a burst holds the map's updates back, it
1685/// tells the session once they show, so that no frame that waits for the
1686/// command draws the update before it.
1687pub(crate) fn apply_command<T>(
1688    core: &mut RuntimeCore,
1689    id: MapId,
1690    sequence: u64,
1691    outbox: &mut Outbox,
1692    apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> T,
1693    after: impl FnOnce(&MapEntry, T, Applied, &mut Outbox),
1694) {
1695    // What the runtime's calls change, a flush in the same task takes. What
1696    // came since then, the map reported: the report posted a flush, or is
1697    // queued with its waker still on its way.
1698    if core.maps.get(&id).is_some_and(|entry| entry.flush_pending.is_set() || entry.core.has_reports()) {
1699        flush(core, id, outbox);
1700    }
1701    let Some(entry) = core.maps.get_mut(&id) else { return };
1702    let value = apply(entry, outbox);
1703    entry.applied = sequence;
1704    flush(core, id, outbox);
1705    let holding = core.holding_updates();
1706    let Some(entry) = core.maps.get_mut(&id) else { return };
1707    after(entry, value, entry.applied(), outbox);
1708    if holding {
1709        entry.held_applied = Some(sequence);
1710    } else {
1711        report_applied(entry, sequence);
1712    }
1713}
1714
1715/// Tells the map's session that the command `sequence` ran, once a frame can
1716/// show it.
1717fn report_applied(entry: &MapEntry, sequence: u64) {
1718    entry.published.applied.store(sequence, Ordering::SeqCst);
1719    if let Some(link) = &entry.session
1720        && sequence >= link.awaited.load(Ordering::SeqCst)
1721    {
1722        worker_post(&link.queue, move |worker, outbox| worker.map_applied(sequence, outbox));
1723    }
1724}
1725
1726/// Tells the map's session that the map took the frame sample `sample`, once
1727/// a frame can show it.
1728fn report_sampled(entry: &MapEntry, sample: u64) {
1729    entry.published.sampled.fetch_max(sample, Ordering::SeqCst);
1730    if let Some(link) = &entry.session {
1731        worker_post(&link.queue, move |worker, outbox| worker.map_sampled(sample, outbox));
1732    }
1733}
1734
1735/// Tells the map's session what ran while a burst held the map's updates
1736/// back, now that they show.
1737pub(crate) fn report_held(entry: &mut MapEntry) {
1738    if let Some(sequence) = entry.held_applied.take() {
1739        report_applied(entry, sequence);
1740    }
1741    if let Some(sample) = entry.held_sampled.take() {
1742        report_sampled(entry, sample);
1743    }
1744}
1745
1746/// Has the map `id` sample its animations at its frame clock's time for the
1747/// frame samples that demands asked for.
1748fn sample_frame(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1749    let Some(entry) = core.maps.get(&id) else { return };
1750    // A demand from now on asks for another sample.
1751    entry.published.sample_queued.store(false, Ordering::SeqCst);
1752    let sample = entry.published.samples_requested.load(Ordering::SeqCst);
1753    if entry.flush_pending.is_set() || entry.core.has_reports() {
1754        flush(core, id, outbox);
1755    }
1756    let Some(entry) = core.maps.get_mut(&id) else { return };
1757    entry.core.sample_frame();
1758    flush(core, id, outbox);
1759    let holding = core.holding_updates();
1760    let Some(entry) = core.maps.get_mut(&id) else { return };
1761    if holding {
1762        entry.held_sampled = Some(sample);
1763    } else {
1764        report_sampled(entry, sample);
1765    }
1766}
1767
1768/// Runs a command on the map `id` and completes with what `finish` makes of
1769/// its result and the map after it.
1770pub(crate) fn run_command<T, R: 'static>(
1771    core: &mut RuntimeCore,
1772    id: MapId,
1773    sequence: u64,
1774    apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error>,
1775    finish: impl FnOnce(T, &MapEntry) -> R,
1776    resolver: Resolver<R>,
1777    outbox: &mut Outbox,
1778) {
1779    if !core.maps.contains_key(&id) {
1780        return outbox.resolve(resolver, Err(missing_map()));
1781    }
1782    apply_command(core, id, sequence, outbox, apply, move |entry, result, _, outbox| {
1783        outbox.resolve(resolver, result.map(|value| finish(value, entry)));
1784    });
1785}
1786
1787/// Starts a style load on the map `id`. Its completion waits for the load's
1788/// outcome, which a flush finds among the map's events.
1789fn load_style(
1790    core: &mut RuntimeCore,
1791    id: MapId,
1792    sequence: u64,
1793    load: StyleLoad,
1794    resolver: Resolver<Applied>,
1795    outbox: &mut Outbox,
1796) {
1797    if !core.maps.contains_key(&id) {
1798        return outbox.resolve(resolver, Err(missing_map()));
1799    }
1800    // The flush before the load sends the outcomes of earlier loads to their
1801    // own completions.
1802    apply_command(
1803        core,
1804        id,
1805        sequence,
1806        outbox,
1807        move |entry, outbox| {
1808            let from_json = matches!(load, StyleLoad::Json(_));
1809            if let Some(previous) = entry.pending_style.replace(PendingStyle { resolver, from_json }) {
1810                outbox.resolve(previous.resolver, Err(Error::cancelled("another style load started")));
1811            }
1812            match load {
1813                StyleLoad::Url(url) => entry.core.load_style_url(&url),
1814                StyleLoad::Json(json) => entry.core.load_style_json(&json),
1815            }
1816        },
1817        |_, (), _, _| {},
1818    );
1819}
1820
1821/// Handles what the map's style and renderer reported, publishes its state
1822/// if it changed, and sends its events. A flush with nothing to handle and no
1823/// change to publish costs little, so callers flush whenever they may need
1824/// to.
1825pub(crate) fn flush(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1826    let Some(entry) = core.maps.get_mut(&id) else { return };
1827    // The flush takes what the map reported so far, and what it reports from
1828    // now on posts another.
1829    entry.flush_pending.clear();
1830    let events = entry.core.drain_events();
1831    let repaint_at = entry.core.repaint_at();
1832    if entry.repaint.as_ref().map(|(at, _)| *at) != repaint_at {
1833        if let Some((_, task)) = entry.repaint.take() {
1834            core.queue.cancel(task);
1835        }
1836        entry.repaint =
1837            repaint_at.map(|at| (at, post_at(&core.queue, at, move |core, outbox| repaint(core, id, outbox))));
1838    }
1839    // The sources that left the style, by a command or a style load, let go
1840    // of what they held before anything reports the change.
1841    crate::style::reconcile(entry, outbox);
1842    let generation = entry.core.generation();
1843    // The camera commands that ended report the snapshot that shows them.
1844    let ends: Vec<_> = entry
1845        .core
1846        .drain_command_ends()
1847        .filter_map(|end| Some((entry.camera_commands.remove(&end.command)?, TransitionEnd { generation, ..end.end })))
1848        .collect();
1849    // Each change to the state grows the generation, so a snapshot of the
1850    // same generation shows the state as it is.
1851    let mut published = entry.published.snapshot.lock();
1852    if published.is_none_or(|snapshot| snapshot.generation != generation) {
1853        *published = Some(entry.core.snapshot());
1854    }
1855    drop(published);
1856
1857    let mut style_outcome = None;
1858    let from_json = entry.pending_style.as_ref().is_some_and(|pending| pending.from_json);
1859    for event in &events {
1860        match event {
1861            MapEvent::StyleLoaded => style_outcome = Some(Ok(())),
1862            MapEvent::LoadingFailed(StyleLoadError::Parse(message)) if from_json => {
1863                style_outcome = Some(Err(Error::invalid_argument(message)));
1864            }
1865            MapEvent::LoadingFailed(error) => style_outcome = Some(Err(Error::native(error.message()))),
1866            _ => {}
1867        }
1868    }
1869    let style_outcome = style_outcome.map(|outcome| (outcome, entry.pending_style.take(), entry.applied()));
1870    let still_outcome = match &mut entry.pending_still {
1871        Some(pending) => pending
1872            .refused
1873            .take()
1874            .or_else(|| entry.core.take_still_image().map(|result| result.map_err(still_image_error))),
1875        None => None,
1876    };
1877    let still = still_outcome.and_then(|outcome| Some((outcome, entry.pending_still.take()?.resolver)));
1878    // The session demands a frame for the image while it waits, and lets
1879    // the demand go once it doesn't.
1880    let still_image = entry.pending_still.as_ref().and(entry.core.pending_still_image()).unwrap_or(0);
1881    if entry.published.still_image.swap(still_image, Ordering::SeqCst) != still_image
1882        && let Some(link) = &entry.session
1883    {
1884        worker_post(&link.queue, Worker::still_image_changed);
1885    }
1886
1887    let mask = entry.mask;
1888    let events: Vec<RuntimeEvent> = events
1889        .into_iter()
1890        .map(RuntimeEventKind::Map)
1891        .filter(|kind| mask.contains(kind.event_type()))
1892        .map(|kind| RuntimeEvent { source: EventSource::Map { id, generation }, kind })
1893        .collect();
1894    core.send_events(events, outbox);
1895    for (resolver, end) in ends {
1896        outbox.resolve(resolver, Ok(end));
1897    }
1898
1899    if let Some((outcome, Some(pending), applied)) = style_outcome {
1900        outbox.resolve(pending.resolver, outcome.map(|()| applied));
1901    }
1902    if let Some((outcome, resolver)) = still {
1903        outbox.resolve(resolver, outcome);
1904    }
1905}
1906
1907/// Draws the map `id` once its last frame's time to change came.
1908fn repaint(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1909    let Some(entry) = core.maps.get_mut(&id) else { return };
1910    entry.repaint = None;
1911    if entry.core.repaint_at().is_some() {
1912        entry.core.trigger_repaint();
1913    }
1914    flush(core, id, outbox);
1915}
1916
1917/// Lets go of the map `id`, after sending the events it still had.
1918fn remove(core: &mut RuntimeCore, id: MapId, done: Option<Resolver<()>>, outbox: &mut Outbox) {
1919    flush(core, id, outbox);
1920    if let Some(mut entry) = core.maps.remove(&id) {
1921        if let Some((_, task)) = entry.repaint.take() {
1922            core.queue.cancel(task);
1923        }
1924        entry.core.set_waker(None);
1925        if let Some(pending) = entry.pending_style.take() {
1926            outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1927        }
1928        if let Some(pending) = entry.pending_still.take() {
1929            outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1930        }
1931        crate::style::release(&mut entry, outbox);
1932        // The map's camera changes end as closed as it drops, with no
1933        // snapshot to show them.
1934        entry.core.close_camera();
1935        for end in entry.core.drain_command_ends() {
1936            if let Some(resolver) = entry.camera_commands.remove(&end.command) {
1937                outbox.resolve(resolver, Ok(end.end));
1938            }
1939        }
1940    }
1941    if let Some(done) = done {
1942        outbox.resolve(done, Ok(()));
1943    }
1944}