mln-rs-runtime 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
use std::sync::Arc;
use std::sync::atomic::Ordering;

use mln_engine::{RenderMode, Renderer, RendererEvent, Update};
use mln_gfx::Handoff;
use mln_style::error::Error;

use super::init::Gfx;
use super::{Task, Worker, post};
use crate::render::frame::{DemandMode, FrameDemand, FrameDisposition, FrameResult};
use crate::render::session::{DemandGuard, Published, RenderSessionState};
use crate::runtime::Outbox;

/// A host's frame demand on its way, and the last command sent before it.
pub(super) struct PendingDemand {
    pub(super) demand: FrameDemand,
    pub(super) sequence: u64,
    /// The map's frame sample that the demand waits for, or 0.
    pub(super) sample: u64,
    /// The demand's place among the demands that reached the session.
    pub(super) serial: u64,
    /// Counts this demand against the session's pending demands until it is
    /// evaluated or ended.
    _guard: DemandGuard,
}

/// The demand that renders the map's still image while the image waits for
/// a frame. Its result has no token.
pub(super) struct StillDemand {
    /// The `still_image_request_id` of the image.
    pub(super) request: u64,
    /// The update that the demand tried and drew nothing of, since a
    /// resource that the image needs had yet to load. The demand waits for
    /// a newer one.
    pub(super) tried: Option<u64>,
}

/// A frame that the worker rendered, or tried to, and has yet to publish.
struct RenderedFrame {
    result: FrameResult,
    /// The renderer's events of the frame.
    events: Vec<RendererEvent>,
    /// The ring slot that the frame rendered into, with what the host may
    /// acquire of it.
    slot: Option<(usize, Option<Published>)>,
}

/// How a frame that was drawn for a still image ended.
#[derive(Clone, Copy, Debug)]
enum FrameOutcome {
    /// The frame went through its handoff.
    Handed,
    /// The frame was drawn for a host's demand.
    ForDemand,
    /// A surface dropped the frame.
    Dropped,
}

/// Takes the still image off the reports in `events` of a frame that ends
/// none: one drawn for a host's demand, or one that a surface `dropped`,
/// which has no picture to complete it with. A dropped frame that failed
/// keeps it, so that its error fails the still image it was drawn for.
fn disown_still(events: &mut [RendererEvent], outcome: FrameOutcome) {
    if matches!(outcome, FrameOutcome::Handed) {
        return;
    }
    for event in events {
        if let RendererEvent::RenderFrameFinished { still_image_request_id, error, .. } = event
            && (matches!(outcome, FrameOutcome::ForDemand) || error.is_none())
        {
            *still_image_request_id = 0;
        }
    }
}

/// Work that waits for the work sent before it: resizes that haven't
/// landed, and demands that wait for the map's commands.
pub(super) struct Behind {
    /// How many of the session's resizes must land first.
    resizes: u64,
    /// How many demands reached the session before the work.
    demands: u64,
    task: Task,
}

/// The texture of a borrowed ring that the next frame renders into.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RingPick {
    /// The target isn't a ring.
    None,
    /// The ring's texture at this slot, which is now marked as rendering.
    Slot(usize),
    /// The host holds a frame in every texture it may render into.
    Full,
    /// No texture may be rendered into again.
    Quarantined,
}

/// What the renderer reported about the frame it drew.
struct FrameReport {
    mode: RenderMode,
    needs_repaint: bool,
}

impl Worker {
    /// Whether the map ran what `pending` waits for: the commands sent
    /// before it, and its frame sample.
    fn ran(&self, pending: &PendingDemand) -> bool {
        pending.sequence <= self.map_applied && pending.sample <= self.map_sampled
    }

    /// Takes a host's demand, which supersedes the demands with its mode on
    /// their way unless it forces a frame.
    pub(crate) fn demand(
        &mut self,
        demand: FrameDemand,
        sequence: u64,
        sample: u64,
        guard: DemandGuard,
        outbox: &mut Outbox,
    ) {
        if self.torn_down {
            let result = FrameResult::unrendered(Some(demand.token), FrameDisposition::TargetNotReady, 0);
            return self.publish(&result, outbox);
        }
        if demand.mode != DemandMode::Force {
            let latest = self.latest_generation();
            let (superseded, kept): (Vec<_>, Vec<_>) =
                self.queue.drain(..).partition(|pending| pending.demand.mode == demand.mode);
            self.queue = kept.into();
            let (waiting_superseded, waiting): (Vec<_>, Vec<_>) =
                self.waiting.drain(..).partition(|(pending, _)| pending.demand.mode == demand.mode);
            self.waiting = waiting;
            let superseded = superseded.into_iter().chain(waiting_superseded.into_iter().map(|(pending, _)| pending));
            for pending in superseded {
                let result = FrameResult::unrendered(Some(pending.demand.token), FrameDisposition::Superseded, latest);
                self.publish(&result, outbox);
            }
        }
        self.demands_received += 1;
        self.queue.push_back(PendingDemand { demand, sequence, sample, serial: self.demands_received, _guard: guard });
        self.pump(outbox);
    }

