guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use std::sync::Arc;

use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use wgpu::{Device, Instance, Queue, Surface, SurfaceConfiguration};

/// How long a device outlives the last surface. Long enough that a dialog
/// closed and opened again straight away finds it still there, rather than
/// paying to build a device and a renderer twice.
pub(crate) const GPU_GRACE: std::time::Duration = std::time::Duration::from_secs(30);

/// Where the loop's device comes from.
///
/// The device is held inline although it makes `Lazy` hundreds of bytes
/// larger than the other variants: there is one slot per application, so
/// boxing it would save nothing.
#[allow(clippy::large_enum_variant)]
pub(crate) enum GpuSlot {
    /// Made when a surface needs it, dropped [`GPU_GRACE`] after the last.
    Lazy {
        gpu: Option<GpuContext>,
        /// When the last surface closed, while the device is still held.
        idle_since: Option<std::time::Instant>,
    },
    /// One device, held by somebody else for longer than the loop — the test
    /// binary's, which `testing::shared_device` makes once.
    #[cfg(feature = "testing")]
    Shared(&'static GpuContext),
    /// No adapter to be had: what a machine without Vulkan hands the loop.
    #[cfg(feature = "testing")]
    Absent,
}

impl GpuSlot {
    pub(crate) fn lazy() -> Self {
        GpuSlot::Lazy {
            gpu: None,
            idle_since: None,
        }
    }

    /// The device, made now if it has to be. `None` when there is no usable
    /// adapter, which is logged by `GpuContext::try_new`.
    pub(crate) fn get(&mut self) -> Option<&GpuContext> {
        match self {
            GpuSlot::Lazy { gpu, idle_since } => {
                *idle_since = None;
                if gpu.is_none() {
                    *gpu = GpuContext::try_new();
                }
                gpu.as_ref()
            }
            #[cfg(feature = "testing")]
            GpuSlot::Shared(gpu) => Some(gpu),
            #[cfg(feature = "testing")]
            GpuSlot::Absent => None,
        }
    }

    /// No surface is left at `now`: let the device go if it has outlived the
    /// last one by [`GPU_GRACE`]. Whether it went.
    pub(crate) fn release_if_idle(&mut self, now: std::time::Instant) -> bool {
        let GpuSlot::Lazy {
            gpu: gpu @ Some(_),
            idle_since,
        } = self
        else {
            return false;
        };
        if now < *idle_since.get_or_insert(now) + GPU_GRACE {
            return false;
        }
        *gpu = None;
        *idle_since = None;
        true
    }

    /// When the loop has to wake to let the device go, if it is waiting to.
    pub(crate) fn release_at(&self) -> Option<std::time::Instant> {
        match self {
            GpuSlot::Lazy {
                gpu: Some(_),
                idle_since: Some(since),
            } => Some(*since + GPU_GRACE),
            _ => None,
        }
    }

    /// The device, if one is held right now.
    #[cfg(feature = "testing")]
    pub(crate) fn held(&self) -> Option<&GpuContext> {
        match self {
            GpuSlot::Lazy { gpu, .. } => gpu.as_ref(),
            GpuSlot::Shared(gpu) => Some(gpu),
            GpuSlot::Absent => None,
        }
    }
}

pub struct GpuContext {
    pub instance: Instance,
    pub device: Arc<Device>,
    pub queue: Arc<Queue>,
    /// Which adapter answered. Kept because a timing is only a fact about the
    /// hardware that produced it: lavapipe and a discrete GPU both draw the
    /// same frame, and only one of them says anything about what a frame
    /// costs. Asking wgpu again later would ask a *second* request_adapter,
    /// which is free to answer differently.
    pub adapter_info: wgpu::AdapterInfo,
}

impl GpuContext {
    /// A device on the first Vulkan adapter that answers, or `None` when there
    /// is none. The reason is logged at error level.
    pub fn try_new() -> Option<Self> {
        let instance = Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::Backends::VULKAN,
            ..wgpu::InstanceDescriptor::new_without_display_handle()
        });

