Skip to main content

day_core/
image.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Raster images (docs/images.md): decoding encoded bytes into a native image, reading what it
5//! is, encoding it back, and releasing it again. Rendering a canvas drawing into a bitmap or a
6//! PDF (docs/canvas.md "Exporting") lives here too: a rendered bitmap is the same [`Bitmap`] a
7//! decode returns, held in the same toolkit table.
8//!
9//! The shape mirrors presentation (`present.rs`): a request id, a pending registry, and a
10//! completion that arrives as an [`day_spec::Event`] the backend raises. It is request-shaped rather than
11//! blocking because one backend can never answer synchronously (a browser decodes through
12//! `createImageBitmap`, which is a promise), and one async-shaped API everywhere beats a
13//! synchronous one that is a lie on the web (docs/async.md rule 3: a callback and a future,
14//! never a runtime).
15//!
16//! Everything here is thread-local and `!Send`, like the rest of day-core: Day has one UI thread.
17
18use std::cell::{Cell, RefCell};
19use std::collections::HashMap;
20use std::future::Future;
21use std::pin::Pin;
22use std::rc::Rc;
23use std::sync::Arc;
24use std::task::{Context, Poll, Waker};
25
26use day_spec::{
27    BitmapId, BitmapInfo, Cap, DrawOp, EncodeSpec, ExportError, ImageError, ImageFormat,
28    ImageProperties, PdfInfo, PdfPage, Size,
29};
30
31use crate::with_tree;
32
33day_reactive::tls_slots! {
34    image;
35    /// Keyed by request id, carrying the bitmap id day-core minted for it: the completion brings
36    /// only what the decoder read, never an id, so nothing a backend answers can name a handle
37    /// to something else.
38    static PENDING_DECODE: RefCell<HashMap<u64, (BitmapId, Pending<(BitmapId, BitmapInfo)>)>> =
39        RefCell::new(HashMap::new());
40    static PENDING_ENCODE: RefCell<HashMap<u64, Pending<Vec<u8>>>> = RefCell::new(HashMap::new());
41    /// Canvas exports, keyed like the decodes: a rendered bitmap's id is minted here too.
42    static PENDING_BITMAP: RefCell<HashMap<u64, (BitmapId, Waiting<(BitmapId, BitmapInfo), ExportError>)>> =
43        RefCell::new(HashMap::new());
44    static PENDING_PDF: RefCell<HashMap<u64, Waiting<Vec<u8>, ExportError>>> =
45        RefCell::new(HashMap::new());
46    /// Releases that arrived while the tree was borrowed (a handler dropping its last handle
47    /// inside `collect_and_release`), drained at the top of the next pump, once the borrow ends.
48    static DEFERRED_RELEASE: RefCell<Vec<BitmapId>> = RefCell::new(Vec::new());
49    static NEXT_REQ: Cell<u64> = const { Cell::new(1) };
50    /// [`canvas_exports`]'s answer for the installed tree, read once: the caps and the encode
51    /// list never change under a running toolkit, and a context menu built inside the tree's
52    /// own borrow must still be able to ask.
53    static EXPORTS: Cell<Option<CanvasExports>> = const { Cell::new(None) };
54    /// Ids are minted here, not by the backends: day-core hands the id to the backend with the
55    /// bytes, so the backend's side table is keyed by something the app can name afterwards.
56    /// Never reused, so a completion arriving after a release finds nothing and does nothing.
57    static NEXT_BITMAP: Cell<u64> = const { Cell::new(1) };
58}
59
60/// A caller waiting by CALLBACK rather than by future (docs/async.md rule 3): what
61/// `decode_async` / `encode_async` hand over in place of an `.await`.
62///
63/// Named rather than spelled out at each use so the three signatures below read as one idea,
64/// and not `Done<T>`, which is day-bridge's callback tier and a different thing.
65type ImageDone<T, E = ImageError> = Box<dyn FnOnce(Result<T, E>)>;
66
67/// One waiting caller: either a future parked on a `Waker`, or a plain callback. The error is
68/// [`ImageError`] for the image duties and [`ExportError`] for canvas exports.
69struct Waiting<T, E> {
70    shared: Rc<Shared<T, E>>,
71    callback: Option<ImageDone<T, E>>,
72}
73
74/// The image duties' waiter, named so their signatures read as before.
75type Pending<T> = Waiting<T, ImageError>;
76
77struct Shared<T, E = ImageError> {
78    result: RefCell<Option<Result<T, E>>>,
79    waker: RefCell<Option<Waker>>,
80    /// The future was dropped before its answer came. A decode that completes afterwards has
81    /// nobody to hand its image to, so the completion releases it instead of parking it.
82    cancelled: Cell<bool>,
83}
84
85impl<T, E> Default for Shared<T, E> {
86    fn default() -> Self {
87        Shared {
88            result: RefCell::new(None),
89            waker: RefCell::new(None),
90            cancelled: Cell::new(false),
91        }
92    }
93}
94
95fn next_req() -> u64 {
96    NEXT_REQ.with(|c| {
97        let v = c.get();
98        c.set(v + 1);
99        v
100    })
101}
102
103fn next_bitmap() -> BitmapId {
104    BitmapId(NEXT_BITMAP.with(|c| {
105        let v = c.get();
106        c.set(v + 1);
107        v
108    }))
109}
110
111// ---------------------------------------------------------------------------
112// The handle
113// ---------------------------------------------------------------------------
114
115/// A decoded image the toolkit holds, released when the last handle drops.
116///
117/// Cheap to clone (an `Rc`), so several nodes and the canvas can draw the same decode. `!Send`
118/// like everything else that talks to the toolkit.
119#[derive(Clone)]
120pub struct Bitmap(Rc<BitmapInner>);
121
122struct BitmapInner {
123    id: BitmapId,
124    info: BitmapInfo,
125}
126
127impl Drop for BitmapInner {
128    fn drop(&mut self) {
129        release(self.id);
130    }
131}
132
133/// Release a toolkit image now if the tree is free, and at the next pump if it is not.
134///
135/// A handle can die inside the tree's own borrow: `collect_and_release` drops a removed node's
136/// handlers, and a handler may own the last clone. A plain `with_tree` there would panic on the
137/// re-borrow, so the id is queued and [`flush_deferred_releases`] runs it once the borrow has
138/// ended. The tree being absent (teardown, or a test that never mounted one) is the other way
139/// to have nothing to release, and that is the no-op the duty promises.
140fn release(id: BitmapId) {
141    if crate::tree_absent() {
142        return;
143    }
144    if crate::with_tree_if_free(|t| t.release_image(id)).is_none() {
145        DEFERRED_RELEASE.with(|q| q.borrow_mut().push(id));
146        crate::request_pump();
147    }
148}
149
150/// Run the releases that could not run inline. Called at the top of every pump, which begins
151/// only once the tree borrow has ended; a pump nested inside a still-borrowed tree keeps them
152/// queued rather than dropping them.
153pub(crate) fn flush_deferred_releases() {
154    let ids: Vec<BitmapId> = DEFERRED_RELEASE.with(|q| std::mem::take(&mut *q.borrow_mut()));
155    for id in ids {
156        if crate::with_tree_if_free(|t| t.release_image(id)).is_none() {
157            DEFERRED_RELEASE.with(|q| q.borrow_mut().push(id));
158        }
159    }
160}
161
162impl Bitmap {
163    /// The id the toolkit knows this image by, which [`day_spec::ImageSource::Decoded`] carries.
164    #[must_use]
165    pub fn id(&self) -> BitmapId {
166        self.0.id
167    }
168
169    /// Pixel size, scale, format and alpha, read once at decode (docs/images.md).
170    #[must_use]
171    pub fn info(&self) -> BitmapInfo {
172        self.0.info
173    }
174
175    /// The metadata beyond the pixels: EXIF orientation, DPI, capture time. `None` where this
176    /// backend ships no metadata reader; probe [`Cap::ImageProperties`] before offering an
177    /// affordance that needs it.
178    #[must_use]
179    pub fn properties(&self) -> Option<ImageProperties> {
180        let id = self.0.id;
181        with_tree(|t| t.image_properties(id))
182    }
183
184    /// Encode back to bytes, in `spec`'s format. Await it inside `day::task`.
185    #[must_use]
186    pub fn encode(&self, spec: EncodeSpec) -> EncodeFuture {
187        EncodeFuture {
188            source: self.clone(),
189            spec,
190            shared: Rc::new(Shared::default()),
191            started: false,
192        }
193    }
194
195    /// [`Bitmap::encode`]'s callback half, for a call site that is not already async.
196    pub fn encode_async(
197        &self,
198        spec: EncodeSpec,
199        on_done: impl FnOnce(Result<Vec<u8>, ImageError>) + 'static,
200    ) {
201        if support(Cap::ImageEncode) == day_spec::Support::Unsupported {
202            on_done(Err(ImageError::Unsupported));
203            return;
204        }
205        // The clone rides in the callback so the toolkit's image outlives the encode however the
206        // app juggles its own handle; a browser encodes on a later turn.
207        let keep = self.clone();
208        start_encode(
209            self.0.id,
210            spec,
211            None,
212            Some(Box::new(move |r| {
213                drop(keep);
214                on_done(r);
215            })),
216        );
217    }
218}
219
220impl std::fmt::Debug for Bitmap {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        f.debug_struct("Bitmap")
223            .field("id", &self.0.id.0)
224            .field("info", &self.0.info)
225            .finish()
226    }
227}
228
229/// Two handles are the same image when they name the same decode.
230impl PartialEq for Bitmap {
231    fn eq(&self, other: &Self) -> bool {
232        self.0.id == other.0.id
233    }
234}
235
236// ---------------------------------------------------------------------------
237// Decoding
238// ---------------------------------------------------------------------------
239
240/// Decode encoded image bytes (PNG/JPEG/…) with the platform's own decoder.
241///
242/// ```ignore
243/// day::task(async move {
244///     match day::decode_image(bytes).await {
245///         Ok(bitmap) => shown.set(Some(bitmap)),
246///         Err(e) => log::warn!("not an image: {e}"),
247///     }
248/// });
249/// ```
250///
251/// `Err(ImageError::Unsupported)` where the backend has no byte decoder at all
252/// ([`Cap::ImageDecode`]); `Err(ImageError::Decode)` where it has one and the bytes are not an
253/// image it reads.
254#[must_use]
255pub fn decode(bytes: Arc<Vec<u8>>) -> DecodeFuture {
256    DecodeFuture {
257        bytes: Some(bytes),
258        shared: Rc::new(Shared::default()),
259        started: false,
260    }
261}
262
263/// [`decode`]'s callback half (docs/async.md rule 3), for a call site that is not already async.
264#[expect(
265    clippy::needless_pass_by_value,
266    reason = "public signature, the callback twin of the future-returning function it mirrors"
267)]
268pub fn decode_async(
269    bytes: Arc<Vec<u8>>,
270    on_done: impl FnOnce(Result<Bitmap, ImageError>) + 'static,
271) {
272    if support(Cap::ImageDecode) == day_spec::Support::Unsupported {
273        on_done(Err(ImageError::Unsupported));
274        return;
275    }
276    start_decode(
277        &bytes,
278        None,
279        Some(Box::new(move |r| on_done(r.map(bitmap_from)))),
280    );
281}
282
283/// Whether this toolkit can decode image bytes at all ([`Cap::ImageDecode`]).
284#[must_use]
285pub fn image_decode_support() -> day_spec::Support {
286    support(Cap::ImageDecode)
287}
288
289/// Whether this toolkit can encode a decoded image back to bytes ([`Cap::ImageEncode`]).
290#[must_use]
291pub fn image_encode_support() -> day_spec::Support {
292    support(Cap::ImageEncode)
293}
294
295/// Which formats [`Bitmap::encode`] can write here: the [`Cap::ImageEncode`]
296/// counterpart of `font_families()`. Empty where encoding is unsupported.
297#[must_use]
298pub fn image_encode_formats() -> Vec<ImageFormat> {
299    with_tree(|t| t.image_encode_formats())
300}
301
302fn support(cap: Cap) -> day_spec::Support {
303    with_tree(|t| t.capability(cap))
304}
305
306fn bitmap_from((id, info): (BitmapId, BitmapInfo)) -> Bitmap {
307    Bitmap(Rc::new(BitmapInner { id, info }))
308}
309
310/// Shared by the future and the callback form: mint the id, park the waiter, ask the toolkit.
311fn start_decode(
312    bytes: &[u8],
313    shared: Option<Rc<Shared<(BitmapId, BitmapInfo)>>>,
314    callback: Option<ImageDone<(BitmapId, BitmapInfo)>>,
315) -> u64 {
316    let req = next_req();
317    let id = next_bitmap();
318    PENDING_DECODE.with(|p| {
319        p.borrow_mut().insert(
320            req,
321            (
322                id,
323                Pending {
324                    shared: shared.unwrap_or_default(),
325                    callback,
326                },
327            ),
328        )
329    });
330    with_tree(|t| t.decode_image(req, id, bytes));
331    req
332}
333
334fn start_encode(
335    id: BitmapId,
336    spec: EncodeSpec,
337    shared: Option<Rc<Shared<Vec<u8>>>>,
338    callback: Option<ImageDone<Vec<u8>>>,
339) -> u64 {
340    let req = next_req();
341    PENDING_ENCODE.with(|p| {
342        p.borrow_mut().insert(
343            req,
344            Pending {
345                shared: shared.unwrap_or_default(),
346                callback,
347            },
348        )
349    });
350    with_tree(|t| t.encode_image(req, id, &spec));
351    req
352}
353
354/// A decode in flight. Resolves with the decoded [`Bitmap`], or why it could not be.
355pub struct DecodeFuture {
356    bytes: Option<Arc<Vec<u8>>>,
357    shared: Rc<Shared<(BitmapId, BitmapInfo)>>,
358    started: bool,
359}
360
361impl Future for DecodeFuture {
362    type Output = Result<Bitmap, ImageError>;
363
364    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
365        if let Some(result) = self.shared.result.borrow_mut().take() {
366            return Poll::Ready(result.map(bitmap_from));
367        }
368        if !self.started {
369            self.started = true;
370            if support(Cap::ImageDecode) == day_spec::Support::Unsupported {
371                return Poll::Ready(Err(ImageError::Unsupported));
372            }
373            let bytes = self.bytes.take().expect("decode bytes");
374            let shared = self.shared.clone();
375            start_decode(&bytes, Some(shared), None);
376            // A backend that decodes inline has already answered by now; every backend but the
377            // browser does, since `with_tree` pumps the completion on its way out. The waker is
378            // not registered yet at that point, so `deliver`'s wake reaches nobody; take the
379            // result here instead of parking forever. (Presentation never needed this: a native
380            // modal cannot answer before it is shown.)
381            if let Some(result) = self.shared.result.borrow_mut().take() {
382                return Poll::Ready(result.map(bitmap_from));
383            }
384        }
385        *self.shared.waker.borrow_mut() = Some(cx.waker().clone());
386        Poll::Pending
387    }
388}
389
390impl Drop for DecodeFuture {
391    fn drop(&mut self) {
392        // Answered but never taken: no handle was built, so the toolkit's image would outlive
393        // every owner. Release it here.
394        if let Some(Ok((id, _))) = self.shared.result.borrow_mut().take() {
395            release(id);
396        }
397        // Still in flight: the completion, when it comes, releases rather than parking a result
398        // nobody will read (`resolve_image_decode`).
399        self.shared.cancelled.set(true);
400    }
401}
402
403/// An encode in flight. Resolves with the encoded bytes, or why they could not be produced.
404pub struct EncodeFuture {
405    /// Held for the encode's whole life: dropping the app's last handle mid-encode would
406    /// otherwise release the very image the toolkit is still reading.
407    source: Bitmap,
408    spec: EncodeSpec,
409    shared: Rc<Shared<Vec<u8>>>,
410    started: bool,
411}
412
413impl Future for EncodeFuture {
414    type Output = Result<Vec<u8>, ImageError>;
415
416    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
417        if let Some(result) = self.shared.result.borrow_mut().take() {
418            return Poll::Ready(result);
419        }
420        if !self.started {
421            self.started = true;
422            if support(Cap::ImageEncode) == day_spec::Support::Unsupported {
423                return Poll::Ready(Err(ImageError::Unsupported));
424            }
425            let shared = self.shared.clone();
426            start_encode(self.source.id(), self.spec, Some(shared), None);
427            // Answered inline; see `DecodeFuture::poll`.
428            if let Some(result) = self.shared.result.borrow_mut().take() {
429                return Poll::Ready(result);
430            }
431        }
432        *self.shared.waker.borrow_mut() = Some(cx.waker().clone());
433        Poll::Pending
434    }
435}
436
437// ---------------------------------------------------------------------------
438// Completions (pumped from `Event::ImageDecoded` / `Event::ImageEncoded`)
439// ---------------------------------------------------------------------------
440
441/// Deliver a decode answer. Called from `pump_events`; a request already answered, cancelled, or
442/// never issued finds nothing and does nothing, the same contract presentation has.
443pub fn resolve_image_decode(req: u64, result: Result<BitmapInfo, ImageError>) {
444    let Some((id, entry)) = PENDING_DECODE.with(|p| p.borrow_mut().remove(&req)) else {
445        return;
446    };
447    // The future is gone (a browser decode outliving the task that asked): a success has nobody
448    // to own it, so it is released here rather than parked as a result no one will read.
449    if entry.callback.is_none() && entry.shared.cancelled.get() {
450        if result.is_ok() {
451            release(id);
452        }
453        return;
454    }
455    deliver(entry, result.map(|info| (id, info)));
456}
457
458/// Deliver an encode answer (see [`resolve_image_decode`]).
459pub fn resolve_image_encode(req: u64, result: Result<Vec<u8>, ImageError>) {
460    let Some(entry) = PENDING_ENCODE.with(|p| p.borrow_mut().remove(&req)) else {
461        return;
462    };
463    deliver(entry, result);
464}
465
466fn deliver<T, E>(entry: Waiting<T, E>, value: Result<T, E>) {
467    if let Some(cb) = entry.callback {
468        cb(value);
469        return;
470    }
471    *entry.shared.result.borrow_mut() = Some(value);
472    if let Some(waker) = entry.shared.waker.borrow_mut().take() {
473        waker.wake();
474    }
475}
476
477/// Resolve every pending request (tests, and `uninstall_tree`): the tree that would have answered
478/// is going away, so each waiter gets `Unsupported` (there is no backend left to ask) rather
479/// than staying parked forever. Queued releases go too: their toolkit is the one being torn down.
480pub(crate) fn reset() {
481    let decodes: Vec<_> =
482        PENDING_DECODE.with(|p| p.borrow_mut().drain().map(|(_, (_, e))| e).collect());
483    for entry in decodes {
484        deliver(entry, Err(ImageError::Unsupported));
485    }
486    let encodes: Vec<_> = PENDING_ENCODE.with(|p| p.borrow_mut().drain().map(|(_, e)| e).collect());
487    for entry in encodes {
488        deliver(entry, Err(ImageError::Unsupported));
489    }
490    let bitmaps: Vec<_> =
491        PENDING_BITMAP.with(|p| p.borrow_mut().drain().map(|(_, (_, e))| e).collect());
492    for entry in bitmaps {
493        deliver(entry, Err(ExportError::Unsupported));
494    }
495    let pdfs: Vec<_> = PENDING_PDF.with(|p| p.borrow_mut().drain().map(|(_, e)| e).collect());
496    for entry in pdfs {
497        deliver(entry, Err(ExportError::Unsupported));
498    }
499    DEFERRED_RELEASE.with(|q| q.borrow_mut().clear());
500    EXPORTS.with(|c| c.set(None));
501}
502
503// ---------------------------------------------------------------------------
504// Canvas export (docs/canvas.md "Exporting")
505// ---------------------------------------------------------------------------
506
507/// What this toolkit can export a canvas drawing to ([`Cap::CanvasBitmap`],
508/// [`Cap::CanvasPdf`]). Read it to enable or hide export commands, the way
509/// [`image_encode_formats`] decides which formats to offer.
510#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
511pub struct CanvasExports {
512    /// [`render_bitmap`] works here, and with it PNG export wherever [`Bitmap::encode`] writes
513    /// PNG (see [`CanvasExports::png`]).
514    pub bitmap: bool,
515    /// [`render_pdf`] works here: the platform has a native PDF writer.
516    pub pdf: bool,
517    png: bool,
518}
519
520impl CanvasExports {
521    /// Whether a drawing can become PNG bytes here: a rendered bitmap plus a PNG encoder.
522    #[must_use]
523    pub fn png(&self) -> bool {
524        self.png
525    }
526}
527
528/// What this toolkit can export a canvas drawing to.
529///
530/// Safe to call anywhere, including from a context menu that is built while the tree is busy
531/// summoning it: the answer is read once per installed tree and kept. Before a tree is
532/// installed, and in the rare case its first read lands inside a borrow, everything answers
533/// `false`.
534#[must_use]
535pub fn canvas_exports() -> CanvasExports {
536    if let Some(known) = EXPORTS.with(std::cell::Cell::get) {
537        return known;
538    }
539    let Some(read) = crate::with_tree_if_free(|t| {
540        let yes = |cap| t.capability(cap) != day_spec::Support::Unsupported;
541        let bitmap = yes(Cap::CanvasBitmap);
542        CanvasExports {
543            bitmap,
544            pdf: yes(Cap::CanvasPdf),
545            png: bitmap && t.image_encode_formats().contains(&ImageFormat::Png),
546        }
547    }) else {
548        return CanvasExports::default();
549    };
550    EXPORTS.with(|c| c.set(Some(read)));
551    read
552}
553
554/// `size` points at `scale` is something a toolkit can be asked to render: positive and
555/// finite, and within [`day_spec::EXPORT_MAX_SIDE`] / [`day_spec::EXPORT_MAX_PIXELS`].
556fn check_bitmap(size: Size, scale: f64) -> Result<(), ExportError> {
557    let positive = |v: f64| v.is_finite() && v > 0.0;
558    if !positive(size.width) || !positive(size.height) || !positive(scale) {
559        return Err(ExportError::Invalid);
560    }
561    let (width, height) = day_spec::export_pixels(size, scale);
562    if width > day_spec::EXPORT_MAX_SIDE
563        || height > day_spec::EXPORT_MAX_SIDE
564        || u64::from(width) * u64::from(height) > day_spec::EXPORT_MAX_PIXELS
565    {
566        return Err(ExportError::TooLarge { width, height });
567    }
568    Ok(())
569}
570
571fn check_pdf(pages: &[PdfPage]) -> Result<(), ExportError> {
572    let positive = |v: f64| v.is_finite() && v > 0.0;
573    if pages.is_empty()
574        || pages
575            .iter()
576            .any(|p| !positive(p.size.width) || !positive(p.size.height))
577    {
578        return Err(ExportError::Invalid);
579    }
580    Ok(())
581}
582
583/// The check every bitmap export runs before asking the toolkit: the cap, then the size.
584fn admit_bitmap(size: Size, scale: f64) -> Result<(), ExportError> {
585    if support(Cap::CanvasBitmap) == day_spec::Support::Unsupported {
586        return Err(ExportError::Unsupported);
587    }
588    check_bitmap(size, scale)
589}
590
591fn admit_pdf(pages: &[PdfPage]) -> Result<(), ExportError> {
592    if support(Cap::CanvasPdf) == day_spec::Support::Unsupported {
593        return Err(ExportError::Unsupported);
594    }
595    check_pdf(pages)
596}
597
598/// Replay `ops` into an offscreen bitmap of `size` points at `scale` pixels per point, through
599/// the toolkit's own canvas painter. Resolves with a [`Bitmap`] like a decode does, so
600/// `image(&bitmap)`, `Draw::image` and [`Bitmap::encode`] all take it. Apps reach this through
601/// `Drawing::to_bitmap`.
602#[must_use]
603pub fn render_bitmap(ops: Vec<DrawOp>, size: Size, scale: f64) -> RenderBitmap {
604    RenderBitmap {
605        job: Some((ops, size, scale)),
606        shared: Rc::new(Shared::default()),
607        started: false,
608    }
609}
610
611/// [`render_bitmap`]'s callback half (docs/async.md rule 3).
612#[expect(
613    clippy::needless_pass_by_value,
614    reason = "public signature, the callback twin of the future-returning function it mirrors"
615)]
616pub fn render_bitmap_async(
617    ops: Vec<DrawOp>,
618    size: Size,
619    scale: f64,
620    on_done: impl FnOnce(Result<Bitmap, ExportError>) + 'static,
621) {
622    if let Err(e) = admit_bitmap(size, scale) {
623        on_done(Err(e));
624        return;
625    }
626    start_bitmap(
627        &ops,
628        size,
629        scale,
630        None,
631        Some(Box::new(move |r| on_done(r.map(bitmap_from)))),
632    );
633}
634
635/// Replay each page into one PDF document through the platform's own PDF writer. Resolves with
636/// the document's bytes. Apps reach this through `Drawing::to_pdf` and `PdfDocument::render`.
637#[must_use]
638pub fn render_pdf(pages: Vec<PdfPage>, info: PdfInfo) -> RenderPdf {
639    RenderPdf {
640        job: Some((pages, info)),
641        shared: Rc::new(Shared::default()),
642        started: false,
643    }
644}
645
646/// [`render_pdf`]'s callback half (docs/async.md rule 3).
647#[expect(
648    clippy::needless_pass_by_value,
649    reason = "public signature, the callback twin of the future-returning function it mirrors"
650)]
651pub fn render_pdf_async(
652    pages: Vec<PdfPage>,
653    info: PdfInfo,
654    on_done: impl FnOnce(Result<Vec<u8>, ExportError>) + 'static,
655) {
656    if let Err(e) = admit_pdf(&pages) {
657        on_done(Err(e));
658        return;
659    }
660    start_pdf(&pages, &info, None, Some(Box::new(on_done)));
661}
662
663fn start_bitmap(
664    ops: &[DrawOp],
665    size: Size,
666    scale: f64,
667    shared: Option<Rc<Shared<(BitmapId, BitmapInfo), ExportError>>>,
668    callback: Option<ImageDone<(BitmapId, BitmapInfo), ExportError>>,
669) {
670    let req = next_req();
671    let id = next_bitmap();
672    PENDING_BITMAP.with(|p| {
673        p.borrow_mut().insert(
674            req,
675            (
676                id,
677                Waiting {
678                    shared: shared.unwrap_or_default(),
679                    callback,
680                },
681            ),
682        )
683    });
684    with_tree(|t| t.render_bitmap(req, id, ops, size, scale));
685}
686
687fn start_pdf(
688    pages: &[PdfPage],
689    info: &PdfInfo,
690    shared: Option<Rc<Shared<Vec<u8>, ExportError>>>,
691    callback: Option<ImageDone<Vec<u8>, ExportError>>,
692) {
693    let req = next_req();
694    PENDING_PDF.with(|p| {
695        p.borrow_mut().insert(
696            req,
697            Waiting {
698                shared: shared.unwrap_or_default(),
699                callback,
700            },
701        )
702    });
703    with_tree(|t| t.render_pdf(req, pages, info));
704}
705
706/// A bitmap render in flight. Resolves with the rendered [`Bitmap`], or why it could not be.
707/// Nothing is asked of the toolkit until the first poll.
708pub struct RenderBitmap {
709    job: Option<(Vec<DrawOp>, Size, f64)>,
710    shared: Rc<Shared<(BitmapId, BitmapInfo), ExportError>>,
711    started: bool,
712}
713
714impl Future for RenderBitmap {
715    type Output = Result<Bitmap, ExportError>;
716
717    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
718        if let Some(result) = self.shared.result.borrow_mut().take() {
719            return Poll::Ready(result.map(bitmap_from));
720        }
721        if !self.started {
722            self.started = true;
723            let Some((ops, size, scale)) = self.job.take() else {
724                return Poll::Ready(Err(ExportError::Invalid));
725            };
726            if let Err(e) = admit_bitmap(size, scale) {
727                return Poll::Ready(Err(e));
728            }
729            start_bitmap(&ops, size, scale, Some(self.shared.clone()), None);
730            // Answered inline everywhere but the browser; see `DecodeFuture::poll`.
731            if let Some(result) = self.shared.result.borrow_mut().take() {
732                return Poll::Ready(result.map(bitmap_from));
733            }
734        }
735        *self.shared.waker.borrow_mut() = Some(cx.waker().clone());
736        Poll::Pending
737    }
738}
739
740impl Drop for RenderBitmap {
741    fn drop(&mut self) {
742        // The same two cases as `DecodeFuture`: answered but never taken, or still in flight.
743        if let Some(Ok((id, _))) = self.shared.result.borrow_mut().take() {
744            release(id);
745        }
746        self.shared.cancelled.set(true);
747    }
748}
749
750/// A PDF render in flight. Resolves with the document's bytes, or why they could not be
751/// produced. Nothing is asked of the toolkit until the first poll.
752pub struct RenderPdf {
753    job: Option<(Vec<PdfPage>, PdfInfo)>,
754    shared: Rc<Shared<Vec<u8>, ExportError>>,
755    started: bool,
756}
757
758impl Future for RenderPdf {
759    type Output = Result<Vec<u8>, ExportError>;
760
761    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
762        if let Some(result) = self.shared.result.borrow_mut().take() {
763            return Poll::Ready(result);
764        }
765        if !self.started {
766            self.started = true;
767            let Some((pages, info)) = self.job.take() else {
768                return Poll::Ready(Err(ExportError::Invalid));
769            };
770            if let Err(e) = admit_pdf(&pages) {
771                return Poll::Ready(Err(e));
772            }
773            start_pdf(&pages, &info, Some(self.shared.clone()), None);
774            if let Some(result) = self.shared.result.borrow_mut().take() {
775                return Poll::Ready(result);
776            }
777        }
778        *self.shared.waker.borrow_mut() = Some(cx.waker().clone());
779        Poll::Pending
780    }
781}
782
783/// Deliver a bitmap render's answer (`Event::BitmapRendered`). The same contract as
784/// [`resolve_image_decode`], including releasing a success nobody is waiting for.
785pub fn resolve_bitmap_render(req: u64, result: Result<BitmapInfo, ExportError>) {
786    let Some((id, entry)) = PENDING_BITMAP.with(|p| p.borrow_mut().remove(&req)) else {
787        return;
788    };
789    if entry.callback.is_none() && entry.shared.cancelled.get() {
790        if result.is_ok() {
791            release(id);
792        }
793        return;
794    }
795    deliver(entry, result.map(|info| (id, info)));
796}
797
798/// Deliver a PDF render's answer (`Event::PdfRendered`).
799pub fn resolve_pdf_render(req: u64, result: Result<Vec<u8>, ExportError>) {
800    let Some(entry) = PENDING_PDF.with(|p| p.borrow_mut().remove(&req)) else {
801        return;
802    };
803    deliver(entry, result);
804}
805
806#[cfg(test)]
807mod export_tests {
808    use super::*;
809
810    #[test]
811    fn bitmap_sizes_are_checked_before_the_toolkit() {
812        let size = Size::new(100.0, 50.0);
813        assert_eq!(check_bitmap(size, 2.0), Ok(()));
814        assert_eq!(
815            check_bitmap(Size::new(0.0, 50.0), 1.0),
816            Err(ExportError::Invalid)
817        );
818        assert_eq!(check_bitmap(size, f64::NAN), Err(ExportError::Invalid));
819        assert_eq!(check_bitmap(size, -1.0), Err(ExportError::Invalid));
820        assert_eq!(
821            check_bitmap(Size::new(16_385.0, 1.0), 1.0),
822            Err(ExportError::TooLarge {
823                width: 16_385,
824                height: 1
825            })
826        );
827        // Each side fits, the total does not: 10,000 × 10,000 is 100 megapixels.
828        assert_eq!(
829            check_bitmap(Size::new(5_000.0, 5_000.0), 2.0),
830            Err(ExportError::TooLarge {
831                width: 10_000,
832                height: 10_000
833            })
834        );
835        // Partial pixels round up, so the limit counts the bitmap actually allocated.
836        assert_eq!(day_spec::export_pixels(Size::new(10.2, 3.0), 2.0), (21, 6));
837    }
838
839    #[test]
840    fn a_pdf_needs_pages_with_a_size() {
841        assert_eq!(check_pdf(&[]), Err(ExportError::Invalid));
842        let page = |w, h| PdfPage {
843            size: Size::new(w, h),
844            ops: Vec::new(),
845        };
846        assert_eq!(check_pdf(&[page(612.0, 792.0)]), Ok(()));
847        assert_eq!(
848            check_pdf(&[page(612.0, 792.0), page(0.0, 10.0)]),
849            Err(ExportError::Invalid)
850        );
851    }
852}
853
854#[cfg(test)]
855mod teardown_tests {
856    use super::*;
857
858    #[test]
859    fn bitmap_drop_during_reactive_tls_teardown() {
860        const CHILD: &str = "DAY_CORE_BITMAP_REACTIVE_TEARDOWN_CHILD";
861        if let Some(mode) = std::env::var_os(CHILD) {
862            struct TeardownBitmap {
863                bitmap: Option<Bitmap>,
864                dropped: std::sync::mpsc::Sender<()>,
865            }
866            impl Drop for TeardownBitmap {
867                fn drop(&mut self) {
868                    drop(self.bitmap.take());
869                    self.dropped.send(()).unwrap();
870                }
871            }
872            let (dropped, observed) = std::sync::mpsc::channel();
873            std::thread::spawn(move || {
874                // The reactive arena owns the last bitmap until its TLS destructor runs.
875                // Construct the handle directly so the first case never initializes core TLS.
876                day_reactive::Signal::global(TeardownBitmap {
877                    bitmap: Some(bitmap_from((BitmapId(1), BitmapInfo::default()))),
878                    dropped,
879                });
880                if mode == "initialized" {
881                    // On Windows GNU, core TLS can be initialized again after its destructor
882                    // finishes. This is the canvas mock_e2e crash's teardown ordering.
883                    assert!(crate::try_tls_root(|_| ()).is_ok());
884                }
885            })
886            .join()
887            .unwrap();
888            observed
889                .recv_timeout(std::time::Duration::from_secs(5))
890                .expect("bitmap was not dropped during reactive TLS teardown");
891            return;
892        }
893        // A TLS destructor panic aborts, so isolate both the never-initialized core and the
894        // already-destroyed core cases. Neither may initialize signals while releasing a bitmap.
895        for mode in ["uninitialized", "initialized"] {
896            let output = std::process::Command::new(std::env::current_exe().unwrap())
897                .args([
898                    "--exact",
899                    "image::teardown_tests::bitmap_drop_during_reactive_tls_teardown",
900                    "--nocapture",
901                ])
902                .env(CHILD, mode)
903                .output()
904                .unwrap();
905            assert!(
906                output.status.success(),
907                "{mode}: {}",
908                String::from_utf8_lossy(&output.stderr)
909            );
910        }
911    }
912
913    #[test]
914    fn bitmap_drop_during_core_tls_teardown() {
915        const CHILD: &str = "DAY_CORE_BITMAP_TEARDOWN_CHILD";
916        if std::env::var_os(CHILD).is_some() {
917            struct TeardownBitmap {
918                bitmap: Option<Bitmap>,
919                dropped: std::sync::mpsc::Sender<()>,
920            }
921            impl Drop for TeardownBitmap {
922                fn drop(&mut self) {
923                    // LocalKey access must fail while its own destructor runs. This does not
924                    // depend on the platform's ordering of unrelated TLS destructors.
925                    assert!(crate::try_tls_root(|_| ()).is_err());
926                    drop(self.bitmap.take());
927                    self.dropped.send(()).unwrap();
928                }
929            }
930            let (dropped, observed) = std::sync::mpsc::channel();
931            std::thread::spawn(move || {
932                let held = TeardownBitmap {
933                    bitmap: Some(bitmap_from((BitmapId(1), BitmapInfo::default()))),
934                    dropped,
935                };
936                // A pending callback owns the bitmap until the core TLS root is destroyed.
937                // The callback is never invoked: dropping the registry drops its captures.
938                PENDING_ENCODE.with(|pending| {
939                    pending.borrow_mut().insert(
940                        1,
941                        Pending {
942                            shared: Rc::new(Shared::default()),
943                            callback: Some(Box::new(move |_| drop(held))),
944                        },
945                    );
946                });
947                assert!(crate::try_tls_root(|_| ()).is_ok());
948            })
949            .join()
950            .unwrap();
951            // Prove the destructor actually exercised the release path, rather than allowing
952            // a platform that skipped TLS cleanup to pass silently.
953            observed
954                .recv_timeout(std::time::Duration::from_secs(5))
955                .expect("bitmap was not dropped during core TLS teardown");
956            return;
957        }
958        let output = std::process::Command::new(std::env::current_exe().unwrap())
959            .args([
960                "--exact",
961                "image::teardown_tests::bitmap_drop_during_core_tls_teardown",
962                "--nocapture",
963            ])
964            .env(CHILD, "1")
965            .output()
966            .unwrap();
967        assert!(
968            output.status.success(),
969            "{}",
970            String::from_utf8_lossy(&output.stderr)
971        );
972    }
973}