Skip to main content

mln_runtime/
map.rs

1//! A handle to a map that lives on its runtime's thread.
2
3use std::cell::RefCell;
4use std::rc::Rc;
5use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
6use std::sync::{Arc, Mutex, Weak};
7
8use mln_actor::RunLoopHandle;
9use mln_map::{
10    AnimationOptions, BoundOptions, Camera, CameraDelta, CameraOptions, CameraUpdate, FreeCameraOptions, LogicalExtent,
11    MapDebugOptions, MapEvent, MapMode, MapSnapshot, ProjectionMode, StyleLoadError, TransitionEnd, TransitionOutcome,
12};
13use mln_text::GlyphCache;
14use mln_util::error::{Error, ErrorKind};
15use mln_util::geo::LatLngBounds;
16use mln_util::size::Size;
17use mln_util::sync::MutexExt;
18
19use crate::camera::{self, CameraFitArea, CameraFitOptions, CameraFitUpdate, TileOptions, ViewportOptions};
20use crate::completion::{Completion, Resolver};
21use crate::event::{EventMask, EventSource, RuntimeEvent, RuntimeEventKind};
22use crate::feature_state::{FeatureState, FeatureStateSelector, FeatureStateStore};
23use crate::render::{
24    Abandoner, AttachOptions, RenderSession, RenderTarget, SessionId, SessionShared, Worker, worker_post,
25};
26use crate::runtime::{Outbox, Runtime, RuntimeCore, RuntimeShared, post};
27use crate::style::{CallbackSources, GeoJsonUpdates};
28
29/// The ID of a map, unique within its runtime.
30#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct MapId(pub u64);
32
33/// How to create a map.
34#[derive(Clone, Debug)]
35pub struct MapOptions {
36    pub map: mln_map::MapOptions,
37    /// The events that the map reports.
38    pub event_mask: EventMask,
39    /// JSON text of the font faces that the map falls back to for glyphs
40    /// that the style's fonts lack, as `Style::set_fallback_font_faces`
41    /// takes it.
42    pub fallback_font_faces: Option<String>,
43    /// Whether the map's render sessions keep tiles in memory after they
44    /// leave the view, so they show again without loading. On by default.
45    pub tile_cache_enabled: bool,
46}
47
48impl Default for MapOptions {
49    fn default() -> Self {
50        MapOptions {
51            map: mln_map::MapOptions::default(),
52            event_mask: EventMask::default(),
53            fallback_font_faces: None,
54            tile_cache_enabled: true,
55        }
56    }
57}
58
59impl MapOptions {
60    #[must_use]
61    pub fn new(map: mln_map::MapOptions) -> Self {
62        MapOptions { map, ..Self::default() }
63    }
64
65    #[must_use]
66    pub fn with_event_mask(mut self, event_mask: EventMask) -> Self {
67        self.event_mask = event_mask;
68        self
69    }
70
71    #[must_use]
72    pub fn with_fallback_font_faces(mut self, json: impl Into<String>) -> Self {
73        self.fallback_font_faces = Some(json.into());
74        self
75    }
76
77    #[must_use]
78    pub fn with_tile_cache_enabled(mut self, enabled: bool) -> Self {
79        self.tile_cache_enabled = enabled;
80        self
81    }
82}
83
84/// What a map command left behind once it ran.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub struct Applied {
87    /// The command's place among the map's commands: the map's creation is
88    /// 1, and each command takes the next number when it is sent.
89    pub sequence: u64,
90    /// The map's generation after the command: a snapshot with this
91    /// generation or a later one includes the command.
92    pub generation: u64,
93    /// The map's update generation after the command: a frame that renders
94    /// this update or a later one shows the command.
95    pub render_update_generation: u64,
96}
97
98/// The camera, and the generation of the map that it belongs to.
99#[derive(Clone, Copy, Debug, PartialEq)]
100pub struct CameraQuery {
101    pub generation: u64,
102    pub camera: Camera,
103}
104
105/// What the runtime's thread publishes for a map's handles.
106pub(crate) struct Published {
107    snapshot: Mutex<Option<MapSnapshot>>,
108    /// The sequence number of the last command that ran.
109    applied: AtomicU64,
110    event_mask: AtomicU64,
111}
112
113impl Published {
114    pub(crate) fn new(event_mask: EventMask) -> Self {
115        Published {
116            snapshot: Mutex::new(None),
117            applied: AtomicU64::new(0),
118            event_mask: AtomicU64::new(event_mask.bits()),
119        }
120    }
121}
122
123pub(crate) struct MapShared {
124    id: MapId,
125    runtime: Arc<RuntimeShared>,
126    mode: MapMode,
127    /// The map's scale factor, an `f64`'s bits: the options' pixel ratio,
128    /// until a session's resize sends another.
129    scale_factor: AtomicU64,
130    tile_cache_enabled: bool,
131    /// The render session attached to the map, from its attach until its
132    /// detach completes.
133    session: Mutex<Option<SessionClaim>>,
134    /// The sequence number of the last command sent. It stays locked while
135    /// a command is numbered and posted, so the runtime's thread runs the
136    /// map's commands in the order of their numbers.
137    sent: Mutex<u64>,
138    /// Whether the handles refuse commands.
139    released: AtomicBool,
140    /// Whether the map's removal was posted to the runtime's thread.
141    removed: AtomicBool,
142    published: Arc<Published>,
143}
144
145impl MapShared {
146    pub(crate) fn new(id: MapId, runtime: Arc<RuntimeShared>, options: &MapOptions, published: Arc<Published>) -> Self {
147        MapShared {
148            id,
149            runtime,
150            mode: options.map.map_mode(),
151            scale_factor: AtomicU64::new(f64::from(options.map.pixel_ratio()).to_bits()),
152            tile_cache_enabled: options.tile_cache_enabled,
153            session: Mutex::new(None),
154            sent: Mutex::new(1),
155            released: AtomicBool::new(false),
156            removed: AtomicBool::new(false),
157            published,
158        }
159    }
160
161    /// Numbers a command and posts it to the runtime's thread.
162    pub(crate) fn send<R: Send + 'static>(
163        &self,
164        command: impl FnOnce(&mut RuntimeCore, &mut Outbox, MapId, u64, Resolver<R>) + Send + 'static,
165    ) -> Result<Completion<R>, Error> {
166        let mut sent = self.sent.lock_unpoisoned();
167        if self.released.load(Ordering::SeqCst) {
168            return Err(released());
169        }
170        let (completion, resolver) = self.runtime.completion();
171        let id = self.id;
172        *sent += 1;
173        let sequence = *sent;
174        self.runtime.post(move |core, outbox| command(core, outbox, id, sequence, resolver));
175        Ok(completion)
176    }
177
178    /// Releases the map: no command is sent after its removal. Fails when
179    /// the map was released already.
180    fn release(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
181        self.close()?;
182        self.remove(done);
183        Ok(())
184    }
185
186    /// Refuses the commands sent from now on. Fails when the map was
187    /// released already.
188    fn close(&self) -> Result<(), Error> {
189        let _sent = self.sent.lock_unpoisoned();
190        if self.released.swap(true, Ordering::SeqCst) {
191            return Err(released());
192        }
193        Ok(())
194    }
195
196    /// Removes the closed map from its runtime's thread, after the commands
197    /// sent before, once.
198    fn remove(&self, done: Option<Resolver<()>>) {
199        if self.removed.swap(true, Ordering::SeqCst) {
200            return;
201        }
202        let id = self.id;
203        self.runtime.post(move |core, outbox| remove(core, id, done, outbox));
204        self.runtime.map_released();
205    }
206}
207
208impl Drop for MapShared {
209    fn drop(&mut self) {
210        let _ = self.close();
211        let deferred = self.session.get_mut_unpoisoned().take().and_then(|claim| claim.removal);
212        self.remove(deferred);
213    }
214}
215
216/// A handle to a map, which lives on its runtime's thread.
217///
218/// Each command takes the next sequence number when it is sent and runs on
219/// the runtime's thread after every command sent before it, to this map,
220/// another map or the runtime. It returns a [`Completion`] of its result, or
221/// an error when it can't be sent, and then never completes. A command sent
222/// before the map is built waits for it. `Clone` is another handle to the
223/// same map, and any thread may use one.
224///
225/// The map lives until [`release`](Self::release) or until its last handle
226/// drops. A command on a released map fails with
227/// [`ErrorKind::InvalidState`](mln_util::ErrorKind).
228#[derive(Clone)]
229pub struct Map {
230    pub(crate) shared: Arc<MapShared>,
231}
232
233impl std::fmt::Debug for Map {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        f.debug_struct("Map").field("id", &self.shared.id).finish()
236    }
237}
238
239impl PartialEq for Map {
240    fn eq(&self, other: &Map) -> bool {
241        Arc::ptr_eq(&self.shared, &other.shared)
242    }
243}
244
245impl Eq for Map {}
246
247fn released() -> Error {
248    Error::invalid_state("the map was released")
249}
250
251pub(crate) fn style_not_loaded() -> Error {
252    Error::invalid_state("style is not loaded")
253}
254
255/// The error of a command whose map failed to be built, or was released
256/// while the command was on its way.
257pub(crate) fn missing_map() -> Error {
258    Error::invalid_state("the map failed to be built or was released")
259}
260
261impl Map {
262    pub(crate) fn new(shared: MapShared) -> Self {
263        Map { shared: Arc::new(shared) }
264    }
265
266    #[must_use]
267    pub fn id(&self) -> MapId {
268        self.shared.id
269    }
270
271    /// When the map renders, as its options set it.
272    #[must_use]
273    pub fn mode(&self) -> MapMode {
274        self.shared.mode
275    }
276
277    /// The runtime that the map lives on.
278    #[must_use]
279    pub fn runtime(&self) -> Runtime {
280        Runtime { shared: self.shared.runtime.clone() }
281    }
282
283    /// The sequence number of the last command sent to the map.
284    #[must_use]
285    pub fn sent_sequence(&self) -> u64 {
286        *self.shared.sent.lock_unpoisoned()
287    }
288
289    /// The sequence number of the last command that ran.
290    #[must_use]
291    pub fn applied_sequence(&self) -> u64 {
292        self.shared.published.applied.load(Ordering::SeqCst)
293    }
294
295    /// The map's state after the last command that ran, without waiting for
296    /// the commands still on their way. To read the state after them, send a
297    /// command and read the snapshot once it completes, or use a query such
298    /// as [`camera`](Self::camera).
299    ///
300    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) until the
301    /// map is built, and after it is released.
302    pub fn snapshot(&self) -> Result<MapSnapshot, Error> {
303        if self.shared.released.load(Ordering::SeqCst) {
304            return Err(released());
305        }
306        self.shared.published.snapshot.lock_unpoisoned().ok_or_else(|| Error::invalid_state("the map isn't built"))
307    }
308
309    /// The events that the map reports, as of the last command that ran.
310    #[must_use]
311    pub fn event_mask(&self) -> EventMask {
312        EventMask::from_bits(self.shared.published.event_mask.load(Ordering::SeqCst)).unwrap_or_default()
313    }
314
315    /// Sends a command that runs `apply` on the map's entry, and completes
316    /// with what `finish` makes of its result and the map after it.
317    pub(crate) fn send<T: 'static, R: Send + 'static>(
318        &self,
319        apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error> + Send + 'static,
320        finish: impl FnOnce(T, &MapEntry) -> R + Send + 'static,
321    ) -> Result<Completion<R>, Error> {
322        self.shared.send(move |core, outbox, id, sequence, resolver| {
323            run_command(core, id, sequence, apply, finish, resolver, outbox);
324        })
325    }
326
327    /// A command that changes the map.
328    pub(crate) fn command(
329        &self,
330        apply: impl FnOnce(&mut mln_map::Map) -> Result<(), Error> + Send + 'static,
331    ) -> Result<Completion<Applied>, Error> {
332        self.send(move |entry, _| apply(&mut entry.core), |(), entry| entry.applied())
333    }
334
335    /// A command that reads the map.
336    pub(crate) fn query<T: Send + 'static>(
337        &self,
338        read: impl FnOnce(&mut mln_map::Map) -> Result<T, Error> + Send + 'static,
339    ) -> Result<Completion<T>, Error> {
340        self.send(move |entry, _| read(&mut entry.core), |value, _| value)
341    }
342
343    /// Runs `f` on the map itself, on the runtime's thread, in its place
344    /// among the map's commands. It sees the effects of the commands sent
345    /// before it. The map handles what `f` changed, and reports its events,
346    /// before the completion.
347    pub fn with_core<R: Send + 'static>(
348        &self,
349        f: impl FnOnce(&mut mln_map::Map) -> R + Send + 'static,
350    ) -> Result<Completion<R>, Error> {
351        self.query(move |map| Ok(f(map)))
352    }
353
354    /// Releases the map. The completion reports when the runtime has let go
355    /// of it. A render session that was released, but hasn't let go of the
356    /// map yet, is abandoned, as
357    /// [`RenderSession::abandon`](crate::RenderSession::abandon) does: a
358    /// caller-driven one that the host stopped servicing would otherwise
359    /// hold the map for good.
360    ///
361    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) when the
362    /// map was released already, or while a render session that wasn't
363    /// released is attached to it.
364    pub fn release(&self) -> Result<Completion<()>, Error> {
365        self.release_with(false)
366    }
367
368    /// Releases the map whatever its state, as dropping its last handle
369    /// does, and lets the runtime finish in the background: the completion
370    /// reports when the runtime has let go of it, and may be dropped. Every
371    /// command fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind)
372    /// from now on. A render session that is attached and wasn't released
373    /// keeps drawing the map's last update, and the runtime lets go of the
374    /// map once the session detaches or is abandoned. A released one is
375    /// abandoned, as [`release`](Self::release) does.
376    ///
377    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) when the
378    /// map was released already.
379    pub fn dispose(&self) -> Result<Completion<()>, Error> {
380        self.release_with(true)
381    }
382
383    fn release_with(&self, in_any_state: bool) -> Result<Completion<()>, Error> {
384        let (completion, resolver) = self.shared.runtime.completion();
385        let claimed = {
386            let mut claim = self.shared.session.lock_unpoisoned();
387            match claim.as_mut() {
388                None => None,
389                Some(held) => match held.session.upgrade() {
390                    // Abandoned now, or ended already and about to let go.
391                    Some(session) if session.is_released() => Some((held.id, Some(session))),
392                    // The session lets go of the map when it ends, and the
393                    // map is removed then.
394                    Some(_) if in_any_state => {
395                        self.shared.close()?;
396                        held.removal = Some(resolver);
397                        return Ok(completion);
398                    }
399                    Some(_) => return Err(Error::invalid_state("the map still has an attached render session")),
400                    // The session is gone without letting go of the map.
401                    None => Some((held.id, None)),
402                },
403            }
404        };
405        if let Some((id, session)) = claimed {
406            if let Some(session) = session {
407                let _ = session.abandon(Abandoner::Library);
408            }
409            self.release_session_claim(id);
410        }
411        self.shared.release(Some(resolver))?;
412        Ok(completion)
413    }
414
415    // MARK: - Map
416
417    /// Sets the map's size and scale factor. The map keeps its tiles, and a
418    /// resize to the extent the map has changes nothing, so it renders
419    /// nothing. Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind)
420    /// while a render session is attached, since the session sizes the map
421    /// to its target: resize the session instead. Fails with
422    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an empty size,
423    /// or a scale factor that isn't finite and positive.
424    pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
425        let LogicalExtent { size, scale_factor } = extent;
426        if self.shared.session.lock_unpoisoned().is_some() {
427            return Err(Error::invalid_state("the map has a render session: resize the session instead"));
428        }
429        if size.is_empty() {
430            return Err(Error::invalid_argument("logical size dimensions must be positive"));
431        }
432        if !scale_factor.is_finite() || scale_factor <= 0.0 {
433            return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
434        }
435        // The scale factor that a session attached later renders at.
436        self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
437        self.command(move |map| {
438            if map.get_map_options().size() != size {
439                map.set_size(size)?;
440            }
441            map.set_pixel_ratio(scale_factor as f32)
442        })
443    }
444
445    /// Renders a new frame of a continuous map, even when nothing changed.
446    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a
447    /// static or tile map, which renders only still images.
448    pub fn request_repaint(&self) -> Result<Completion<Applied>, Error> {
449        if self.shared.mode != MapMode::Continuous {
450            return Err(Error::invalid_state("map is not in continuous mode"));
451        }
452        self.command(|map| {
453            map.trigger_repaint();
454            Ok(())
455        })
456    }
457
458    /// Holds the map's changes back from rendering until the matching
459    /// [`end_command_group`](Self::end_command_group), so that they show in
460    /// the same frame. Groups nest, and the changes show when the outermost
461    /// group ends.
462    pub fn begin_command_group(&self) -> Result<Completion<Applied>, Error> {
463        self.command(|map| {
464            map.begin_command_group();
465            Ok(())
466        })
467    }
468
469    /// Ends the group that [`begin_command_group`](Self::begin_command_group)
470    /// began. Completes with [`ErrorKind::InvalidState`](mln_util::ErrorKind)
471    /// when no group is open.
472    pub fn end_command_group(&self) -> Result<Completion<Applied>, Error> {
473        self.command(mln_map::Map::end_command_group)
474    }
475
476    /// Begins a command group that ends when the guard drops, or with
477    /// [`CommandGroup::end`].
478    pub fn command_group(&self) -> Result<CommandGroup, Error> {
479        drop(self.begin_command_group()?);
480        Ok(CommandGroup { map: Some(self.clone()) })
481    }
482
483    /// Selects the events that the map reports.
484    pub fn set_event_mask(&self, mask: EventMask) -> Result<Completion<Applied>, Error> {
485        self.send(
486            move |entry, _| {
487                if entry.mask != mask {
488                    entry.mask = mask;
489                    entry.published.event_mask.store(mask.bits(), Ordering::SeqCst);
490                    entry.core.record_change();
491                }
492                Ok(())
493            },
494            |(), entry| entry.applied(),
495        )
496    }
497
498    // MARK: - Rendering
499
500    /// Attaches a render session, which renders the map into `target`, and
501    /// sizes the map to the target. A map has one session at a time. The
502    /// session takes frame demands and other work at once, and runs them
503    /// once the completion reports it ready.
504    ///
505    /// The session renders on a thread of its own, or, with
506    /// [`Driver::CallerThread`](crate::Driver::CallerThread), on the thread
507    /// that takes its [`DriverWork`](crate::DriverWork): the attach completes
508    /// in that thread's first service.
509    ///
510    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) when the
511    /// map already has a session or was released, or a window is minimized
512    /// or has no client area, and with
513    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an empty
514    /// target, or a [`Surface::wgpu`](crate::Surface::wgpu) without the
515    /// host's device. The completion fails as
516    /// [`Device::new`](crate::Device::new) does when the
517    /// session has to create its device and can't, with
518    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) when the window or
519    /// surface had no area to present to by then, with
520    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) when no GPU can present
521    /// to a window, and with [`ErrorKind::Native`](mln_util::ErrorKind) when
522    /// the window has no surface to give.
523    pub fn attach(
524        &self,
525        target: RenderTarget,
526        options: AttachOptions,
527    ) -> Result<(RenderSession, Completion<()>), Error> {
528        crate::render::attach(self, target, options)
529    }
530
531    /// Renders a still image of a static or tile map, once every resource
532    /// that it needs has loaded. The map's render session draws it, and
533    /// [`RenderSession::read_texture`] reads its pixels once the completion
534    /// reports success. Without a session, the image waits for the next one.
535    ///
536    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a
537    /// continuous map. Completes with
538    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) while another image
539    /// is on its way or a command group is open,
540    /// [`ErrorKind::Native`](mln_util::ErrorKind) when the
541    /// style or a resource that the image needs fails to load, and
542    /// [`ErrorKind::Cancelled`](mln_util::ErrorKind) when the map is released
543    /// first.
544    pub fn request_still_image(&self) -> Result<Completion<()>, Error> {
545        if self.shared.mode == MapMode::Continuous {
546            return Err(Error::invalid_state("the map is not in static or tile mode"));
547        }
548        self.shared.send(move |core, outbox, id, sequence, resolver| {
549            if !core.maps.contains_key(&id) {
550                return outbox.resolve(resolver, Err(missing_map()));
551            }
552            apply_command(
553                core,
554                id,
555                sequence,
556                outbox,
557                move |entry, outbox| {
558                    if entry.pending_still.is_some() {
559                        let error = Error::invalid_state("the map is rendering a still image already");
560                        return outbox.resolve(resolver, Err(error));
561                    }
562                    // The group holds back the update that the image needs.
563                    if entry.core.command_group_depth() > 0 {
564                        let error = Error::invalid_state("a still image can't render while a command group is open");
565                        return outbox.resolve(resolver, Err(error));
566                    }
567                    let outcome = Rc::new(RefCell::new(None));
568                    let done = outcome.clone();
569                    entry.core.render_still(Box::new(move |result| {
570                        *done.borrow_mut() = Some(result.map_err(still_image_error));
571                    }));
572                    entry.pending_still = Some(PendingStill { resolver, outcome });
573                },
574                |_, (), _, _| {},
575            );
576        })
577    }
578
579    pub(crate) fn runtime_thread(&self) -> std::thread::ThreadId {
580        self.shared.runtime.thread()
581    }
582
583    /// The map's scale factor: device pixels per logical pixel. It is the
584    /// pixel ratio of the map's options until a render session's
585    /// [`resize`](crate::RenderSession::resize) sets another, and the map's
586    /// next session renders at it.
587    #[must_use]
588    pub fn scale_factor(&self) -> f64 {
589        f64::from_bits(self.shared.scale_factor.load(Ordering::SeqCst))
590    }
591
592    pub(crate) fn tile_cache_enabled(&self) -> bool {
593        self.shared.tile_cache_enabled
594    }
595
596    pub(crate) fn glyph_cache(&self) -> Arc<GlyphCache> {
597        self.shared.runtime.glyph_cache.clone()
598    }
599
600    /// Reserves the map for the session `id`.
601    pub(crate) fn claim_session(&self, id: SessionId, session: Weak<SessionShared>) -> Result<(), Error> {
602        let mut claim = self.shared.session.lock_unpoisoned();
603        if self.shared.released.load(Ordering::SeqCst) {
604            return Err(released());
605        }
606        if claim.is_some() {
607            return Err(Error::invalid_state("the map already has an attached render session"));
608        }
609        *claim = Some(SessionClaim { id, session, removal: None });
610        Ok(())
611    }
612
613    /// Lets another session attach once the session `id` is gone, and
614    /// removes the map when a dispose waited for the session.
615    pub(crate) fn release_session_claim(&self, id: SessionId) {
616        let claim = {
617            let mut session = self.shared.session.lock_unpoisoned();
618            if session.as_ref().is_some_and(|claim| claim.id == id) { session.take() } else { None }
619        };
620        if let Some(removal) = claim.and_then(|claim| claim.removal) {
621            self.shared.remove(Some(removal));
622        }
623    }
624
625    /// Sends the command that binds the session `id`, whose thread runs
626    /// `run_loop`, to the map: it sizes the map to `size`, and hands the
627    /// session the map's updates.
628    pub(crate) fn bind_session(&self, id: SessionId, run_loop: RunLoopHandle, size: Size) -> Result<(), Error> {
629        let sent = self.shared.send(move |core, outbox, map_id, sequence, resolver: Resolver<()>| {
630            drop(resolver);
631            if !core.maps.contains_key(&map_id) {
632                return worker_post(&run_loop, |worker, outbox| worker.bind_failed(missing_map(), outbox));
633            }
634            let link = SessionLink { id, run_loop: run_loop.clone() };
635            apply_command(
636                core,
637                map_id,
638                sequence,
639                outbox,
640                move |entry, _| {
641                    entry.session = Some(link);
642                    let resized = entry.core.set_size(size);
643                    (resized, entry.core.update_reader(), entry.core.renderer_events())
644                },
645                move |_, (resized, reader, events), _, _| match resized {
646                    Ok(()) => {
647                        worker_post(&run_loop, move |worker, outbox| worker.bound(sequence, reader, events, outbox));
648                    }
649                    Err(error) => worker_post(&run_loop, move |worker, outbox| worker.bind_failed(error, outbox)),
650                },
651            );
652        });
653        sent.map(drop)
654    }
655
656    /// Unbinds the session `id` from the map on the runtime's thread, after
657    /// the commands sent before.
658    pub(crate) fn unbind_session(&self, id: SessionId) {
659        let map_id = self.shared.id;
660        // A runtime that shut down has no map to unbind from.
661        self.shared.runtime.post_or((), move |core, _, ()| unbind(core, map_id, id), |()| {});
662    }
663
664    /// Unbinds the session `id` as [`unbind_session`](Self::unbind_session)
665    /// does, then runs `then` on the session's thread.
666    pub(crate) fn unbind_session_then(
667        &self,
668        id: SessionId,
669        run_loop: RunLoopHandle,
670        then: impl FnOnce(&mut Worker, &mut Outbox) + Send + 'static,
671    ) {
672        let map_id = self.shared.id;
673        let session_loop = run_loop.clone();
674        // A runtime that shut down has no map to unbind from.
675        self.shared.runtime.post_or(
676            then,
677            move |core, _, then| {
678                unbind(core, map_id, id);
679                worker_post(&run_loop, then);
680            },
681            |then| worker_post(&session_loop, then),
682        );
683    }
684
685    /// Sends a command that resizes the map to `size` at `scale_factor`,
686    /// then runs `resize` with its outcome on the thread of the session that
687    /// `run_loop` runs, before the session learns of any later command.
688    pub(crate) fn resize_for_session(
689        &self,
690        size: Size,
691        scale_factor: f64,
692        run_loop: RunLoopHandle,
693        resize: impl FnOnce(&mut Worker, Result<Applied, Error>, &mut Outbox) + Send + 'static,
694    ) -> Result<(), Error> {
695        // The scale factor that a session attached later renders at.
696        self.shared.scale_factor.store(scale_factor.to_bits(), Ordering::SeqCst);
697        let sent = self.shared.send(move |core, outbox, id, sequence, resolver: Resolver<()>| {
698            drop(resolver);
699            if !core.maps.contains_key(&id) {
700                return worker_post(&run_loop, move |worker, outbox| resize(worker, Err(missing_map()), outbox));
701            }
702            apply_command(
703                core,
704                id,
705                sequence,
706                outbox,
707                move |entry, _| {
708                    // A host may hand the session the target it has, such as
709                    // on every frame. That changes nothing, so it publishes
710                    // no update, which a demand sent before would draw.
711                    let pixel_ratio = scale_factor as f32;
712                    if entry.core.get_map_options().size() == size && entry.core.get_pixel_ratio() == pixel_ratio {
713                        return Ok(());
714                    }
715                    entry.core.set_size(size)?;
716                    entry.core.set_pixel_ratio(pixel_ratio)
717                },
718                move |_, resized, applied, _| {
719                    let result = resized.map(|()| applied);
720                    worker_post(&run_loop, move |worker, outbox| resize(worker, result, outbox));
721                },
722            );
723        });
724        sent.map(drop)
725    }
726
727    // MARK: - Feature state
728
729    /// Merges `state` into the state of the feature that `selector` names:
730    /// its keys replace the same keys of the feature's state, and the other
731    /// keys stay.
732    ///
733    /// The map keeps the state until it is removed, its source leaves the
734    /// style, or a style loads: [`remove_style_source`](Self::remove_style_source)
735    /// removes the state of the source's features, and a style that loads
736    /// removes the state of every source. To set state for a new style's
737    /// sources, wait until [`set_style_url`](Self::set_style_url) or
738    /// [`set_style_json`](Self::set_style_json) completes.
739    ///
740    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
741    /// selector without a feature, or an empty state.
742    pub fn set_feature_state(
743        &self,
744        selector: &FeatureStateSelector,
745        state: FeatureState,
746    ) -> Result<Completion<Applied>, Error> {
747        let key = selector.key(true)?;
748        if state.is_empty() {
749            return Err(Error::invalid_argument("feature state must not be empty"));
750        }
751        self.send(
752            move |entry, _| {
753                entry.feature_state.set(key, state);
754                Ok(())
755            },
756            |(), entry| entry.applied(),
757        )
758    }
759
760    /// The state of the feature that `selector` names, empty when it has
761    /// none. Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind)
762    /// for a selector without a feature.
763    pub fn feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<FeatureState>, Error> {
764        let key = selector.key(true)?;
765        self.send(move |entry, _| Ok(entry.feature_state.get(&key)), |state, _| state)
766    }
767
768    /// Removes the state that `selector` selects: one key of a feature, all
769    /// of a feature's state, or that of every feature in a source layer.
770    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
771    /// state key without a feature.
772    pub fn remove_feature_state(&self, selector: &FeatureStateSelector) -> Result<Completion<Applied>, Error> {
773        let key = selector.key(false)?;
774        self.send(
775            move |entry, _| {
776                entry.feature_state.remove(&key);
777                Ok(())
778            },
779            |(), entry| entry.applied(),
780        )
781    }
782
783    // MARK: - Style
784
785    /// Loads the map's style from `url`.
786    ///
787    /// Completes once the style document has loaded and parsed, with
788    /// [`ErrorKind::Native`](mln_util::ErrorKind) when it fails to, and with
789    /// [`ErrorKind::Cancelled`](mln_util::ErrorKind) when another style load
790    /// starts or the map is released first. The style's sources, sprites and
791    /// glyphs then load in the background. Commands that change the style
792    /// fail with [`ErrorKind::InvalidState`](mln_util::ErrorKind) until the
793    /// document has parsed.
794    pub fn set_style_url(&self, url: impl Into<String>) -> Result<Completion<Applied>, Error> {
795        let url = url.into();
796        if url.is_empty() {
797            return Err(Error::invalid_argument("style URL must not be empty"));
798        }
799        self.load_style(StyleLoad::Url(url))
800    }
801
802    /// Loads the map's style from JSON text. Completes as
803    /// [`set_style_url`](Self::set_style_url) does, once the style has
804    /// parsed, but with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind)
805    /// for JSON that isn't a valid style. A style that fails to parse leaves
806    /// the map's style as it was.
807    pub fn set_style_json(&self, json: impl Into<String>) -> Result<Completion<Applied>, Error> {
808        let json = json.into();
809        if json.is_empty() {
810            return Err(Error::invalid_argument("style JSON must not be empty"));
811        }
812        self.load_style(StyleLoad::Json(json))
813    }
814
815    fn load_style(&self, load: StyleLoad) -> Result<Completion<Applied>, Error> {
816        self.shared.send(move |core, outbox, id, sequence, resolver| {
817            load_style(core, id, sequence, load, resolver, outbox);
818        })
819    }
820
821    /// The JSON of the style that the map loaded, without the changes made
822    /// since.
823    pub fn loaded_style_json(&self) -> Result<Completion<String>, Error> {
824        self.query(|map| Ok(map.style().get_json()))
825    }
826
827    /// The URL of the map's style, or `None` for a style loaded from JSON.
828    pub fn style_url(&self) -> Result<Completion<Option<String>>, Error> {
829        self.query(|map| Ok(Some(map.style().get_url()).filter(|url| !url.is_empty())))
830    }
831
832    /// Adds a source to the style from its JSON. See
833    /// `Style::add_source_json` for the errors.
834    pub fn add_style_source_json(
835        &self,
836        source_id: impl Into<String>,
837        json: impl Into<String>,
838    ) -> Result<Completion<Applied>, Error> {
839        let (source_id, json) = (source_id.into(), json.into());
840        self.command(move |map| map.style_mut().add_source_json(&source_id, &json))
841    }
842
843    /// Removes a source from the style. Completes with
844    /// [`ErrorKind::NotFound`](mln_util::ErrorKind) when the style has no
845    /// such source, and [`ErrorKind::InvalidState`](mln_util::ErrorKind)
846    /// when a layer uses it or the style isn't loaded. The source's features
847    /// lose their state, and a custom source's callbacks drop before the
848    /// completion.
849    pub fn remove_style_source(&self, source_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
850        let source_id = source_id.into();
851        self.send(
852            move |entry, _| {
853                let style = entry.core.style_mut();
854                if !style.is_loaded() {
855                    return Err(style_not_loaded());
856                }
857                if style.get_source(&source_id).is_none() {
858                    return Err(Error::not_found(format!("source \"{source_id}\" does not exist")));
859                }
860                if let Some(layer) = style.get_layers().into_iter().find(|layer| layer.get_source_id() == source_id) {
861                    let message = format!("source \"{source_id}\" is used by layer \"{}\"", layer.get_id());
862                    return Err(Error::invalid_state(message));
863                }
864                style.remove_source(&source_id);
865                entry.feature_state.remove_source(&source_id);
866                Ok(())
867            },
868            |(), entry| entry.applied(),
869        )
870    }
871
872    /// Adds a layer to the style from its JSON, below `before_layer_id` or
873    /// above every layer. See `Style::add_layer_json` for the errors.
874    pub fn add_style_layer_json(
875        &self,
876        json: impl Into<String>,
877        before_layer_id: Option<String>,
878    ) -> Result<Completion<Applied>, Error> {
879        let json = json.into();
880        self.command(move |map| map.style_mut().add_layer_json(&json, before_layer_id.as_deref()))
881    }
882
883    /// Removes a layer from the style. Completes with
884    /// [`ErrorKind::NotFound`](mln_util::ErrorKind) when the style has no
885    /// such layer, and [`ErrorKind::InvalidState`](mln_util::ErrorKind)
886    /// while the style isn't loaded.
887    pub fn remove_style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
888        let layer_id = layer_id.into();
889        self.command(move |map| {
890            let style = map.style_mut();
891            if !style.is_loaded() {
892                return Err(style_not_loaded());
893            }
894            style
895                .remove_layer(&layer_id)
896                .map(drop)
897                .ok_or_else(|| Error::not_found(format!("layer \"{layer_id}\" does not exist")))
898        })
899    }
900
901    /// A layer of the style as JSON, or `None` when the style has no such
902    /// layer.
903    pub fn style_layer_json(&self, layer_id: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
904        let layer_id = layer_id.into();
905        self.query(move |map| Ok(map.style().layer_json(&layer_id)))
906    }
907
908    /// Sets a property of a layer to a JSON value. See
909    /// `Style::set_layer_property_json` for the errors.
910    pub fn set_style_layer_property(
911        &self,
912        layer_id: impl Into<String>,
913        name: impl Into<String>,
914        json: impl Into<String>,
915    ) -> Result<Completion<Applied>, Error> {
916        let (layer_id, name, json) = (layer_id.into(), name.into(), json.into());
917        self.command(move |map| map.style_mut().set_layer_property_json(&layer_id, &name, &json))
918    }
919
920    /// A property of a layer as JSON, or `None` when the layer doesn't set
921    /// it. See `Style::layer_property_json` for the errors.
922    pub fn style_layer_property(
923        &self,
924        layer_id: impl Into<String>,
925        name: impl Into<String>,
926    ) -> Result<Completion<Option<String>>, Error> {
927        let (layer_id, name) = (layer_id.into(), name.into());
928        self.query(move |map| map.style().layer_property_json(&layer_id, &name))
929    }
930
931    /// Sets a root property of the style to a JSON value, without
932    /// reloading the style. See `Style::set_root_property_json` for the
933    /// properties that change and the errors.
934    pub fn set_style_root_property(
935        &self,
936        name: impl Into<String>,
937        json: impl Into<String>,
938    ) -> Result<Completion<Applied>, Error> {
939        let (name, json) = (name.into(), json.into());
940        self.command(move |map| map.style_mut().set_root_property_json(&name, &json))
941    }
942
943    /// A root property of the style as JSON, or `None` when neither the
944    /// style nor the map sets it. See `Style::root_property_json`.
945    pub fn style_root_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
946        let name = name.into();
947        self.query(move |map| map.style().root_property_json(&name))
948    }
949
950    /// Sets a property of the style's light to a JSON value.
951    pub fn set_style_light_property(
952        &self,
953        name: impl Into<String>,
954        json: impl Into<String>,
955    ) -> Result<Completion<Applied>, Error> {
956        let (name, json) = (name.into(), json.into());
957        self.command(move |map| map.style_mut().set_light_property_json(&name, &json))
958    }
959
960    /// A property of the style's light as JSON, or `None` when the light
961    /// doesn't set it.
962    pub fn style_light_property(&self, name: impl Into<String>) -> Result<Completion<Option<String>>, Error> {
963        let name = name.into();
964        self.query(move |map| Ok(map.style().light_property_json(&name)))
965    }
966
967    // MARK: - Camera
968
969    /// A command that moves the camera: its animation's end function runs on
970    /// the runtime's thread once the map has published the snapshot that
971    /// shows where the change left the camera, whose generation the end
972    /// reports, and before the command's completion.
973    fn camera_command(
974        &self,
975        apply: impl FnOnce(&mut mln_map::Map, &Ends) -> Result<(), Error> + Send + 'static,
976    ) -> Result<Completion<Applied>, Error> {
977        self.send(move |entry, _| apply(&mut entry.core, &entry.ends), |(), entry| entry.applied())
978    }
979
980    /// Moves the camera to absolute values, by a jump, an ease or a flight.
981    pub fn update_camera(&self, mut update: CameraUpdate) -> Result<Completion<Applied>, Error> {
982        self.camera_command(move |map, ends| {
983            ends.defer(&mut update.animation);
984            map.update_camera(&update);
985            Ok(())
986        })
987    }
988
989    /// Moves the camera relative to where it is, as a gesture does.
990    /// Completes with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for
991    /// a delta that the camera can't apply.
992    pub fn apply_camera_delta(&self, mut delta: CameraDelta) -> Result<Completion<Applied>, Error> {
993        self.camera_command(move |map, ends| {
994            ends.defer(&mut delta.animation);
995            map.apply_camera_delta(&delta).map_err(|error| Error::invalid_argument(error.to_string()))
996        })
997    }
998
999    /// The camera that fits `area` in the map's view, after the commands
1000    /// sent before. It keeps the map's bearing and pitch unless `options`
1001    /// sets them, and its zoom stays within the map's zoom limits.
1002    ///
1003    /// Completes with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for
1004    /// an empty area, and for padding that leaves no room for it.
1005    pub fn camera_for(
1006        &self,
1007        area: CameraFitArea,
1008        options: CameraFitOptions,
1009    ) -> Result<Completion<CameraOptions>, Error> {
1010        self.query(move |map| camera::camera_for(map, &area, &options))
1011    }
1012
1013    /// Moves the camera to the one that [`camera_for`](Self::camera_for)
1014    /// finds once the commands sent before have run, as
1015    /// [`update_camera`](Self::update_camera) moves it.
1016    ///
1017    /// Completes as `camera_for` fails, and then leaves the camera where it
1018    /// is and ends the animation as cancelled.
1019    pub fn fit_camera(&self, area: CameraFitArea, update: CameraFitUpdate) -> Result<Completion<Applied>, Error> {
1020        self.camera_command(move |map, ends| {
1021            let CameraFitUpdate { mode, fit, mut animation } = update;
1022            ends.defer(&mut animation);
1023            match camera::camera_for(map, &area, &fit) {
1024                Ok(camera) => {
1025                    map.update_camera(&CameraUpdate { mode, camera, animation, ..CameraUpdate::default() });
1026                    Ok(())
1027                }
1028                Err(error) => {
1029                    if let Some(end_fn) = &animation.transition_end_fn {
1030                        end_fn(&TransitionEnd { outcome: TransitionOutcome::Cancelled, ..TransitionEnd::default() });
1031                    }
1032                    Err(error)
1033                }
1034            }
1035        })
1036    }
1037
1038    /// Stops every camera animation.
1039    pub fn cancel_camera_transitions(&self) -> Result<Completion<Applied>, Error> {
1040        self.command(|map| {
1041            map.cancel_transitions();
1042            Ok(())
1043        })
1044    }
1045
1046    /// Stops the camera animations whose transition ID is `transition_id`.
1047    pub fn cancel_camera_transitions_with_id(&self, transition_id: u64) -> Result<Completion<Applied>, Error> {
1048        self.command(move |map| {
1049            map.cancel_transitions_with_id(transition_id);
1050            Ok(())
1051        })
1052    }
1053
1054    /// The camera after the commands sent before.
1055    pub fn camera(&self) -> Result<Completion<CameraQuery>, Error> {
1056        self.send(
1057            |_, _| Ok(()),
1058            |(), entry| CameraQuery { generation: entry.core.generation(), camera: entry.core.snapshot().view.camera },
1059        )
1060    }
1061
1062    /// The area that `camera` would show, with the fields that `camera`
1063    /// leaves out from the map's camera. It holds every corner of a rotated
1064    /// view, and its longitudes can pass ±180, so a view across the
1065    /// antimeridian gives one continuous range.
1066    pub fn lat_lng_bounds_for_camera(&self, camera: CameraOptions) -> Result<Completion<LatLngBounds>, Error> {
1067        self.query(move |map| map.lat_lng_bounds_for_camera_unwrapped(&camera))
1068    }
1069
1070    /// Sets the limits on the camera.
1071    pub fn set_bounds(&self, bounds: BoundOptions) -> Result<Completion<Applied>, Error> {
1072        self.command(move |map| map.set_bounds(&bounds))
1073    }
1074
1075    /// Sets the camera's position and orientation in three dimensions.
1076    pub fn set_free_camera_options(&self, camera: FreeCameraOptions) -> Result<Completion<Applied>, Error> {
1077        self.command(move |map| {
1078            map.set_free_camera_options(&camera);
1079            Ok(())
1080        })
1081    }
1082
1083    /// Sets how the map orients and constrains its view.
1084    pub fn set_viewport_options(&self, options: ViewportOptions) -> Result<Completion<Applied>, Error> {
1085        self.command(move |map| {
1086            camera::set_viewport(map, &options);
1087            Ok(())
1088        })
1089    }
1090
1091    /// Sets how the map picks the tiles to load.
1092    pub fn set_tile_options(&self, options: TileOptions) -> Result<Completion<Applied>, Error> {
1093        self.command(move |map| {
1094            camera::set_tile_options(map, &options);
1095            Ok(())
1096        })
1097    }
1098
1099    pub fn set_projection_mode(&self, mode: ProjectionMode) -> Result<Completion<Applied>, Error> {
1100        self.command(move |map| {
1101            map.set_projection_mode(&mode);
1102            Ok(())
1103        })
1104    }
1105
1106    /// Selects the debug overlays that the map draws.
1107    pub fn set_debug_flags(&self, flags: MapDebugOptions) -> Result<Completion<Applied>, Error> {
1108        self.command(move |map| {
1109            map.set_debug(flags);
1110            Ok(())
1111        })
1112    }
1113
1114    /// Shows or hides the rendering statistics over the map.
1115    pub fn set_rendering_stats_view_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1116        self.command(move |map| {
1117            map.enable_rendering_stats_view(enabled);
1118            Ok(())
1119        })
1120    }
1121
1122    /// Sets whether drags and zooms on a globe turn the bearing, as
1123    /// `mln_map::Map::set_globe_free_bearing` describes.
1124    pub fn set_globe_free_bearing_enabled(&self, enabled: bool) -> Result<Completion<Applied>, Error> {
1125        self.command(move |map| {
1126            map.set_globe_free_bearing(enabled);
1127            Ok(())
1128        })
1129    }
1130
1131    /// Logs the style's sources and their state.
1132    pub fn dump_debug_logs(&self) -> Result<Completion<Applied>, Error> {
1133        self.command(|map| {
1134            map.dump_debug_logs();
1135            Ok(())
1136        })
1137    }
1138}
1139
1140/// A command group of a map that ends when it drops.
1141#[must_use = "the group ends when it drops"]
1142pub struct CommandGroup {
1143    map: Option<Map>,
1144}
1145
1146impl CommandGroup {
1147    /// Ends the group, as [`Map::end_command_group`] does.
1148    pub fn end(mut self) -> Result<Completion<Applied>, Error> {
1149        match self.map.take() {
1150            Some(map) => map.end_command_group(),
1151            None => Err(Error::invalid_state("the group ended already")),
1152        }
1153    }
1154}
1155
1156impl Drop for CommandGroup {
1157    fn drop(&mut self) {
1158        if let Some(map) = self.map.take() {
1159            let _ = map.end_command_group();
1160        }
1161    }
1162}
1163
1164enum StyleLoad {
1165    Url(String),
1166    Json(String),
1167}
1168
1169/// A style load that hasn't completed.
1170struct PendingStyle {
1171    resolver: Resolver<Applied>,
1172    /// Whether the caller passed the style document, which then is the
1173    /// argument that fails to parse.
1174    from_json: bool,
1175}
1176
1177/// The render session that a map is reserved for.
1178struct SessionClaim {
1179    id: SessionId,
1180    session: Weak<SessionShared>,
1181    /// The completion of a dispose that waits for the session to end.
1182    removal: Option<Resolver<()>>,
1183}
1184
1185/// Forgets the session `id` on the runtime's thread, unless the map has
1186/// bound another since.
1187fn unbind(core: &mut RuntimeCore, map_id: MapId, id: SessionId) {
1188    if let Some(entry) = core.maps.get_mut(&map_id)
1189        && entry.session.as_ref().is_some_and(|link| link.id == id)
1190    {
1191        entry.session = None;
1192    }
1193}
1194
1195/// The render session bound to a map, as the runtime's thread knows it.
1196pub(crate) struct SessionLink {
1197    id: SessionId,
1198    run_loop: RunLoopHandle,
1199}
1200
1201/// A still image on its way: the map's callback leaves its outcome for the
1202/// next flush.
1203struct PendingStill {
1204    resolver: Resolver<()>,
1205    outcome: Rc<RefCell<Option<Result<(), Error>>>>,
1206}
1207
1208/// A still image's error as the handle reports it: a load failure is the
1209/// library's, whatever the core called it.
1210fn still_image_error(error: Error) -> Error {
1211    match error.kind {
1212        ErrorKind::InvalidState => error,
1213        _ => Error::native(error.message),
1214    }
1215}
1216
1217/// A map on the runtime's thread.
1218pub(crate) struct MapEntry {
1219    pub(crate) core: mln_map::Map,
1220    published: Arc<Published>,
1221    mask: EventMask,
1222    /// The sequence number of the last command that ran.
1223    applied: u64,
1224    /// The style load in progress.
1225    pending_style: Option<PendingStyle>,
1226    pending_still: Option<PendingStill>,
1227    /// The render session that draws the map.
1228    session: Option<SessionLink>,
1229    /// Whether a flush of the map's events is on its way.
1230    flush_scheduled: Arc<AtomicBool>,
1231    ends: Ends,
1232    pub(crate) feature_state: FeatureStateStore,
1233    /// The callbacks of the custom sources that commands added.
1234    pub(crate) callback_sources: CallbackSources,
1235    /// The GeoJSON data that commands set and that is still being built.
1236    pub(crate) geojson_updates: GeoJsonUpdates,
1237}
1238
1239impl MapEntry {
1240    pub(crate) fn applied(&self) -> Applied {
1241        Applied {
1242            sequence: self.applied,
1243            generation: self.core.generation(),
1244            render_update_generation: self.core.pending_update_generation(),
1245        }
1246    }
1247}
1248
1249/// The camera changes of a map's commands that ended, which wait to report
1250/// their end until the map publishes the snapshot that shows it.
1251#[derive(Clone, Default)]
1252pub(crate) struct Ends(Arc<Mutex<Vec<(EndFn, TransitionEnd)>>>);
1253
1254type EndFn = Arc<dyn Fn(&TransitionEnd) + Send + Sync>;
1255
1256impl Ends {
1257    /// Makes `animation`'s end function wait for the snapshot.
1258    fn defer(&self, animation: &mut AnimationOptions) {
1259        if let Some(end_fn) = animation.transition_end_fn.take() {
1260            let ended = self.0.clone();
1261            animation.transition_end_fn = Some(Arc::new(move |end: &TransitionEnd| {
1262                ended.lock_unpoisoned().push((end_fn.clone(), *end));
1263            }));
1264        }
1265    }
1266
1267    /// Reports the changes that ended to their commands, after what `outbox`
1268    /// holds, with the generation of the snapshot that shows them.
1269    fn deliver(&self, generation: u64, outbox: &mut Outbox) {
1270        for (end_fn, end) in std::mem::take(&mut *self.0.lock_unpoisoned()) {
1271            outbox.push(move || end_fn(&TransitionEnd { generation, ..end }));
1272        }
1273    }
1274}
1275
1276/// Builds the map `id` on the runtime's thread.
1277pub(crate) fn create(
1278    core: &mut RuntimeCore,
1279    id: MapId,
1280    options: &MapOptions,
1281    published: Arc<Published>,
1282    resolver: Resolver<Applied>,
1283    outbox: &mut Outbox,
1284) {
1285    let (file_sources, resource_options) = core.file_sources();
1286    let mut map = match mln_map::Map::with_resource_options(options.map, file_sources, resource_options) {
1287        Ok(map) => map,
1288        Err(error) => return outbox.resolve(resolver, Err(error)),
1289    };
1290    if let Some(json) = &options.fallback_font_faces
1291        && let Err(error) = map.style_mut().set_fallback_font_faces(json)
1292    {
1293        return outbox.resolve(resolver, Err(error));
1294    }
1295    let flush_scheduled = Arc::new(AtomicBool::new(false));
1296    let scheduled = flush_scheduled.clone();
1297    let run_loop = core.run_loop.clone();
1298    map.set_waker(Some(Arc::new(move || {
1299        if !scheduled.swap(true, Ordering::SeqCst) {
1300            post(&run_loop, move |core, outbox| flush(core, id, outbox));
1301        }
1302    })));
1303    published.applied.store(1, Ordering::SeqCst);
1304    core.maps.insert(
1305        id,
1306        MapEntry {
1307            core: map,
1308            published,
1309            mask: options.event_mask,
1310            applied: 1,
1311            pending_style: None,
1312            pending_still: None,
1313            session: None,
1314            flush_scheduled,
1315            ends: Ends::default(),
1316            feature_state: FeatureStateStore::default(),
1317            callback_sources: CallbackSources::default(),
1318            geojson_updates: GeoJsonUpdates::default(),
1319        },
1320    );
1321    flush(core, id, outbox);
1322    if let Some(entry) = core.maps.get(&id) {
1323        outbox.resolve(resolver, Ok(entry.applied()));
1324    }
1325}
1326
1327/// Runs a command on the map `id`, which must be there: handles what came
1328/// before it, applies it, publishes the map's state, sends its events, and
1329/// runs `after` with what `apply` returned. Then it tells the map's render
1330/// session that the command ran, so `after` can send the session what the
1331/// session must see first.
1332pub(crate) fn apply_command<T>(
1333    core: &mut RuntimeCore,
1334    id: MapId,
1335    sequence: u64,
1336    outbox: &mut Outbox,
1337    apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> T,
1338    after: impl FnOnce(&MapEntry, T, Applied, &mut Outbox),
1339) {
1340    flush(core, id, outbox);
1341    let Some(entry) = core.maps.get_mut(&id) else { return };
1342    let value = apply(entry, outbox);
1343    entry.applied = sequence;
1344    flush(core, id, outbox);
1345    let Some(entry) = core.maps.get(&id) else { return };
1346    after(entry, value, entry.applied(), outbox);
1347    entry.published.applied.store(sequence, Ordering::SeqCst);
1348    if let Some(link) = &entry.session {
1349        worker_post(&link.run_loop, move |worker, outbox| worker.map_applied(sequence, outbox));
1350    }
1351}
1352
1353/// Runs a command on the map `id` and completes with what `finish` makes of
1354/// its result and the map after it.
1355pub(crate) fn run_command<T, R: 'static>(
1356    core: &mut RuntimeCore,
1357    id: MapId,
1358    sequence: u64,
1359    apply: impl FnOnce(&mut MapEntry, &mut Outbox) -> Result<T, Error>,
1360    finish: impl FnOnce(T, &MapEntry) -> R,
1361    resolver: Resolver<R>,
1362    outbox: &mut Outbox,
1363) {
1364    if !core.maps.contains_key(&id) {
1365        return outbox.resolve(resolver, Err(missing_map()));
1366    }
1367    apply_command(core, id, sequence, outbox, apply, move |entry, result, _, outbox| {
1368        outbox.resolve(resolver, result.map(|value| finish(value, entry)));
1369    });
1370}
1371
1372/// Starts a style load on the map `id`. Its completion waits for the load's
1373/// outcome, which a flush finds among the map's events.
1374fn load_style(
1375    core: &mut RuntimeCore,
1376    id: MapId,
1377    sequence: u64,
1378    load: StyleLoad,
1379    resolver: Resolver<Applied>,
1380    outbox: &mut Outbox,
1381) {
1382    if !core.maps.contains_key(&id) {
1383        return outbox.resolve(resolver, Err(missing_map()));
1384    }
1385    // The flush before the load sends the outcomes of earlier loads to their
1386    // own completions.
1387    apply_command(
1388        core,
1389        id,
1390        sequence,
1391        outbox,
1392        move |entry, outbox| {
1393            let from_json = matches!(load, StyleLoad::Json(_));
1394            if let Some(previous) = entry.pending_style.replace(PendingStyle { resolver, from_json }) {
1395                outbox.resolve(previous.resolver, Err(Error::cancelled("another style load started")));
1396            }
1397            let style = entry.core.style_mut();
1398            match load {
1399                StyleLoad::Url(url) => style.load_url(&url),
1400                StyleLoad::Json(json) => style.load_json(&json),
1401            }
1402        },
1403        |_, (), _, _| {},
1404    );
1405}
1406
1407/// Handles what the map's style and renderer reported, publishes its state,
1408/// and sends its events.
1409pub(crate) fn flush(core: &mut RuntimeCore, id: MapId, outbox: &mut Outbox) {
1410    let Some(entry) = core.maps.get_mut(&id) else { return };
1411    entry.flush_scheduled.store(false, Ordering::SeqCst);
1412    let events = entry.core.drain_events();
1413    // The sources that left the style, by a command or a style load, let go
1414    // of what they held before anything reports the change.
1415    crate::style::reconcile(entry, outbox);
1416    let generation = entry.core.generation();
1417    *entry.published.snapshot.lock_unpoisoned() = Some(entry.core.snapshot());
1418
1419    let mut style_outcome = None;
1420    let from_json = entry.pending_style.as_ref().is_some_and(|pending| pending.from_json);
1421    for event in &events {
1422        match event {
1423            MapEvent::StyleLoaded => {
1424                // A new style's sources start without state.
1425                entry.feature_state.clear();
1426                style_outcome = Some(Ok(()));
1427            }
1428            MapEvent::LoadingFailed(StyleLoadError::Parse(message)) if from_json => {
1429                style_outcome = Some(Err(Error::invalid_argument(message)));
1430            }
1431            MapEvent::LoadingFailed(error) => style_outcome = Some(Err(Error::native(error.message()))),
1432            _ => {}
1433        }
1434    }
1435    let style_outcome = style_outcome.map(|outcome| (outcome, entry.pending_style.take(), entry.applied()));
1436    let still_outcome = entry.pending_still.as_ref().and_then(|pending| pending.outcome.borrow_mut().take());
1437    let still = still_outcome.and_then(|outcome| Some((outcome, entry.pending_still.take()?.resolver)));
1438
1439    let mask = entry.mask;
1440    let events: Vec<RuntimeEvent> = events
1441        .into_iter()
1442        .map(RuntimeEventKind::Map)
1443        .filter(|kind| mask.contains(kind.event_type()))
1444        .map(|kind| RuntimeEvent { source: EventSource::Map { id, generation }, kind })
1445        .collect();
1446    let ends = entry.ends.clone();
1447    core.send_events(events, outbox);
1448    ends.deliver(generation, outbox);
1449
1450    if let Some((outcome, Some(pending), applied)) = style_outcome {
1451        outbox.resolve(pending.resolver, outcome.map(|()| applied));
1452    }
1453    if let Some((outcome, resolver)) = still {
1454        outbox.resolve(resolver, outcome);
1455    }
1456}
1457
1458/// Lets go of the map `id`, after sending the events it still had.
1459fn remove(core: &mut RuntimeCore, id: MapId, done: Option<Resolver<()>>, outbox: &mut Outbox) {
1460    flush(core, id, outbox);
1461    if let Some(mut entry) = core.maps.remove(&id) {
1462        entry.core.set_waker(None);
1463        if let Some(pending) = entry.pending_style.take() {
1464            outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1465        }
1466        if let Some(pending) = entry.pending_still.take() {
1467            outbox.resolve(pending.resolver, Err(Error::cancelled("the map was released")));
1468        }
1469        crate::style::release(&mut entry, outbox);
1470        // The map's camera changes end as closed as it drops, with no
1471        // snapshot to show them.
1472        let ends = entry.ends.clone();
1473        drop(entry);
1474        ends.deliver(0, outbox);
1475    }
1476    if let Some(done) = done {
1477        outbox.resolve(done, Ok(()));
1478    }
1479}