feather-ui 0.4.0

Feather UI library
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2025 Fundament Research Institute <https://fundament.institute>

use std::collections::HashMap;

use crate::render::atlas::{ATLAS_FORMAT, Atlas, AtlasKind};
use crate::render::compositor::Compositor;
use crate::render::shape::Shape;
use crate::render::{atlas, compositor};
use crate::resource::{Loader, Location, MAX_VARIANCE};
use crate::{Error, Mat4x4, render};
use guillotiere::AllocId;
use parking_lot::RwLock;
use smallvec::SmallVec;
use std::any::TypeId;
use std::sync::Arc;
use swash::scale::ScaleContext;
use wgpu::{PipelineLayout, ShaderModule};
use winit::window::CursorIcon;

// Points are specified as 72 per inch, and a scale factor of 1.0 corresponds to
// 96 DPI, so we multiply by the ratio times the scaling factor.
#[inline]
pub fn point_to_pixel(pt: f32, scale_factor: f32) -> f32 {
    pt * (72.0 / 96.0) * scale_factor // * text_scale_factor
}

pub type PipelineID = TypeId;

#[derive_where::derive_where(Debug)]
#[allow(clippy::type_complexity)]
pub(crate) struct PipelineState {
    layout: PipelineLayout,
    shader: ShaderModule,
    #[derive_where(skip)]
    generator: Box<
        dyn Fn(&PipelineLayout, &ShaderModule, &Driver) -> Box<dyn render::Pipeline> + Send + Sync,
    >,
}

#[derive(Debug)]
pub struct GlyphRegion {
    pub offset: [i32; 2],
    pub region: atlas::Region,
}

pub(crate) type GlyphCache = HashMap<cosmic_text::CacheKey, GlyphRegion>;

/// Represents a particular realized instance of a resource on the GPU. This
/// includes the target size, DPI, and whether mipmaps have been generated.
#[derive(Debug)]
pub struct ResourceInstance<'a> {
    location: Result<Box<dyn Location>, &'a dyn Location>,
    /// If finite, this is used for vector resources, which must care about DPI
    /// beyond simply changing their size.
    dpi: f32,
    /// If true, mipmaps should be generated for this resource because the user
    /// expects to resize it in realtime.
    resizable: bool,
}

impl Clone for ResourceInstance<'_> {
    fn clone(&self) -> Self {
        Self {
            location: self.location.clone(),
            dpi: self.dpi,
            resizable: self.resizable,
        }
    }
}

impl std::hash::Hash for ResourceInstance<'_> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match &self.location {
            Ok(l) => l.hash(state),
            Err(l) => l.hash(state),
        }
        // This works because DPI is always non-zero
        f32::to_bits(self.dpi).hash(state);
        self.resizable.hash(state);
    }
}

impl PartialEq for ResourceInstance<'_> {
    fn eq(&self, other: &Self) -> bool {
        let l = match &self.location {
            Ok(l) => l.as_ref(),
            Err(l) => *l,
        };

        let r = match &other.location {
            Ok(l) => l.as_ref(),
            Err(l) => *l,
        };

        *l == *r && self.dpi == other.dpi && self.resizable == other.resizable
    }
}

// We don't put NaNs in our DPI float so this is fine.
impl Eq for ResourceInstance<'_> {}