        let adapter =
            match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::LowPower,
                compatible_surface: None,
                force_fallback_adapter: false,
                apply_limit_buckets: false,
            })) {
                Ok(adapter) => adapter,
                Err(e) => {
                    log::error!("No Vulkan adapter: {e}");
                    return None;
                }
            };

        let (device, queue) =
            match pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
                label: Some("Guido Device"),
                required_features: wgpu::Features::TEXTURE_FORMAT_16BIT_NORM,
                required_limits: wgpu::Limits::default(),
                // The default, `Performance`, reserves memory in blocks of
                // 128-256 MB; a renderer allocates about one.
                memory_hints: wgpu::MemoryHints::MemoryUsage,
                experimental_features: wgpu::ExperimentalFeatures::default(),
                trace: wgpu::Trace::Off,
            })) {
                Ok(pair) => pair,
                Err(e) => {
                    log::error!(
                        "Adapter {:?} cannot make a device: {e}",
                        adapter.get_info().name
                    );
                    return None;
                }
            };

        Some(Self {
            instance,
            device: Arc::new(device),
            queue: Arc::new(queue),
            adapter_info: adapter.get_info(),
        })
    }

    pub fn create_surface<W>(&self, window: W, width: u32, height: u32) -> SurfaceState
    where
        W: HasWindowHandle + HasDisplayHandle,
    {
        let surface = unsafe {
            self.instance
                .create_surface_unsafe(
                    wgpu::SurfaceTargetUnsafe::from_display_and_window(&window, &window).unwrap(),
                )
                .expect("Failed to create surface")
        };

        // Get surface capabilities and use preferred format
        let caps = surface.get_capabilities(
            &pollster::block_on(self.instance.request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::LowPower,
                compatible_surface: Some(&surface),
                force_fallback_adapter: false,
                apply_limit_buckets: false,
            }))
            .unwrap(),
        );

        // Select a renderable format - prefer Bgra8Unorm or Rgba8Unorm for compatibility
        let format = caps
            .formats
            .iter()
            .find(|f| {
                matches!(
                    f,
                    wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm
                )
            })
            .copied()
            .unwrap_or_else(|| {
                // Fallback to first format that is not 16-bit
                caps.formats
                    .iter()
                    .find(|f| !matches!(f, wgpu::TextureFormat::Rgba16Unorm))
                    .copied()
                    .unwrap_or(caps.formats[0])
            });

        log::info!("Using surface format: {:?}", format);

        let config = SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format,
            color_space: wgpu::SurfaceColorSpace::Auto,
            width,
            height,
            present_mode: wgpu::PresentMode::Fifo,
            alpha_mode: caps
                .alpha_modes
                .iter()
                .find(|m| **m == wgpu::CompositeAlphaMode::PreMultiplied)
                .copied()
                .unwrap_or_else(|| {
                    caps.alpha_modes
                        .first()
                        .copied()
                        .unwrap_or(wgpu::CompositeAlphaMode::Auto)
                }),
            view_formats: vec![],
            desired_maximum_frame_latency: 2,
        };

        surface.configure(&self.device, &config);

        SurfaceState {
            surface,
            config,
            device: self.device.clone(),
            queue: self.queue.clone(),
        }
    }

    /// The bytes of texture memory this device holds right now, once what has
    /// been dropped is really gone.
    ///
    /// For the tests that ask whether a glyph atlas keeps growing: glyphon
    /// will not say how big its atlas is, but the device it allocates from
    /// can. Needs wgpu's `counters`, which the dev-dependency turns on.
    #[cfg(test)]
    pub(crate) fn texture_bytes(&self) -> isize {
        self.device
            .poll(wgpu::PollType::wait_indefinitely())
            .expect("the device never went idle");
        self.device
            .get_internal_counters()
            .hal
            .texture_memory
            .read()
    }
}

pub struct SurfaceState {
    pub surface: Surface<'static>,
    pub config: SurfaceConfiguration,
    pub device: Arc<Device>,
    pub queue: Arc<Queue>,
}

impl SurfaceState {
    pub fn resize(&mut self, width: u32, height: u32) {
        if width > 0 && height > 0 {
            self.config.width = width;
            self.config.height = height;
            self.surface.configure(&self.device, &self.config);
        }
    }

    pub fn width(&self) -> u32 {
        self.config.width
    }

    pub fn height(&self) -> u32 {
        self.config.height
    }
}

/// Where a drawn frame lands.
///
/// A swapchain is a compositor's: it hands out a texture, takes it back, and
/// shows it. A texture is the caller's, and nobody shows it — which is the only
/// difference, and the reason a frame can be inspected without a compositor at
/// all. Everything upstream of here draws the same commands either way.
pub enum RenderTarget {
    /// The compositor's swapchain. Acquired per frame, presented after.
    Swapchain(SurfaceState),
    /// A texture the caller owns and can read back.
    #[cfg(any(test, feature = "testing"))]
    Offscreen(OffscreenTarget),
}

/// A texture a frame is drawn into, with the handles needed to read it back.
///
/// The texture is the only state: it already knows its size and its format, so
/// storing either beside it would be a second copy of a fact that cannot drift
/// while it is derived.
#[cfg(any(test, feature = "testing"))]
pub struct OffscreenTarget {
    pub texture: wgpu::Texture,
    pub device: Arc<Device>,
    pub queue: Arc<Queue>,
}

#[cfg(any(test, feature = "testing"))]
impl OffscreenTarget {
    /// The colour at one pixel, in the texture's own format.
    pub fn read_pixel(&self, x: u32, y: u32) -> [u8; 4] {
        self.read_back(|data, bytes_per_row| {
            let at = (y * bytes_per_row + x * 4) as usize;
            [data[at], data[at + 1], data[at + 2], data[at + 3]]
        })
    }

    /// Every pixel, row by row and tightly packed, in the texture's own
    /// format — for a test that compares whole frames rather than points.
    pub fn read_pixels(&self) -> Vec<u8> {
        let row = (self.texture.width() * 4) as usize;
        self.read_back(|data, bytes_per_row| {
            let mut out = Vec::with_capacity(row * self.texture.height() as usize);
            for padded in data.chunks(bytes_per_row as usize) {
                out.extend_from_slice(&padded[..row]);
            }
            out
        })
    }

