Skip to main content

gpui/fast/
dynamic_textures.rs

1// Modified by Longbridge for gpui-fast.
2//! Mutable BGRA8 textures for content that changes every frame.
3//!
4//! A texture allocated through [`crate::Window::create_dynamic_texture`] is
5//! owned by the platform renderer, not by the sprite atlas: it lives outside
6//! the atlas allocator, so repainting a frame into it never invalidates the
7//! glyphs and icons sharing the atlas. Callers paint the current contents
8//! with [`crate::Window::paint_dynamic_texture`] and refresh sub-regions with
9//! [`crate::Window::update_dynamic_texture`]; the upload goes straight into
10//! the existing GPU texture instead of rebuilding an image.
11//!
12//! Renderer crates can also register a GPU-written texture through
13//! [`DynamicTexture::new_gpu`], retaining its GPU memory on their own context.
14//! GPUI tracks only the size and content version; no GPU object enters the
15//! upload platform or the process-wide metadata table.
16//!
17//! CPU uploads use [`DynamicTexturePlatform`] and
18//! [`set_dynamic_texture_platform`]. Platforms without an upload backend
19//! report an error from `create_dynamic_texture`. GPU-written handles refuse
20//! CPU updates; their renderer records writes through
21//! [`crate::Window::refresh_dynamic_texture`].
22
23use anyhow::{Context as _, Result};
24use std::{
25    borrow::Cow,
26    collections::HashMap,
27    sync::{
28        Arc,
29        atomic::{AtomicBool, AtomicU32, Ordering},
30    },
31};
32
33use crate::fast::layers::scene::LAYER_TILE_TEXTURE_BASE;
34use crate::{
35    AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, DevicePixels, Pixels, PolychromeSprite,
36    TileId, Window, point,
37};
38
39/// Bytes per pixel of a dynamic texture: BGRA8, matching the scene's
40/// polychrome sprite format.
41const BYTES_PER_PIXEL: usize = 4;
42
43/// Atlas texture indices at or above this base belong to dynamic textures.
44///
45/// The sprite atlas numbers its textures from small, densely reused indices,
46/// and layer tiles reserve the range at [`LAYER_TILE_TEXTURE_BASE`], so a
47/// reserved range below that keeps the three id spaces disjoint without
48/// touching `AtlasTextureKind`, which is upstream's type.
49///
50/// [`LAYER_TILE_TEXTURE_BASE`]: crate::fast::layers::scene::LAYER_TILE_TEXTURE_BASE
51const DYNAMIC_INDEX_BASE: u32 = 0xE000_0000;
52
53/// How many dynamic texture ids the reserved atlas index range holds.
54const DYNAMIC_ID_LIMIT: u32 = LAYER_TILE_TEXTURE_BASE - DYNAMIC_INDEX_BASE;
55
56/// Identifies one dynamic texture for its lifetime.
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
58pub struct DynamicTextureId(u32);
59
60impl DynamicTextureId {
61    /// The atlas texture id a sprite of this dynamic texture carries. The
62    /// renderer resolves these ids through the dynamic texture backend before
63    /// it falls back to the sprite atlas.
64    pub fn atlas_texture_id(self) -> AtlasTextureId {
65        AtlasTextureId {
66            index: DYNAMIC_INDEX_BASE.wrapping_add(self.0),
67            kind: AtlasTextureKind::Polychrome,
68        }
69    }
70
71    /// The dynamic texture id behind an atlas texture id, if it is one.
72    pub fn from_atlas_texture_id(id: AtlasTextureId) -> Option<Self> {
73        (id.kind == AtlasTextureKind::Polychrome
74            && id.index >= DYNAMIC_INDEX_BASE
75            && id.index - DYNAMIC_INDEX_BASE < DYNAMIC_ID_LIMIT)
76            .then(|| Self(id.index - DYNAMIC_INDEX_BASE))
77    }
78}
79
80/// A copyable handle to a mutable texture, not an owner of its GPU memory.
81///
82/// Applications obtain uploaded textures from
83/// [`crate::Window::create_dynamic_texture`]. Renderer crates can register
84/// GPU-written textures with [`Self::new_gpu`] and own their GPU memory.
85/// Removing a texture retires every copy of its handle.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct DynamicTexture {
88    id: DynamicTextureId,
89    size: crate::Size<DevicePixels>,
90}
91
92impl DynamicTexture {
93    /// Identifies the texture in its renderer's lookup table.
94    /// This is not a GPU resource or an ownership token.
95    pub fn id(&self) -> DynamicTextureId {
96        self.id
97    }
98
99    /// Registers the size and version of a GPU-written texture.
100    ///
101    /// Renderer crates allocate and own its GPU memory on their own context.
102    /// Applications should use their renderer's constructor. This method never
103    /// selects or calls the process's upload platform.
104    pub fn new_gpu(size: crate::Size<DevicePixels>) -> Result<Self> {
105        anyhow::ensure!(
106            size.width.0 > 0 && size.height.0 > 0,
107            "dynamic texture dimensions must be positive"
108        );
109        allocate(size, TextureSource::Gpu, |_| Ok(()))
110    }
111
112    /// Releases the texture without requiring a live window, for example
113    /// when the producer is dropped. Other copies of the handle become stale.
114    /// Releasing an already removed texture has no effect.
115    /// Renderer owners must also release GPU memory held outside the upload
116    /// platform; this method retires only the metadata of GPU-written textures.
117    pub fn remove(self) {
118        remove(self);
119    }
120}
121
122/// The GPU side of dynamic textures, implemented by the platform crates that
123/// can upload into an existing texture.
124///
125/// Every method receives tightly packed BGRA8 rows — the caller repacks
126/// strided input, so the backend never sees row padding.
127pub trait DynamicTexturePlatform: Send + Sync {
128    /// Allocates a texture of `size` for `id` and uploads `bytes` into it.
129    fn create_texture(
130        &self,
131        id: DynamicTextureId,
132        size: crate::Size<DevicePixels>,
133        bytes: &[u8],
134    ) -> Result<()>;
135
136    /// Uploads `bytes` for `bounds` — relative to the texture's own origin —
137    /// into the texture allocated for `id`.
138    ///
139    /// May fail while the platform still holds earlier staged uploads, for
140    /// example when the window has not drawn to drain them. A refused
141    /// upload leaves the texture's previous contents in place.
142    fn update_texture(
143        &self,
144        id: DynamicTextureId,
145        bounds: Bounds<DevicePixels>,
146        bytes: &[u8],
147    ) -> Result<()>;
148
149    /// Releases the texture allocated for `id`.
150    fn remove_texture(&self, id: DynamicTextureId);
151}
152
153static PLATFORM: parking_lot::RwLock<Option<Arc<dyn DynamicTexturePlatform>>> =
154    parking_lot::RwLock::new(None);
155
156/// Installs the platform backend for dynamic textures.
157///
158/// Called once by the platform's renderer while it is coming up. The first
159/// backend wins: every renderer in the process selects the same Metal device,
160/// and textures must stay on the device that draws them.
161pub fn set_dynamic_texture_platform(backend: Arc<dyn DynamicTexturePlatform>) {
162    let mut platform = PLATFORM.write();
163    if platform.is_none() {
164        *platform = Some(backend);
165    }
166}
167
168fn platform() -> Result<Arc<dyn DynamicTexturePlatform>> {
169    require_platform(PLATFORM.read().clone())
170}
171
172/// The backend to use, or the error that says why there is none.
173///
174/// Split out of [`platform`] so the missing-backend branch can be tested:
175/// the global is installed once per process, and a test binary that has
176/// already installed a mock can never see it empty again.
177fn require_platform(
178    platform: Option<Arc<dyn DynamicTexturePlatform>>,
179) -> Result<Arc<dyn DynamicTexturePlatform>> {
180    platform.context("dynamic textures are not supported on this platform")
181}
182
183static NEXT_TEXTURE_ID: AtomicU32 = AtomicU32::new(0);
184
185/// Set the first time the id counter passes the reserved atlas range. The
186/// counter is not allowed to wrap: past `u32::MAX` it would count back into
187/// ids a live texture may still hold, so once the range runs out no further
188/// id is granted for the life of the process.
189static IDS_EXHAUSTED: AtomicBool = AtomicBool::new(false);
190
191/// The live dynamic textures, so update and paint can validate their
192/// arguments against the size the texture was created with.
193static LIVE_TEXTURES: parking_lot::Mutex<Option<HashMap<DynamicTextureId, TextureState>>> =
194    parking_lot::Mutex::new(None);
195
196/// A live texture's created size and its content version.
197#[derive(Clone, Copy)]
198struct TextureState {
199    size: crate::Size<DevicePixels>,
200    source: TextureSource,
201    /// Bumped on every sub-region update. Painted sprites carry it in
202    /// [`PolychromeSprite::pad`], which the scroll-layer tile hashes cover,
203    /// so tiles showing refreshed contents are re-rendered instead of
204    /// kept from the cache.
205    version: u32,
206}
207
208#[derive(Clone, Copy, PartialEq, Eq)]
209enum TextureSource {
210    Upload,
211    Gpu,
212}
213
214fn live_textures() -> parking_lot::MappedMutexGuard<'static, HashMap<DynamicTextureId, TextureState>>
215{
216    parking_lot::MutexGuard::map(LIVE_TEXTURES.lock(), |textures| {
217        textures.get_or_insert_with(HashMap::new)
218    })
219}
220
221/// The version a sprite painted now must carry: a changing texture version,
222/// so a cached frame holding a sprite of a refreshed texture is told apart
223/// from the new one.
224fn painted_version(id: DynamicTextureId) -> u32 {
225    live_textures()
226        .get(&id)
227        .map_or(1, |state| state.version.max(1))
228}
229
230/// Allocates a mutable BGRA8 texture.
231///
232/// `bytes` holds the initial contents in `bytes_per_row`-strided rows; padded
233/// multi-row inputs are repacked into tight rows before the upload, while
234/// tightly packed inputs are borrowed in place. The payload must hold every
235/// row's visible bytes; padding on the final row — what a native framebuffer
236/// allocation naturally has — is fine, and anything past the rows the
237/// texture needs is ignored.
238pub(crate) fn create(
239    size: crate::Size<DevicePixels>,
240    bytes: &[u8],
241    bytes_per_row: u32,
242) -> Result<DynamicTexture> {
243    let width = usize::try_from(size.width.0).context("negative texture width")?;
244    let height = usize::try_from(size.height.0).context("negative texture height")?;
245    anyhow::ensure!(
246        width > 0 && height > 0,
247        "dynamic texture dimensions must be positive"
248    );
249
250    let row_bytes = width
251        .checked_mul(BYTES_PER_PIXEL)
252        .context("dynamic texture row size overflow")?;
253    let stride = usize::try_from(bytes_per_row).context("negative bytes per row")?;
254    anyhow::ensure!(
255        stride >= row_bytes,
256        "dynamic texture stride is smaller than one row"
257    );
258
259    let required = checked_payload_len(height, stride, row_bytes)?;
260    anyhow::ensure!(
261        bytes.len() >= required,
262        "dynamic texture payload is shorter than its dimensions"
263    );
264
265    let packed = pack_rows(bytes, stride, row_bytes, height);
266    let backend = platform()?;
267    allocate(size, TextureSource::Upload, |id| {
268        backend.create_texture(id, size, &packed)
269    })
270}
271
272/// Grants a texture id, has the backend allocate the texture under it with
273/// `create`, and tracks it as live.
274fn allocate(
275    size: crate::Size<DevicePixels>,
276    source: TextureSource,
277    create: impl FnOnce(DynamicTextureId) -> Result<()>,
278) -> Result<DynamicTexture> {
279    let id = DynamicTextureId(NEXT_TEXTURE_ID.fetch_add(1, Ordering::Relaxed));
280    // Ids count up for the life of the process into the reserved atlas
281    // range, so an id past the range would name a layer tile's texture.
282    // Refuse — and keep refusing for good: the counter would eventually
283    // wrap around and hand out an id a live texture already holds.
284    if IDS_EXHAUSTED.load(Ordering::Relaxed) || id.0 >= DYNAMIC_ID_LIMIT {
285        IDS_EXHAUSTED.store(true, Ordering::Relaxed);
286        anyhow::bail!("dynamic texture ids are exhausted");
287    }
288    create(id).with_context(|| format!("failed to create dynamic texture {id:?}"))?;
289    live_textures().insert(
290        id,
291        TextureState {
292            size,
293            source,
294            version: 1,
295        },
296    );
297
298    Ok(DynamicTexture { id, size })
299}
300
301/// Uploads a BGRA8 sub-region into a mutable texture.
302///
303/// The region is relative to the texture's own origin and must lie inside it,
304/// so a stale texture size cannot scribble over other content. Padded rows are
305/// repacked before the upload while tight rows are borrowed in place, and the
306/// texture's version advances so cached
307/// frames learn about the new contents.
308pub(crate) fn update(
309    texture: DynamicTexture,
310    bounds: Bounds<DevicePixels>,
311    bytes: &[u8],
312    bytes_per_row: u32,
313) -> Result<()> {
314    let state = live_textures()
315        .get(&texture.id)
316        .copied()
317        .context("unknown dynamic texture")?;
318    anyhow::ensure!(
319        state.source == TextureSource::Upload,
320        "GPU-written textures must be updated by their producer"
321    );
322    let packed = validate_region(state.size, bounds, bytes, bytes_per_row)?;
323
324    platform()?
325        .update_texture(texture.id, bounds, &packed)
326        .with_context(|| format!("failed to update dynamic texture {texture:?}"))?;
327    if let Some(state) = live_textures().get_mut(&texture.id) {
328        state.version = state.version.wrapping_add(1).max(1);
329    }
330
331    Ok(())
332}
333
334/// Records that a GPU producer wrote new contents into `texture`: the version
335/// the next paint carries advances, as an update's does.
336pub(crate) fn mark_written(texture: DynamicTexture) -> Result<()> {
337    let mut textures = live_textures();
338    let state = textures
339        .get_mut(&texture.id)
340        .context("unknown dynamic texture")?;
341    state.version = state.version.wrapping_add(1).max(1);
342    Ok(())
343}
344
345/// Paints the current contents of a mutable texture into the scene.
346///
347/// This should only be called as part of the paint phase of element drawing.
348pub(crate) fn paint(
349    window: &mut Window,
350    bounds: Bounds<Pixels>,
351    texture: DynamicTexture,
352) -> Result<()> {
353    window.invalidator.debug_assert_paint();
354
355    let texture_size = live_size(texture.id)?;
356
357    // Every consumer resolves a sprite of this texture through its atlas
358    // texture id — the dynamic range the renderer checks first — and never
359    // looks the tile up by id in the atlas, so the tile id here only needs
360    // to be stable within the scene; it must never be used to reach the
361    // sprite atlas.
362    let tile = AtlasTile {
363        texture_id: texture.id.atlas_texture_id(),
364        tile_id: TileId(texture.id.0),
365        padding: 0,
366        bounds: Bounds {
367            origin: point(DevicePixels(0), DevicePixels(0)),
368            size: texture_size,
369        },
370    };
371    window.next_frame.scene.insert_primitive(PolychromeSprite {
372        order: 0,
373        pad: painted_version(texture.id),
374        grayscale: false.into(),
375        bounds: window.snap_bounds(bounds),
376        content_mask: window.snapped_content_mask(),
377        corner_radii: Default::default(),
378        tile,
379        opacity: window.element_opacity(),
380    });
381
382    Ok(())
383}
384
385/// Releases a mutable texture and its GPU memory.
386pub(crate) fn remove(texture: DynamicTexture) {
387    let state = live_textures().remove(&texture.id);
388    if state.is_some_and(|state| state.source == TextureSource::Upload)
389        && let Ok(backend) = platform()
390    {
391        backend.remove_texture(texture.id);
392    }
393}
394
395impl Window {
396    /// Allocates a mutable BGRA8 texture for content that changes every
397    /// frame, such as a stream of video or remote desktop frames.
398    ///
399    /// `bytes_per_row` may include padding past the visible width, which is
400    /// what surfaces backed by a native framebuffer hand over. The texture
401    /// lives outside the sprite atlas, so refreshing it never reallocates the
402    /// tiles glyphs and icons share. Subsequent sub-region writes go through
403    /// [`Window::update_dynamic_texture`]; platforms without a dynamic
404    /// texture backend report an error here.
405    pub fn create_dynamic_texture(
406        &mut self,
407        size: crate::Size<DevicePixels>,
408        bytes: &[u8],
409        bytes_per_row: u32,
410    ) -> Result<DynamicTexture> {
411        create(size, bytes, bytes_per_row)
412    }
413
414    /// Uploads a BGRA8 sub-region into a mutable texture.
415    ///
416    /// The region is relative to the texture's own origin and must lie inside
417    /// it; both requirements are checked, so a stale texture size cannot
418    /// scribble over other content. The platform may also refuse the update
419    /// while it still holds earlier staged uploads — a window that has not
420    /// drawn to drain them — in which case the error is returned, the
421    /// texture keeps its previous contents, and the version the next paint
422    /// carries does not advance.
423    ///
424    /// Called outside a frame, this marks the window for a full redraw, so
425    /// cached content showing the texture — a retained view that would draw
426    /// nothing again, or a scroll-layer tile — re-renders with the new
427    /// contents even though no element state changed. Called while a frame is
428    /// drawing, the upload lands on the next frame and the window is not
429    /// marked: painting cannot schedule a redraw, so an element that streams
430    /// from its own paint should ask the window to draw again itself.
431    pub fn update_dynamic_texture(
432        &mut self,
433        texture: DynamicTexture,
434        bounds: Bounds<DevicePixels>,
435        bytes: &[u8],
436        bytes_per_row: u32,
437    ) -> Result<()> {
438        update(texture, bounds, bytes, bytes_per_row)?;
439        self.refresh();
440        Ok(())
441    }
442
443    /// Records that a GPU producer wrote new contents into `texture`.
444    ///
445    /// Like [`Window::update_dynamic_texture`], this advances the version the
446    /// next paint carries and, called outside a frame, marks the window for a
447    /// full redraw, so cached views and scroll-layer tiles showing the
448    /// texture render again. A removed texture is refused.
449    pub fn refresh_dynamic_texture(&mut self, texture: DynamicTexture) -> Result<()> {
450        mark_written(texture)?;
451        self.refresh();
452        Ok(())
453    }
454
455    /// Paints the current contents of a mutable texture into the scene.
456    ///
457    /// This method should only be called as part of the paint phase of
458    /// element drawing.
459    pub fn paint_dynamic_texture(
460        &mut self,
461        bounds: Bounds<Pixels>,
462        texture: DynamicTexture,
463    ) -> Result<()> {
464        paint(self, bounds, texture)
465    }
466
467    /// Releases a mutable texture and its GPU memory.
468    pub fn remove_dynamic_texture(&mut self, texture: DynamicTexture) {
469        remove(texture);
470    }
471}
472
473/// The size a live dynamic texture was created with.
474fn live_size(id: DynamicTextureId) -> Result<crate::Size<DevicePixels>> {
475    live_textures()
476        .get(&id)
477        .map(|state| state.size)
478        .context("unknown dynamic texture")
479}
480
481/// Validates a sub-region against the texture's size and returns its rows
482/// tightly packed.
483fn validate_region<'a>(
484    texture_size: crate::Size<DevicePixels>,
485    bounds: Bounds<DevicePixels>,
486    bytes: &'a [u8],
487    bytes_per_row: u32,
488) -> Result<Cow<'a, [u8]>> {
489    // i64 arithmetic: the caller's bounds are untrusted, and the i32 sums of
490    // origin and size must not wrap before they are compared.
491    let (origin_x, origin_y) = (bounds.origin.x.0 as i64, bounds.origin.y.0 as i64);
492    let (width, height) = (bounds.size.width.0 as i64, bounds.size.height.0 as i64);
493    anyhow::ensure!(
494        origin_x >= 0
495            && origin_y >= 0
496            && width > 0
497            && height > 0
498            && origin_x + width <= texture_size.width.0 as i64
499            && origin_y + height <= texture_size.height.0 as i64,
500        "dynamic texture update is outside the texture"
501    );
502
503    // Positive and bounded by the texture's i32 size, so the usize casts
504    // cannot truncate or go negative.
505    let (width, height) = (width as usize, height as usize);
506    let row_bytes = width
507        .checked_mul(BYTES_PER_PIXEL)
508        .context("dynamic texture region row size overflow")?;
509    let stride = usize::try_from(bytes_per_row).context("negative bytes per row")?;
510    anyhow::ensure!(
511        stride >= row_bytes,
512        "dynamic texture stride is smaller than one row"
513    );
514
515    let required = checked_payload_len(height, stride, row_bytes)?;
516    anyhow::ensure!(
517        bytes.len() >= required,
518        "dynamic texture update is shorter than the region"
519    );
520
521    Ok(pack_rows(bytes, stride, row_bytes, height))
522}
523
524/// The exact byte length a `height`-row payload needs with `stride` bytes per
525/// row and `row_bytes` visible per row.
526fn checked_payload_len(height: usize, stride: usize, row_bytes: usize) -> Result<usize> {
527    (height - 1)
528        .checked_mul(stride)
529        .and_then(|length| length.checked_add(row_bytes))
530        .context("dynamic texture payload size overflow")
531}
532
533/// Borrows already-tight rows in place, or repacks padded multi-row inputs
534/// into tightly packed rows.
535fn pack_rows(bytes: &[u8], stride: usize, row_bytes: usize, height: usize) -> Cow<'_, [u8]> {
536    if stride == row_bytes || height <= 1 {
537        return Cow::Borrowed(&bytes[..row_bytes * height]);
538    }
539    let mut packed = Vec::with_capacity(row_bytes * height);
540    for row in 0..height {
541        let start = row * stride;
542        packed.extend_from_slice(&bytes[start..start + row_bytes]);
543    }
544    Cow::Owned(packed)
545}
546
547#[cfg(test)]
548mod tests {
549    use super::{
550        BYTES_PER_PIXEL, DYNAMIC_INDEX_BASE, DynamicTexture, DynamicTextureId,
551        DynamicTexturePlatform, create, live_size, mark_written, pack_rows, painted_version,
552        remove, set_dynamic_texture_platform, update, validate_region,
553    };
554    use crate::{
555        AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, ContentMask, DevicePixels,
556        PolychromeSprite, ScaledPixels, Scene, TileId, point, size,
557    };
558    use anyhow::Result;
559    use std::{
560        borrow::Cow,
561        sync::{
562            Arc,
563            atomic::{AtomicBool, AtomicUsize, Ordering},
564        },
565    };
566
567    /// Records the platform calls a test makes, standing in for a GPU.
568    ///
569    /// The backend global is process-wide and installed once, so every test
570    /// shares this one instance and resets the call records it cares about.
571    struct MockPlatform {
572        created: parking_lot::Mutex<Vec<(DynamicTextureId, crate::Size<DevicePixels>, usize)>>,
573        updated: parking_lot::Mutex<Vec<(DynamicTextureId, Bounds<DevicePixels>, usize)>>,
574        removed: parking_lot::Mutex<Vec<DynamicTextureId>>,
575        last_bytes_ptr: AtomicUsize,
576        fail_updates: AtomicBool,
577    }
578
579    impl DynamicTexturePlatform for MockPlatform {
580        fn create_texture(
581            &self,
582            id: DynamicTextureId,
583            size: crate::Size<DevicePixels>,
584            bytes: &[u8],
585        ) -> Result<()> {
586            self.last_bytes_ptr
587                .store(bytes.as_ptr() as usize, Ordering::SeqCst);
588            self.created.lock().push((id, size, bytes.len()));
589            Ok(())
590        }
591
592        fn update_texture(
593            &self,
594            id: DynamicTextureId,
595            bounds: Bounds<DevicePixels>,
596            bytes: &[u8],
597        ) -> Result<()> {
598            if self.fail_updates.load(Ordering::SeqCst) {
599                anyhow::bail!("backend refused the update");
600            }
601            self.last_bytes_ptr
602                .store(bytes.as_ptr() as usize, Ordering::SeqCst);
603            self.updated.lock().push((id, bounds, bytes.len()));
604            Ok(())
605        }
606
607        fn remove_texture(&self, id: DynamicTextureId) {
608            self.removed.lock().push(id);
609        }
610    }
611
612    /// Serializes the tests that share the process-wide backend.
613    static MOCK_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
614
615    /// The process-wide mock backend, installed on first use.
616    fn shared_mock() -> &'static Arc<MockPlatform> {
617        static MOCK: std::sync::OnceLock<Arc<MockPlatform>> = std::sync::OnceLock::new();
618        MOCK.get_or_init(|| {
619            let mock = Arc::new(MockPlatform {
620                created: parking_lot::Mutex::new(Vec::new()),
621                updated: parking_lot::Mutex::new(Vec::new()),
622                removed: parking_lot::Mutex::new(Vec::new()),
623                last_bytes_ptr: AtomicUsize::new(0),
624                fail_updates: AtomicBool::new(false),
625            });
626            set_dynamic_texture_platform(mock.clone());
627            mock
628        })
629    }
630
631    /// Takes the test lock and resets the mock's records and flags.
632    fn fresh_mock() -> (parking_lot::MutexGuard<'static, ()>, Arc<MockPlatform>) {
633        let lock = MOCK_LOCK.lock();
634        let mock = shared_mock();
635        mock.created.lock().clear();
636        mock.updated.lock().clear();
637        mock.removed.lock().clear();
638        mock.last_bytes_ptr.store(0, Ordering::SeqCst);
639        mock.fail_updates.store(false, Ordering::SeqCst);
640        (lock, mock.clone())
641    }
642
643    fn size_of(width: i32, height: i32) -> crate::Size<DevicePixels> {
644        size(DevicePixels(width), DevicePixels(height))
645    }
646
647    fn bounds_at(origin: (i32, i32), width: i32, height: i32) -> Bounds<DevicePixels> {
648        Bounds {
649            origin: point(DevicePixels(origin.0), DevicePixels(origin.1)),
650            size: size(DevicePixels(width), DevicePixels(height)),
651        }
652    }
653
654    /// Enough zeroed bytes for a tightly packed texture of `width x height`.
655    fn packed_bytes(width: i32, height: i32) -> Vec<u8> {
656        vec![0u8; width as usize * height as usize * BYTES_PER_PIXEL]
657    }
658
659    #[test]
660    fn create_reports_missing_platform() {
661        // The backend global is installed once per process, so it cannot be
662        // observed empty from a test binary that already installed a mock.
663        // Assert the branch directly instead of skipping when a mock is up.
664        let error = super::require_platform(None)
665            .err()
666            .expect("a missing backend is an error");
667        assert_eq!(
668            error.to_string(),
669            "dynamic textures are not supported on this platform"
670        );
671    }
672
673    #[test]
674    fn create_requires_every_row_and_ignores_trailing_bytes() {
675        let (_lock, mock) = fresh_mock();
676
677        let short = create(size_of(4, 4), &packed_bytes(4, 4)[..63], 16);
678        assert!(short.is_err(), "one byte short must be refused");
679
680        // A native framebuffer allocation pads the final row too: a 4x4
681        // BGRA surface with a 16-byte stride is 64 bytes, not 60.
682        let _padded = create(size_of(4, 4), &[0u8; 4 * 16], 16).expect("created");
683        {
684            let created = mock.created.lock();
685            assert_eq!(created.last().expect("created").2, 4 * 4 * BYTES_PER_PIXEL);
686        }
687
688        let empty = create(size_of(4, 4), &[], 16);
689        assert!(empty.is_err());
690
691        let zero = create(size_of(0, 4), &[], 0);
692        assert!(zero.is_err(), "zero width must be refused");
693    }
694
695    #[test]
696    fn create_rejects_a_stride_smaller_than_a_row() {
697        let (_lock, _mock) = fresh_mock();
698
699        let result = create(
700            size_of(4, 4),
701            &packed_bytes(4, 4),
702            3 * BYTES_PER_PIXEL as u32,
703        );
704        assert!(result.is_err());
705    }
706
707    #[test]
708    fn create_packs_rows_and_allocates_distinct_ids() {
709        let (_lock, mock) = fresh_mock();
710
711        // Two bytes of padding per row that the backend must not receive.
712        // The payload is one strided row plus the final row's visible bytes
713        // only — a 4x2 texture.
714        let stride = (4 * BYTES_PER_PIXEL + 2) as u32;
715        let mut strided = vec![0u8; stride as usize + 4 * BYTES_PER_PIXEL];
716        for byte in strided.iter_mut().step_by(stride as usize) {
717            *byte = 0xFF;
718        }
719
720        let texture = create(size_of(4, 2), &strided, stride).expect("created");
721        {
722            let created = mock.created.lock();
723            let (created_id, created_size, packed_len) =
724                created.last().expect("create reached the platform");
725            assert_eq!(*created_id, texture.id);
726            assert_eq!(*created_size, texture.size);
727            assert_eq!(
728                *packed_len,
729                4 * 2 * BYTES_PER_PIXEL,
730                "rows must arrive tightly packed"
731            );
732        }
733
734        // The second create runs with the records released: the mock's
735        // mutexes are not reentrant.
736        let other = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created again");
737        assert_ne!(texture.id, other.id, "ids must not repeat");
738    }
739
740    #[test]
741    fn update_validates_the_region_against_the_created_size() {
742        let (_lock, mock) = fresh_mock();
743
744        let texture_size = size_of(8, 8);
745        let texture = create(texture_size, &packed_bytes(8, 8), 32).expect("created");
746
747        let inside = bounds_at((0, 0), 4, 4);
748        let inside_bytes = packed_bytes(4, 4);
749        let packed = validate_region(texture_size, inside, &inside_bytes, 16)
750            .expect("a region inside the texture is accepted");
751        assert_eq!(packed.len(), 4 * 4 * BYTES_PER_PIXEL);
752
753        let offset = bounds_at((4, 4), 4, 4);
754        assert!(validate_region(texture_size, offset, &packed_bytes(4, 4), 16).is_ok());
755
756        let too_wide = bounds_at((0, 0), 9, 4);
757        assert!(
758            validate_region(texture_size, too_wide, &packed_bytes(9, 4), 36).is_err(),
759            "a region past the texture must be refused"
760        );
761
762        let negative = bounds_at((-1, 0), 4, 4);
763        assert!(validate_region(texture_size, negative, &packed_bytes(4, 4), 16).is_err());
764
765        let empty = bounds_at((0, 0), 0, 4);
766        assert!(validate_region(texture_size, empty, &[], 0).is_err());
767
768        let unknown = DynamicTexture {
769            id: DynamicTextureId(u32::MAX),
770            size: texture_size,
771        };
772        assert!(
773            live_size(unknown.id).is_err(),
774            "an unknown id must be refused"
775        );
776
777        remove(texture);
778        assert!(
779            live_size(texture.id).is_err(),
780            "a removed texture must be refused"
781        );
782        assert_eq!(mock.created.lock().len(), 1);
783        assert_eq!(mock.updated.lock().len(), 0);
784        assert_eq!(mock.removed.lock().len(), 1);
785    }
786
787    #[test]
788    fn update_requires_a_full_final_row() {
789        let (_lock, _mock) = fresh_mock();
790
791        let texture_size = size_of(8, 8);
792        let bounds = bounds_at((0, 0), 4, 4);
793        let row_bytes = 4 * BYTES_PER_PIXEL;
794
795        let short_by_one = &packed_bytes(4, 4)[..4 * row_bytes - 1];
796        assert!(
797            validate_region(texture_size, bounds, short_by_one, row_bytes as u32).is_err(),
798            "a final row missing bytes must be refused"
799        );
800    }
801
802    #[test]
803    fn remove_releases_the_texture_once() {
804        let (_lock, mock) = fresh_mock();
805
806        let texture = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
807        remove(texture);
808        remove(texture);
809
810        assert_eq!(
811            mock.removed.lock().len(),
812            1,
813            "the platform sees one removal"
814        );
815    }
816
817    #[test]
818    fn a_failing_backend_leaves_no_stale_state() {
819        let (_lock, mock) = fresh_mock();
820        mock.fail_updates.store(true, Ordering::SeqCst);
821
822        let texture = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
823        let version = painted_version(texture.id);
824        let result = update(texture, bounds_at((0, 0), 2, 2), &packed_bytes(2, 2), 8);
825        assert!(result.is_err(), "the backend's error must propagate");
826        assert!(
827            live_size(texture.id).is_ok(),
828            "the texture stays live for the next attempt"
829        );
830        assert_eq!(
831            painted_version(texture.id),
832            version,
833            "a refused update must not advance the version the next paint carries"
834        );
835    }
836
837    #[test]
838    fn atlas_ids_stay_out_of_the_atlas_range() {
839        let id = DynamicTextureId(0);
840        let atlas_id = id.atlas_texture_id();
841        assert_eq!(
842            DynamicTextureId::from_atlas_texture_id(atlas_id),
843            Some(id),
844            "the mapping must round-trip"
845        );
846
847        let atlas_id = AtlasTextureId {
848            index: 7,
849            kind: AtlasTextureKind::Polychrome,
850        };
851        assert_eq!(DynamicTextureId::from_atlas_texture_id(atlas_id), None);
852
853        let atlas_id = AtlasTextureId {
854            index: DYNAMIC_INDEX_BASE,
855            kind: AtlasTextureKind::Monochrome,
856        };
857        assert_eq!(
858            DynamicTextureId::from_atlas_texture_id(atlas_id),
859            None,
860            "a dynamic range index in another kind must not match"
861        );
862    }
863
864    /// A scene holding the texture painted over `region`'s tiles, the way
865    /// [`paint`] would build it: the version the texture carries at paint
866    /// time rides in the sprite's pad.
867    fn scene_with_texture(texture: DynamicTexture, pad: u32) -> Scene {
868        let mut scene = Scene::default();
869        scene.insert_primitive(PolychromeSprite {
870            order: 0,
871            pad,
872            tile: AtlasTile {
873                texture_id: texture.id.atlas_texture_id(),
874                tile_id: TileId(texture.id.0),
875                padding: 0,
876                bounds: Bounds {
877                    origin: point(DevicePixels(0), DevicePixels(0)),
878                    size: texture.size,
879                },
880            },
881            grayscale: false.into(),
882            opacity: 1.,
883            bounds: Bounds {
884                origin: point(ScaledPixels(0.), ScaledPixels(0.)),
885                size: size(ScaledPixels(64.), ScaledPixels(64.)),
886            },
887            content_mask: ContentMask {
888                bounds: Bounds {
889                    origin: point(ScaledPixels(0.), ScaledPixels(0.)),
890                    size: size(ScaledPixels(128.), ScaledPixels(128.)),
891                },
892            },
893            corner_radii: Default::default(),
894        });
895        scene
896    }
897
898    #[test]
899    fn repainting_an_updated_texture_dirties_its_tiles() {
900        let (_lock, _mock) = fresh_mock();
901
902        let texture = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
903        let region = Bounds {
904            origin: point(ScaledPixels(0.), ScaledPixels(0.)),
905            size: size(ScaledPixels(128.), ScaledPixels(128.)),
906        };
907
908        let before = crate::fast::layers::tiles::tile_hashes(
909            &scene_with_texture(texture, painted_version(texture.id)),
910            64,
911            region,
912        );
913
914        // An in-place update at unchanged sprite bounds changes no hashed
915        // field of the sprite but the version the next paint carries.
916        update(texture, bounds_at((0, 0), 2, 2), &packed_bytes(2, 2), 8).expect("updated");
917
918        let after = crate::fast::layers::tiles::tile_hashes(
919            &scene_with_texture(texture, painted_version(texture.id)),
920            64,
921            region,
922        );
923        assert_ne!(before, after, "tiles showing the texture must be dirtied");
924
925        // A texture that was never updated repaints with the same hash, so
926        // its tiles are still kept.
927        let other = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
928        let unchanged = crate::fast::layers::tiles::tile_hashes(
929            &scene_with_texture(other, painted_version(other.id)),
930            64,
931            region,
932        );
933        assert_eq!(
934            crate::fast::layers::tiles::tile_hashes(
935                &scene_with_texture(other, painted_version(other.id)),
936                64,
937                region,
938            ),
939            unchanged,
940        );
941    }
942
943    #[test]
944    fn gpu_metadata_never_calls_the_upload_platform() {
945        let (_lock, mock) = fresh_mock();
946        assert!(DynamicTexture::new_gpu(size_of(0, 4)).is_err());
947        let texture = DynamicTexture::new_gpu(size_of(4, 4)).expect("GPU metadata");
948        assert!(mock.created.lock().is_empty());
949        let version = painted_version(texture.id);
950        mark_written(texture).expect("recorded GPU write");
951        assert_ne!(painted_version(texture.id), version);
952        assert!(update(texture, bounds_at((0, 0), 4, 4), &packed_bytes(4, 4), 16).is_err());
953        texture.remove();
954        assert!(mock.updated.lock().is_empty());
955        assert!(mock.removed.lock().is_empty());
956        assert!(mark_written(texture).is_err());
957    }
958
959    #[test]
960    fn tight_and_single_row_uploads_borrow_caller_slice_without_repacking() {
961        let (_lock, mock) = fresh_mock();
962
963        // Tightly packed multi-row buffer (plus trailing slack) borrows in place.
964        let mut tight = vec![0xAB; 4 * 4 * BYTES_PER_PIXEL + 12];
965        tight[0] = 0x11;
966        let texture = create(size_of(4, 4), &tight, 16).expect("created");
967        assert_eq!(
968            mock.last_bytes_ptr.load(Ordering::SeqCst),
969            tight.as_ptr() as usize,
970            "tightly packed create must forward the caller slice without copying"
971        );
972        assert_eq!(
973            mock.created.lock().last().unwrap().2,
974            4 * 4 * BYTES_PER_PIXEL
975        );
976
977        // Single-row upload with row padding also borrows the visible prefix.
978        let single_row_padded = [0xCDu8; 24];
979        update(texture, bounds_at((0, 0), 4, 1), &single_row_padded, 24).expect("updated");
980        assert_eq!(
981            mock.last_bytes_ptr.load(Ordering::SeqCst),
982            single_row_padded.as_ptr() as usize,
983            "single-row update must borrow the visible prefix without copying"
984        );
985        assert_eq!(mock.updated.lock().last().unwrap().2, 4 * BYTES_PER_PIXEL);
986
987        // Multi-row padded input still repacks into an owned tight buffer.
988        let strided = [1, 2, 3, 4, 0xEE, 0xEE, 5, 6, 7, 8];
989        let repacked = pack_rows(&strided, 6, 4, 2);
990        assert!(matches!(repacked, Cow::Owned(_)));
991        assert_eq!(&*repacked, &[1, 2, 3, 4, 5, 6, 7, 8]);
992
993        remove(texture);
994    }
995}