    /// Evaluates the demands whose commands ran, then the demand of a still
    /// image that the map waits for, then the demands whose update came: an
    /// update that the image's frame showed is no news to them.
    pub(super) fn pump(&mut self, outbox: &mut Outbox) {
        if self.torn_down {
            return;
        }
        if self.reader.is_none() {
            // A demand that came after a failed bind ends at once.
            if self.unbound {
                self.end_demands(FrameDisposition::Failed, outbox);
            }
            return self.run_queued(outbox);
        }
        while let Some(pending) = self.parked.pop_front() {
            if let Some(pending) = self.evaluate(pending, outbox) {
                self.parked.push_front(pending);
                self.run_queued(outbox);
                return self.serve_still(outbox);
            }
        }
        self.run_queued(outbox);
        self.serve_still(outbox);
        let latest = self.latest_generation();
        let retargeting = self.retargeting();
        let (updated, waiting): (Vec<_>, Vec<_>) =
            self.waiting.drain(..).partition(|(_, seen)| !retargeting && latest > *seen);
        self.waiting = waiting;
        for (pending, _) in updated {
            if let Some(pending) = self.evaluate(pending, outbox) {
                self.parked.push_back(pending);
            }
        }
    }

    /// Whether a ring replacement is on its way, which gives the demands
    /// that wait a new target: they render to it once it lands.
    fn retargeting(&self) -> bool {
        self.shared.state.lock().pending_retargets != 0
    }

    /// Runs the demands whose map commands ran and the work that waits
    /// behind earlier work, in the order they came, until each has to wait:
    /// a demand for the map's commands or for a parked demand, and other
    /// work for a resize to land or a demand sent before it that waits for
    /// the map's commands. Work doesn't wait for a ring to free a texture,
    /// as a parked demand and those behind it do.
    pub(super) fn run_queued(&mut self, outbox: &mut Outbox) {
        // A sample that the map took before the session bound to it told no
        // session.
        let sampled = self.map_published.as_ref().map_or(0, |published| published.sampled());
        self.map_sampled = self.map_sampled.max(sampled);
        loop {
            self.run_ready(outbox);
            // The map tells the session of the commands that the demands
            // left wait for. One may have run before it could.
            let awaited = self
                .queue
                .iter()
                .map(|pending| pending.sequence)
                .filter(|sequence| *sequence > self.map_applied)
                .min()
                .unwrap_or(u64::MAX);
            self.shared.awaited_command.store(awaited, Ordering::SeqCst);
            let applied = self.map_published.as_ref().map_or(0, |published| published.applied());
            if awaited == u64::MAX || applied < awaited {
                return;
            }
            self.map_applied = applied;
        }
    }

    /// Runs what [`run_queued`](Self::run_queued) runs, with the map's
    /// commands that the session knows ran.
    fn run_ready(&mut self, outbox: &mut Outbox) {
        loop {
            let front = self.queue.front().map(|pending| (pending.serial, self.ran(pending)));
            let work_first =
                self.behind.front().is_some_and(|behind| front.is_none_or(|(serial, _)| behind.demands < serial));
            let evaluable = !self.torn_down && self.reader.is_some() && self.parked.is_empty();
            if !work_first && evaluable && front.is_some_and(|(_, ready)| ready) {
                if let Some(pending) = self.queue.pop_front()
                    && let Some(pending) = self.evaluate(pending, outbox)
                {
                    self.parked.push_back(pending);
                }
                continue;
            }
            let waits = |behind: &Behind| {
                behind.resizes > self.resizes_landed
                    || self.queue.iter().any(|pending| pending.serial <= behind.demands && !self.ran(pending))
            };
            match self.behind.front() {
                Some(behind) if !waits(behind) => {
                    if let Some(behind) = self.behind.pop_front() {
                        (behind.task)(self, outbox);
                    }
                }
                _ => return,
            }
        }
    }

