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