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