    /// Copy the texture out and hand `read` the mapped bytes and their row
    /// stride.
    ///
    /// Reading a target back is the whole reason to draw into one, so it lives
    /// here rather than beside whoever asks: the row padding wgpu requires and
    /// the map-then-poll order are the sort of thing that is written correctly
    /// once and copied wrongly after.
    fn read_back<R>(&self, read: impl FnOnce(&[u8], u32) -> R) -> R {
        let (width, height) = (self.texture.width(), self.texture.height());
        let bytes_per_row = (width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
            * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
        let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("guido offscreen readback"),
            size: (bytes_per_row * height) as u64,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });
        let mut encoder = self.device.create_command_encoder(&Default::default());
        encoder.copy_texture_to_buffer(
            self.texture.as_image_copy(),
            wgpu::TexelCopyBufferInfo {
                buffer: &buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(bytes_per_row),
                    rows_per_image: Some(height),
                },
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        self.queue.submit([encoder.finish()]);
        buffer.slice(..).map_async(wgpu::MapMode::Read, |_| {});
        self.device
            .poll(wgpu::PollType::wait_indefinitely())
            .expect("readback never completed");
        let data = buffer
            .slice(..)
            .get_mapped_range()
            .expect("the readback buffer was just mapped whole");
        read(&data, bytes_per_row)
    }
}

impl RenderTarget {
    /// A target of `width` by `height` physical pixels, drawn into and kept.
    ///
    /// `COPY_SRC` because a target nobody presents is only useful if it can be
    /// read, and `Rgba8Unorm` because eight bits a channel makes an exact byte
    /// a fair thing to assert.
    #[cfg(any(test, feature = "testing"))]
    pub fn offscreen(gpu: &GpuContext, width: u32, height: u32) -> Self {
        Self::Offscreen(OffscreenTarget {
            texture: offscreen_texture(&gpu.device, width, height),
            device: gpu.device.clone(),
            queue: gpu.queue.clone(),
        })
    }

    pub fn width(&self) -> u32 {
        match self {
            Self::Swapchain(s) => s.width(),
            #[cfg(any(test, feature = "testing"))]
            Self::Offscreen(o) => o.texture.width(),
        }
    }

    pub fn height(&self) -> u32 {
        match self {
            Self::Swapchain(s) => s.height(),
            #[cfg(any(test, feature = "testing"))]
            Self::Offscreen(o) => o.texture.height(),
        }
    }

    /// A swapchain is reconfigured; a texture is replaced.
    ///
    /// Not a no-op for the texture, however tempting: `resolve_geometry` asks
    /// whether the target matches the frame and calls this when it does not, so
    /// a target that quietly declined would report a resize every frame for
    /// ever, repainting the whole tree each time and defeating the incremental
    /// paint the rest of the pipeline is built around.
    pub fn resize(&mut self, width: u32, height: u32) {
        match self {
            Self::Swapchain(s) => s.resize(width, height),
            #[cfg(any(test, feature = "testing"))]
            Self::Offscreen(o) => {
                if width > 0 && height > 0 {
                    o.texture = offscreen_texture(&o.device, width, height);
                }
            }
        }
    }

    pub fn device(&self) -> &Arc<Device> {
        match self {
            Self::Swapchain(s) => &s.device,
            #[cfg(any(test, feature = "testing"))]
            Self::Offscreen(o) => &o.device,
        }
    }

    pub fn queue(&self) -> &Arc<Queue> {
        match self {
            Self::Swapchain(s) => &s.queue,
            #[cfg(any(test, feature = "testing"))]
            Self::Offscreen(o) => &o.queue,
        }
    }

    pub fn format(&self) -> wgpu::TextureFormat {
        match self {
            Self::Swapchain(s) => s.config.format,
            #[cfg(any(test, feature = "testing"))]
            Self::Offscreen(o) => o.texture.format(),
        }
    }
}

#[cfg(any(test, feature = "testing"))]
fn offscreen_texture(device: &Device, width: u32, height: u32) -> wgpu::Texture {
    device.create_texture(&wgpu::TextureDescriptor {
        label: Some("guido offscreen target"),
        size: wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba8Unorm,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
        view_formats: &[],
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::renderer::Renderer;

    /// Every guido process holds a device, and on an integrated GPU what it
    /// reserves is system RAM that RSS does not show (#530).
    #[test]
    fn a_renderer_reserves_megabytes_not_hundreds_of_them() {
        let Some(gpu) = crate::or_skip(GpuContext::try_new()) else {
            return;
        };
        let _renderer = Renderer::new(
            gpu.device.clone(),
            gpu.queue.clone(),
            wgpu::TextureFormat::Bgra8UnormSrgb,
        );
        let report = gpu
            .device
            .generate_allocator_report()
            .expect("Vulkan sub-allocates, so there is a report");
        assert!(
            report.total_reserved_bytes <= 16 << 20,
            "{} MB reserved for {:.2} MB allocated",
            report.total_reserved_bytes >> 20,
            report.total_allocated_bytes as f64 / f64::from(1 << 20),
        );
    }
}