    /// Renders the demand, or ends it, or has it wait for an update. Returns
    /// it when it waits for the ring to free a texture.
    fn evaluate(&mut self, pending: PendingDemand, outbox: &mut Outbox) -> Option<PendingDemand> {
        let token = Some(pending.demand.token);
        let latest = self.latest();
        let latest_generation = latest.as_ref().map_or(0, |update| update.generation);
        self.fail_if_device_lost(outbox);
        if self.gfx.is_none() {
            let failed = self.shared.state.lock().lifecycle == RenderSessionState::Failed;
            let disposition = if failed { FrameDisposition::Failed } else { FrameDisposition::TargetNotReady };
            self.publish(&FrameResult::unrendered(token, disposition, latest_generation), outbox);
            return None;
        }
        let changed = latest_generation != self.rendered_update || self.generation() != self.rendered_generation;
        let rendered = match latest {
            Some(update) if pending.demand.mode == DemandMode::Force || changed => {
                // The texture is picked and marked in one step, so the host
                // can't acquire it in between.
                let slot = match self.pick_slot() {
                    RingPick::Full => return Some(pending),
                    RingPick::Quarantined => {
                        let result =
                            FrameResult::unrendered(token, FrameDisposition::TargetNotReady, latest_generation);
                        self.publish(&result, outbox);
                        return None;
                    }
                    RingPick::None => None,
                    RingPick::Slot(slot) => Some(slot),
                };
                self.rendering = token;
                let frame = self.render(token, &update, slot);
                self.rendering = None;
                let rendered = frame.result.disposition == FrameDisposition::Rendered;
                self.publish_rendered(frame, outbox);
                rendered
            }
            _ if pending.demand.mode == DemandMode::WaitForUpdate => {
                self.waiting.push((pending, latest_generation));
                return None;
            }
            _ => {
                self.publish(&FrameResult::unrendered(token, FrameDisposition::NoUpdate, latest_generation), outbox);
                false
            }
        };
        drop(pending);
        // An update published after `self.latest()` above had its redraw wake
        // held back while this demand was pending; and a running animation
        // moves only when a demand samples it, so the frame wakes the host for
        // the next.
        if self.latest_generation() != latest_generation
            || (rendered && self.map_published.as_ref().is_some_and(|published| published.animating()))
        {
            self.wake_for_redraw(outbox);
        }
        None
    }

    /// The map's still image changed: one waits for a frame, or none does.
    pub(crate) fn still_image_changed(&mut self, outbox: &mut Outbox) {
        self.serve_still(outbox);
    }

    /// The still image that waits for a frame, as the
    /// `still_image_request_id` of the updates that ask for it, or 0.
    pub(super) fn pending_still_image(&self) -> u64 {
        self.map_published.as_ref().map_or(0, |published| published.pending_still_image())
    }