// We want to share our device/adapter state across windows, but can't create it
// until we have at least one window, so we store a weak reference to it in App
// and if all windows are dropped it'll also drop these, which is usually
// sensible behavior.
#[allow(clippy::type_complexity)]
#[derive_where::derive_where(Debug)]
pub struct Driver {
    pub(crate) glyphs: RwLock<GlyphCache>,
    pub(crate) prefetch: RwLock<HashMap<Box<dyn Location>, Box<dyn Loader>>>,
    pub(crate) resources:
        RwLock<HashMap<ResourceInstance<'static>, (SmallVec<[atlas::Region; 1]>, atlas::Size)>>,
    pub(crate) locations:
        RwLock<HashMap<Box<dyn Location>, SmallVec<[ResourceInstance<'static>; 1]>>>,
    pub(crate) atlas: RwLock<Atlas>,
    pub(crate) layer_atlas: [RwLock<Atlas>; 2],
    pub(crate) layer_composite: [RwLock<compositor::Compositor>; 2],
    pub(crate) shared: compositor::Shared,
    pub(crate) pipelines: RwLock<HashMap<PipelineID, Box<dyn crate::render::Pipeline>>>,
    pub(crate) registry: RwLock<HashMap<PipelineID, PipelineState>>,
    pub(crate) queue: wgpu::Queue,
    pub(crate) device: wgpu::Device,
    pub(crate) adapter: wgpu::Adapter,
    pub(crate) cursor: RwLock<CursorIcon>, /* This is a convenient place to track our global
                                            * expected cursor */
    #[derive_where(skip)]
    pub(crate) swash_cache: RwLock<ScaleContext>,
    pub(crate) font_system: RwLock<cosmic_text::FontSystem>,
}

impl Drop for Driver {
    fn drop(&mut self) {
        for (_, mut p) in self.pipelines.write().drain() {
            p.destroy(self);
        }

        for (_, mut r) in self.glyphs.get_mut().drain() {
            r.region.id = AllocId::deserialize(u32::MAX);
        }

        for (_, (regions, _)) in self.resources.get_mut().drain() {
            for mut region in regions {
                region.id = AllocId::deserialize(u32::MAX);
            }
        }
    }
}

impl Driver {
    pub async fn new(
        weak: &mut std::sync::Weak<Self>,
        instance: &wgpu::Instance,
        surface: &wgpu::Surface<'static>,
        on_driver: &mut Option<Box<dyn FnOnce(std::sync::Weak<Driver>) + 'static>>,
    ) -> eyre::Result<Arc<Self>> {
        if let Some(driver) = weak.upgrade() {
            return Ok(driver);
        }

        let adapter = futures_lite::future::block_on(instance.request_adapter(
            &wgpu::RequestAdapterOptions {
                compatible_surface: Some(surface),
                ..Default::default()
            },
        ))?;

        // Create the logical device and command queue
        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("Feather UI wgpu Device"),
                required_features: wgpu::Features::empty(),
                required_limits: wgpu::Limits::default(),
                memory_hints: wgpu::MemoryHints::MemoryUsage,
                trace: wgpu::Trace::Off,
            })
            .await?;

        let shared = compositor::Shared::new(&device);
        let atlas = Atlas::new(&device, 512, AtlasKind::Primary);
        let layer0 = Atlas::new(&device, 128, AtlasKind::Layer0);
        let layer1 = Atlas::new(&device, 128, AtlasKind::Layer1);
        let shape_shader = Shape::<0>::shader(&device);
        let shape_pipeline = Shape::<0>::layout(&device);

        let comp1 = Compositor::new(
            &device,
            &shared,
            &atlas.view,
            &layer1.view,
            ATLAS_FORMAT,
            true,
        );
        let comp2 = Compositor::new(
            &device,
            &shared,
            &atlas.view,
            &layer0.view,
            ATLAS_FORMAT,
            false,
        );

        let mut driver = Self {
            adapter,
            device,
            queue,
            swash_cache: ScaleContext::new().into(),
            prefetch: HashMap::new().into(),
            resources: HashMap::new().into(),
            locations: HashMap::new().into(),
            font_system: cosmic_text::FontSystem::new().into(),
            cursor: CursorIcon::Default.into(),
            pipelines: HashMap::new().into(),
            glyphs: HashMap::new().into(),
            registry: HashMap::new().into(),
            shared,
            atlas: atlas.into(),
            layer_atlas: [layer0.into(), layer1.into()],
            layer_composite: [comp1.into(), comp2.into()],
        };

        driver.register_pipeline::<Shape<0>>(
            shape_pipeline.clone(),
            shape_shader.clone(),
            Shape::<0>::create,
        );
        driver.register_pipeline::<Shape<1>>(
            shape_pipeline.clone(),
            shape_shader.clone(),
            Shape::<1>::create,
        );
        driver.register_pipeline::<Shape<2>>(
            shape_pipeline.clone(),
            shape_shader.clone(),
            Shape::<2>::create,
        );
        driver.register_pipeline::<Shape<3>>(
            shape_pipeline.clone(),
            shape_shader.clone(),
            Shape::<3>::create,
        );

        let driver = Arc::new(driver);
        *weak = Arc::downgrade(&driver);