    /// Serves the map's still image: demands a frame for it while it waits
    /// for one, and renders the demand once the target can take a frame and
    /// the map has an update that it hasn't tried. The demand finishes with
    /// the image's frame. One that draws nothing, because a resource that
    /// the image needs is still loading, waits for the map's next update,
    /// and one that finds the ring full parks until the host releases a
    /// frame. An offscreen target that can't begin a frame fails the image
    /// rather than waits. A host's demands neither replace nor wait for it.
    /// Ending the demands on their way ends it too, until the session can
    /// render again: a barrier demands the image again once it ran, a new
    /// target once it lands, and the next session once it attaches.
    fn serve_still(&mut self, outbox: &mut Outbox) {
        let pending = self.pending_still_image();
        // The image completed or failed meanwhile, and the next one, if one
        // waits, gets a demand of its own.
        if self.still.as_ref().is_some_and(|still| still.request != pending) {
            self.still = None;
            let result = FrameResult::unrendered(None, FrameDisposition::NoUpdate, self.latest_generation());
            self.publish(&result, outbox);
        }
        if pending == 0 {
            return;
        }
        if self.still.is_none() {
            if pending <= self.still_rendered || !self.can_render() {
                return;
            }
            self.still = Some(StillDemand { request: pending, tried: None });
        }
        // The demand ends once the map fails the image.
        if pending == self.still_failing.get() {
            return;
        }
        let Some(update) = self.latest() else { return };
        // The update that asks for the image comes before the map says that
        // the image waits.
        let asks = update.parameters.still_image_request && update.parameters.still_image_request_id == pending;
        let tried = self.still.as_ref().and_then(|still| still.tried);
        if !asks || tried == Some(update.generation) || self.retargeting() {
            return;
        }
        if !self.gfx.as_mut().is_some_and(|gfx| gfx.target.ready_for_frame()) {
            // An offscreen target that can't begin a frame won't by waiting:
            // the map fails the image on the error, with the demand's result
            // queued first.
            if self.gfx.as_ref().is_some_and(|gfx| gfx.target.is_offscreen()) {
                self.still = None;
                self.still_rendered = pending;
                self.publish(&FrameResult::unrendered(None, FrameDisposition::NoUpdate, update.generation), outbox);
                let error = Error::invalid_state(
                    "the offscreen target has no pixels at its size and scale factor, or more than the device's textures take",
                );
                self.forward(vec![RendererEvent::ResourceError(error)]);
            }
            return;
        }
        if self.fail_if_device_lost(outbox) {
            return;
        }
        let slot = match self.pick_slot() {
            RingPick::Full => return,
            RingPick::Quarantined => {
                self.still = None;
                let result = FrameResult::unrendered(None, FrameDisposition::TargetNotReady, update.generation);
                return self.publish(&result, outbox);
            }
            RingPick::None => None,
            RingPick::Slot(slot) => Some(slot),
        };
        let frame = self.render(None, &update, slot);
        // A tile that failed during the frame counts as loaded, so the frame
        // drew the map without it, but the map fails the image on the error,
        // as it does on the image's frame's own failure on the GPU. The
        // demand ends first, so that the image fails with its result queued.
        let fails = frame.events.iter().any(|event| match event {
            RendererEvent::ResourceError(_) => true,
            RendererEvent::RenderFrameFinished { error, still_image_request_id, .. } => {
                error.is_some() && *still_image_request_id == pending
            }
            _ => false,
        });
        if fails {
            self.still = None;
            self.still_rendered = pending;
            let result = FrameResult::unrendered(None, FrameDisposition::NoUpdate, update.generation);
            self.publish_frame(frame.slot.map(|(slot, _)| (slot, None)), &result, outbox);
            return self.forward(frame.events);
        }
        match frame.result.disposition {
            FrameDisposition::Rendered => {
                self.still = None;
                self.still_rendered = pending;
                self.publish_rendered(frame, outbox);
            }
            disposition => {
                // A frame that a surface dropped is tried again.
                if disposition == FrameDisposition::NoUpdate
                    && let Some(still) = self.still.as_mut()
                {
                    still.tried = Some(update.generation);
                }
                if let Some((slot, published)) = frame.slot {
                    self.end_slot(slot, published);
                }
                self.forward(frame.events);
            }
        }
    }

    /// Whether the session can render a frame for a demand of its own: it
    /// attached, has a target, and a ring with a texture it may render into.
    fn can_render(&self) -> bool {
        if self.torn_down || self.reader.is_none() || self.gfx.is_none() {
            return false;
        }
        let state = self.shared.state.lock();
        state.lifecycle == RenderSessionState::Attached
            && state.has_target
            && (state.ring.is_empty() || !state.ring.iter().all(|slot| slot.quarantined))
    }

    fn generation(&self) -> u64 {
        self.shared.state.lock().generation
    }

    /// Renders `update` for the demand `token`, or for the still image's
    /// demand when it has none, into the ring's `slot`, which
    /// [`pick_slot`](Self::pick_slot) marked, or into a target without a
    /// ring. Returns the frame, which
    /// [`publish_rendered`](Self::publish_rendered) publishes. A still map draws no frame until everything that it shows
    /// has loaded, and a surface without a texture to render into takes no
    /// frame. A frame that a surface drops, having had no image for it after
    /// all, finishes as not ready, and the next demand draws the map again.
    /// Only the still image's own frame completes the image or fails it
    /// ([`disown_still`]).
    fn render(&mut self, token: Option<u64>, update: &Update, slot: Option<usize>) -> RenderedFrame {
        let ready = self.gfx.as_mut().is_some_and(|gfx| gfx.target.ready_for_frame());
        let Some(gfx) = self.gfx.as_mut().filter(|_| ready) else {
            if let Some(slot) = slot {
                self.end_slot(slot, None);
            }
            let result = FrameResult::unrendered(token, FrameDisposition::TargetNotReady, update.generation);
            return RenderedFrame { result, events: Vec::new(), slot: None };
        };
        if let Some(slot) = slot
            && gfx.target.select_slot(slot).is_err()
        {
            self.end_slot(slot, None);
            let result = FrameResult::unrendered(token, FrameDisposition::TargetNotReady, update.generation);
            return RenderedFrame { result, events: Vec::new(), slot: None };
        }
        let handoff = gfx.target.render(&update.parameters);
        {
            let mut state = self.shared.state.lock();
            state.graphics_objects = state.graphics_objects.max(Gfx::OBJECTS);
        }
        let mut events = self.renderer_events.take();
        let dropped = gfx.target.is_presenting() && matches!(handoff, Some(Handoff::Dropped));
        let outcome = if token.is_some() {
            FrameOutcome::ForDemand
        } else if dropped {
            FrameOutcome::Dropped
        } else {
            FrameOutcome::Handed
        };
        disown_still(&mut events, outcome);
        if dropped {
            let result = FrameResult::unrendered(token, FrameDisposition::TargetNotReady, update.generation);
            return RenderedFrame { result, events, slot: None };
        }
        let projection = gfx.target.renderer().and_then(Renderer::frame_projection);
        // The previous render's sources may hold the last references to
        // replaced data, which the renderer's workers free instead.
        let sources = update.parameters.style.sources();
        if let Some(previous) = self.sources.replace(Arc::clone(sources))
            && !Arc::ptr_eq(&previous, sources)
            && let Some(renderer) = gfx.target.renderer()
        {
            renderer.drop_on_workers(previous);
        }
        self.rendered_update = update.generation;
        self.rendered_generation = self.generation();
        let report = events.iter().rev().find_map(|event| match event {
            RendererEvent::RenderFrameFinished { mode, needs_repaint, repaint_at, .. } => {
                Some(FrameReport { mode: *mode, needs_repaint: *needs_repaint || repaint_at.is_some() })
            }
            _ => None,
        });
        let result = match report {
            Some(report) => {
                self.has_frame = true;
                // The session takes the frame's generation in
                // `publish_frame`.
                let (generation, frame_generation) = {
                    let state = self.shared.state.lock();
                    (state.generation, state.frame_generation + 1)
                };
                FrameResult {
                    disposition: FrameDisposition::Rendered,
                    token,
                    map_update_generation: update.generation,
                    generation,
                    frame_generation,
                    needs_repaint: report.needs_repaint,
                    view: Some(update.parameters.view.map_view(self.scale_factor)),
                    mode: report.mode,
                    projection,
                }
            }
            None => FrameResult::unrendered(token, FrameDisposition::NoUpdate, update.generation),
        };
        let slot = slot.map(|slot| {
            let published = match handoff {
                Some(Handoff::GivenBack { slot: given, sync }) if given == slot && result.view.is_some() => {
                    let device = self.gfx.as_ref().map(|gfx| gfx.target.device().clone());
                    let texture = self.ring.as_ref().zip(device).and_then(|(ring, device)| ring.texture(slot, &device));
                    Some(Published { result: result.clone(), sync, texture })
                }
                Some(Handoff::Queued { slot: given, sync }) if given == slot && result.view.is_some() => {
                    let texture = self.gfx.as_ref().and_then(|gfx| gfx.target.exported_texture(slot));
                    Some(Published { result: result.clone(), sync, texture })
                }
                _ => None,
            };
            (slot, published)
        });
        RenderedFrame { result, events, slot }
    }

    /// Publishes a frame: its result and ring slot, then the renderer's
    /// events of the frame, which go to the map after the result, so that a
    /// still image completes with its frame's result queued.
    fn publish_rendered(&self, frame: RenderedFrame, outbox: &mut Outbox) {
        self.publish_frame(frame.slot, &frame.result, outbox);
        self.forward(frame.events);
    }

    /// Queues a frame result for the host, and wakes it unless it was woken
    /// since its last drain.
    pub(super) fn publish(&self, result: &FrameResult, outbox: &mut Outbox) {
        self.publish_frame(None, result, outbox);
    }