        if let Some(f) = on_driver.take() {
            f(weak.clone());
        }
        Ok(driver)
    }

    pub fn register_pipeline<T: 'static>(
        &mut self,
        layout: PipelineLayout,
        shader: ShaderModule,
        generator: impl Fn(&PipelineLayout, &ShaderModule, &Self) -> Box<dyn render::Pipeline>
        + Send
        + Sync
        + 'static,
    ) {
        self.registry.write().insert(
            TypeId::of::<T>(),
            PipelineState {
                layout,
                shader,
                generator: Box::new(generator),
            },
        );
    }

    /// Allows replacing the shader in a pipeline, for hot-reloading.
    pub fn reload_pipeline<T: 'static>(&self, shader: ShaderModule) {
        let id = TypeId::of::<T>();
        let mut registry = self.registry.write();
        let pipeline = registry
            .get_mut(&id)
            .expect("Tried to reload unregistered pipeline!");
        pipeline.shader = shader;
        self.pipelines.write().remove(&id);
    }
    pub fn with_pipeline<T: crate::render::Pipeline + 'static, R>(
        &self,
        f: impl FnOnce(&mut T) -> R,
    ) -> R {
        let id = TypeId::of::<T>();

        // We can't use the result of this because it makes the lifetimes weird
        if self.pipelines.read().get(&id).is_none() {
            let PipelineState {
                generator,
                layout,
                shader,
            } = &self.registry.read()[&id];

            self.pipelines
                .write()
                .insert(id, generator(layout, shader, self));
        }

        f(
            (self.pipelines.write().get_mut(&id).unwrap().as_mut() as &mut dyn std::any::Any)
                .downcast_mut()
                .unwrap(),
        )
    }

    pub fn prefetch(&self, location: &dyn Location) -> Result<(), Error> {
        let mut resources = self.prefetch.write();

        if !resources.contains_key(location) {
            resources.insert(dyn_clone::clone_box(location), location.fetch()?);
        }
        Ok(())
    }

    /// This function is called during layout, outside of a render pass, which
    /// allows the texture atlas to be immediately resized to accommodate
    /// the new resource. As a result, it assumes you don't need the region,
    /// only the final intrinsic size.
    pub fn load_and_resize(
        &self,
        location: &dyn Location,
        size: atlas::Size,
        dpi: f32,
        resize: bool,
    ) -> Result<atlas::Size, Error> {
        let mut uvsize = atlas::Size::zero();
        match self.load(location, size, dpi, resize, |r| {
            uvsize = r.uv.size();
            Ok(())
        }) {
            Err(Error::ResizeTextureAtlas(layers, kind)) => {
                // Resize the texture atlas with the requested number of layers (the extent has
                // already been changed)
                match kind {
                    AtlasKind::Primary => self.atlas.write(),
                    AtlasKind::Layer0 => self.layer_atlas[0].write(),
                    AtlasKind::Layer1 => self.layer_atlas[1].write(),
                }
                .resize(&self.device, &self.queue, layers);
                self.load_and_resize(location, size, dpi, resize) // Retry load
            }
            Err(e) => Err(e),
            Ok(_) => Ok(uvsize),
        }
    }

    pub fn load(
        &self,
        location: &dyn Location,
        mut size: atlas::Size,
        dpi: f32,
        resize: bool,
        mut f: impl FnMut(&atlas::Region) -> Result<(), Error>,
    ) -> Result<(), Error> {
        use crate::resource;

        if let Some((regions, native_size)) = self.resources.read().get(&ResourceInstance {
            location: Err(location),
            dpi: f32::INFINITY,
            resizable: resize,
        }) {
            size = resource::fill_size(size, *native_size);

            // Check if our requested size is within reasonable resize range - slightly
            // bigger or smaller is fine, and much smaller is fine if we have
            // access to mipmaps.
            for r in regions {
                if r.uv.size() == size
                    || (r.uv.area() >= resource::MIN_AREA
                        && resource::within_variance(size.width, r.uv.width(), MAX_VARIANCE)
                        && resource::within_variance(size.height, r.uv.height(), MAX_VARIANCE))
                    || (resize && size.width <= r.uv.width() && size.height < r.uv.height())
                {
                    return f(r);
                }
            }
        }

        // Check for a prefetched resource
        let (region, native) = {
            let loader;
            let reader = self.prefetch.read();
            let refload = if let Some(res) = reader.get(location) {
                res
            } else {
                loader = location.fetch()?;
                &loader
            };
            let (raw, dim) = refload.preload(size, dpi)?;
            refload.load(self, (raw, dim), resize)?
        };

        let key = ResourceInstance {
            location: Ok(dyn_clone::clone_box(location)),
            dpi: f32::INFINITY,
            resizable: resize,
        };

        self.locations
            .write()
            .entry(dyn_clone::clone_box(location))
            .and_modify(|x| x.push(key.clone()))
            .or_insert(SmallVec::from_buf([key.clone()]));

        if let Some((entry, _)) = self.resources.write().get_mut(&key) {
            entry.push(region);
            f(entry.last().as_ref().ok_or(Error::InternalFailure)?)
        } else {
            f(&self
                .resources
                .write()
                .entry(key)
                .insert_entry((SmallVec::from_buf([region]), native))
                .get()
                .0[0])
        }
    }

    /// Removes all loaded instances of a particular resource location.
    /// Generally used for hotloading resources that changed on disk.
    pub fn evict(&self, location: &dyn Location) {
        if let Some(instances) = self.locations.read().get(location) {
            for instance in instances {
                if let Some((regions, _)) = self.resources.write().remove(instance) {
                    for mut region in regions {
                        self.atlas.write().destroy(&mut region);
                    }
                }
            }
        }
    }
}