    /// Publishes a frame: ends the ring `slot` it rendered into, with what
    /// the host may acquire of it, and queues its result as `publish` does.
    /// The slot, the result and the session's frame generation change under
    /// one lock, so a snapshot shows a frame only once its result can be
    /// drained and, in a ring, its slot acquired.
    fn publish_frame(&self, slot: Option<(usize, Option<Published>)>, result: &FrameResult, outbox: &mut Outbox) {
        let wake = {
            let mut state = self.shared.state.lock();
            if let Some((slot, published)) = slot
                && let Some(entry) = state.ring.get_mut(slot)
            {
                entry.rendering = false;
                entry.frame = published;
            }
            state.results.push(result.clone());
            state.frame_generation = state.frame_generation.max(result.frame_generation);
            let wake = !state.frame_woken;
            state.frame_woken = true;
            wake.then(|| self.shared.frame_wake.clone()).flatten()
        };
        if let Some(wake) = wake {
            outbox.push(move || wake());
        }
    }

    /// Ends every demand on its way with `disposition`, the still image's
    /// included, and reports whether any host demand ended.
    pub(crate) fn end_demands(&mut self, disposition: FrameDisposition, outbox: &mut Outbox) -> bool {
        let latest = self.latest_generation();
        let pending: Vec<_> = self
            .parked
            .drain(..)
            .chain(self.queue.drain(..))
            .chain(self.waiting.drain(..).map(|(pending, _)| pending))
            .collect();
        let ended = !pending.is_empty();
        for pending in pending {
            self.publish(&FrameResult::unrendered(Some(pending.demand.token), disposition, latest), outbox);
        }
        if self.still.take().is_some() {
            self.publish(&FrameResult::unrendered(None, disposition, latest), outbox);
        }
        ended
    }

    /// Ends every demand on its way as a barrier does, then demands the
    /// still image again, if one waits, once the barrier ran.
    pub(crate) fn barrier(&mut self, outbox: &mut Outbox) {
        let ended = self.end_demands(FrameDisposition::NoUpdate, outbox);
        if ended && self.gfx.is_some() && self.latest().is_some_and(|update| update.generation != self.rendered_update)
        {
            self.wake_for_redraw(outbox);
        }
        post(&self.shared.queue, Worker::still_image_changed);
    }

    /// Runs `task` after the work sent before it: once `resizes` of the
    /// session's resizes have landed, and the demands that came before it
    /// and wait for the map's commands have rendered or ended.
    pub(crate) fn after_earlier_work(&mut self, resizes: u64, task: Task, outbox: &mut Outbox) {
        self.behind.push_back(Behind { resizes, demands: self.demands_received, task });
        self.run_queued(outbox);
    }

    pub(super) fn resize_landed(&mut self, outbox: &mut Outbox) {
        self.resizes_landed += 1;
        self.run_queued(outbox);
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use mln_engine::{RenderMode, RendererEvent};
    use mln_style::error::Error;

    use super::{FrameOutcome, disown_still};

    /// The still image that a frame of the image's update, failed or not,
    /// ends once its report reaches the map.
    fn still_ended(failed: bool, outcome: FrameOutcome) -> u64 {
        let mut events = [RendererEvent::RenderFrameFinished {
            mode: RenderMode::Full,
            needs_repaint: false,
            repaint_at: None,
            placement_changed: false,
            still_image_request_id: 7,
            update_id: 0,
            stats: Arc::default(),
            error: failed.then(|| Box::new(Error::failed("the device was reset"))),
        }];
        disown_still(&mut events, outcome);
        let [RendererEvent::RenderFrameFinished { still_image_request_id, .. }] = events else { unreachable!() };
        still_image_request_id
    }

    /// A frame of the still's update ends it once handed over, and once it
    /// failed whether or not a surface dropped it, so that the still fails
    /// rather than waits. A dropped frame that drew ends no still, which is
    /// drawn again, and a frame for a host's demand ends none.
    #[test]
    fn a_frame_ends_its_still_when_handed_over_or_failed_but_not_for_a_demand() {
        for (failed, outcome, ended) in [
            (false, FrameOutcome::Handed, true),
            (true, FrameOutcome::Handed, true),
            (true, FrameOutcome::Dropped, true),
            (false, FrameOutcome::Dropped, false),
            (false, FrameOutcome::ForDemand, false),
            (true, FrameOutcome::ForDemand, false),
        ] {
            let still = if ended { 7 } else { 0 };
            assert_eq!(still, still_ended(failed, outcome), "failed {failed}, {outcome:?}");
        }
    }
}