static_assertions::assert_impl_all!(Driver: Send, Sync);

static_assertions::const_assert!(size_of::<Mat4x4>() == size_of::<[f32; 16]>());

// This maps x and y to the viewpoint size, maps input_z from [n,f] to [0,1],
// and sets output_w = input_z for perspective. Requires input_w = 1
pub fn mat4_proj(x: f32, y: f32, w: f32, h: f32, n: f32, f: f32) -> Mat4x4 {
    Mat4x4::from_arrays([
        [2.0 / w, 0.0, 0.0, 0.0],
        [0.0, 2.0 / h, 0.0, 0.0],
        [0.0, 0.0, 1.0 / (f - n), 1.0],
        [-(2.0 * x + w) / w, -(2.0 * y + h) / h, -n / (f - n), 0.0],
    ])
}

// Orthographic projection matrix
pub fn mat4_ortho(x: f32, y: f32, w: f32, h: f32, n: f32, f: f32) -> Mat4x4 {
    Mat4x4::from_arrays([
        [2.0 / w, 0.0, 0.0, 0.0],
        [0.0, 2.0 / h, 0.0, 0.0],
        [0.0, 0.0, -2.0 / (f - n), 0.0],
        [
            -(2.0 * x + w) / w,
            -(2.0 * y + h) / h,
            (f + n) / (f - n),
            1.0,
        ],
    ])
}

macro_rules! gen_from_array {
    ($s:path, $t:path, $i:literal) => {
        impl From<[$t; $i]> for $s {
            fn from(value: [$t; $i]) -> Self {
                Self(value)
            }
        }
        impl From<&[$t; $i]> for $s {
            fn from(value: &[$t; $i]) -> Self {
                Self(*value)
            }
        }
    };
}

#[repr(C, align(8))]
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::NoUninit)]
pub struct Vec2f(pub(crate) [f32; 2]);

gen_from_array!(Vec2f, f32, 2);

static_assertions::assert_eq_size!(Vec2f, [f32; 2]);

impl std::hash::Hash for Vec2f {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        use crate::Canonicalize;
        self.0.map(|x| x.canonical_bits()).hash(state);
    }
}

impl std::ops::AddAssign<[f32; 2]> for Vec2f {
    fn add_assign(&mut self, rhs: [f32; 2]) {
        self.0[0] += rhs[0];
        self.0[1] += rhs[1];
    }
}

#[repr(C, align(16))]
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::NoUninit)]
pub struct Vec4f(pub(crate) [f32; 4]);

gen_from_array!(Vec4f, f32, 4);

static_assertions::assert_eq_size!(Vec4f, [f32; 4]);

impl std::hash::Hash for Vec4f {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        use crate::Canonicalize;
        self.0.map(|x| x.canonical_bits()).hash(state);
    }
}

#[repr(C, align(8))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Hash, bytemuck::NoUninit)]
pub struct Vec2i(pub(crate) [i32; 2]);

gen_from_array!(Vec2i, i32, 2);

#[repr(C, align(16))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Hash, bytemuck::NoUninit)]
pub struct Vec4i(pub(crate) [i32; 4]);

gen_from_array!(Vec4i, i32, 4);