blit-gui 0.1.0

2d drawing for blit
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
use alloc::borrow::Cow;
use core::{
    hash::{Hash, Hasher},
    ops::Range,
};

use blit::{
    Fit, FrameSlice, LogicalPoint, LogicalRect, LogicalSize, Paint, PhysicalPoint, Scratch, ScratchBuffer, StrSource,
    Widget, state,
};

use crate::{
    Context,
    color::Color,
    display_list::{Compare, DisplayList},
};

//
// text system
//

pub trait TextSystem: 'static {
    /// registers geometry using the font attributes in style
    /// returned text runs remain valid until finish_frame
    fn text_run(&mut self, text: &str, style: TextStyle) -> TextRun {
        self.rich_text(text, &[], style)
    }

    /// registers geometry using span ranges and font attributes
    /// returned text runs remain valid until finish_frame
    fn rich_text(&mut self, text: &str, spans: &[Span<'_>], style: TextStyle) -> TextRun;

    fn measure(&mut self, text: TextRun, max_width: Option<f32>, options: TextOptions) -> Fit<LogicalSize>;

    fn offset_at_position(&mut self, area: LogicalRect, request: &TextRequest, position: LogicalPoint) -> usize;

    /// returns the zero-width caret rectangle at `offset`
    /// `upstream` keeps an offset at a soft wrap on the line it ends
    fn caret_rect(&mut self, area: LogicalRect, request: &TextRequest, offset: usize, upstream: bool) -> LogicalRect;

    /// returns visual rectangles for `range` in `scratch`
    fn range_rects<'a>(
        &mut self,
        area: LogicalRect,
        request: &TextRequest,
        range: Range<usize>,
        scratch: &'a ScratchBuffer,
    ) -> Scratch<'a, LogicalRect>;

    /// returns positioned glyphs for painting in `scratch`
    /// returned glyph keys remain valid for rasterize until finish_frame
    fn resolve<'a>(
        &mut self,
        area: LogicalRect,
        request: &TextRequest,
        scale: f32,
        scratch: &'a ScratchBuffer,
    ) -> Scratch<'a, PositionedGlyph>;

    /// equal keys must produce identical pixels and bearings
    fn rasterize(&mut self, key: GlyphKey) -> GlyphImage;

    fn finish_frame(&mut self);
}

#[derive(Clone, Copy, Debug)]
pub struct PositionedGlyph {
    pub key: GlyphKey,
    pub origin: PhysicalPoint,
    pub span: u32,
}

/// glyph identity for renderer pixel caches
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct GlyphKey {
    pub font: u64,
    pub size: u32,
    pub glyph: u32,
    pub phase: u8,
}

impl Hash for GlyphKey {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_u64(self.font);
        state.write_u64((u64::from(self.size) << 32) | u64::from(self.glyph));
        state.write_u8(self.phase);
    }
}

#[derive(Debug, Default)]
pub struct GlyphImage {
    pub metrics: GlyphMetrics,
    pub format: GlyphFormat,
    pub pixels: Cow<'static, [u8]>,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GlyphFormat {
    /// tightly packed coverage tinted by the text color
    #[default]
    Alpha8,
    /// tightly packed rgba with encoded srgb channels multiplied by alpha
    /// keeps intrinsic colors and receives text alpha once
    Rgba8,
}

impl GlyphFormat {
    pub const fn bytes_per_pixel(self) -> usize {
        match self {
            Self::Alpha8 => 1,
            Self::Rgba8 => 4,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct GlyphMetrics {
    pub width: u16,
    pub height: u16,
    /// pixel offset from the glyph origin including any horizontal subpixel phase
    pub left: i16,
    /// pixel offset from the baseline with positive values pointing down
    pub top: i16,
}

//
// widgets
//

blit::builder! {
    #[derive(Clone, Copy, Debug)]
    pub struct Text<'a> {
        new(#[into] text: StrSource<'a>),
        style: TextStyle<'a> = TextStyle::new(),
        offset: LogicalPoint = LogicalPoint::new(0.0, 0.0),
        options: TextOptions = TextOptions::new(),
    }
}

impl<C> Widget<C, state::Insert> for Text<'_>
where
    C: Context + Paint<FrameText>,
{
    type Response = ();

    fn build(self, mut ui: blit::Ui<'_, C, state::Insert>) {
        let text = ui.scratch().str(self.text);
        let run = ui.context_mut().text().text_run(&text, self.style);
        let colors = ui.context_mut().store_mut().slice_from(&[self.style.color]);
        ui.insert(FrameText::new(run, colors).offset(self.offset).options(self.options));
    }
}

blit::builder! {
    /// text partitioned by ordered, contiguous spans
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct RichText<'a> {
        new(text: &'a str, spans: &'a [Span<'a>]),
        style: TextStyle<'a> = TextStyle::new(),
        offset: LogicalPoint = LogicalPoint::new(0.0, 0.0),
        options: TextOptions = TextOptions::new(),
    }
}

impl<C> Widget<C, state::Insert> for RichText<'_>
where
    C: Context + Paint<FrameText>,
{
    type Response = ();

    fn build(self, mut ui: blit::Ui<'_, C, state::Insert>) {
        let run = ui.context_mut().text().rich_text(self.text, self.spans, self.style);
        // empty spans lay out as one span in the base color
        let mut colors = ui.context_mut().store_mut().slice(self.spans.len().max(1));
        if self.spans.is_empty() {
            colors.push(self.style.color);
        } else {
            colors.extend(
                self.spans
                    .iter()
                    .map(|span| span.style.color.unwrap_or(self.style.color)),
            )
        }
        let colors = colors.finish();
        ui.insert(FrameText::new(run, colors).offset(self.offset).options(self.options));
    }
}

//
// painting
//

blit::builder! {
    /// resolved text with span colors stored in the frame
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct FrameText {
        // one color per span
        new(text: TextRun, colors: FrameSlice<Color>),
        offset: LogicalPoint = LogicalPoint::new(0.0, 0.0),
        options: TextOptions = TextOptions::new(),
    }
}

impl<C> Widget<C, state::Insert> for FrameText
where
    C: Context + Paint<Self>,
{
    type Response = ();

    fn build(self, mut ui: blit::Ui<'_, C, state::Insert>) {
        let text = self.text;
        let options = self.options;
        ui.measure(move |cx, constraints| {
            let max_width =
                (options.wrap != TextWrap::None && constraints.max.width.is_finite()).then_some(constraints.max.width);
            cx.text().measure(text, max_width, options)
        });
        ui.paint(move |cx, area| cx.context_mut().paint(area, &self));
    }
}

impl FrameText {
    /// placement used for text system queries
    #[inline]
    pub fn request(&self) -> TextRequest {
        TextRequest::new(self.text).offset(self.offset).options(self.options)
    }

    /// missing spans repeat the last color
    pub fn span_color(&self, list: &DisplayList, span: usize) -> Color {
        let colors = list.store().view(self.colors);
        colors
            .get(span)
            .or(colors.last())
            .copied()
            .unwrap_or(Color::TRANSPARENT)
    }
}

impl Compare for FrameText {
    #[inline]
    fn equal(a: &Self, left: &DisplayList, b: &Self, right: &DisplayList) -> bool {
        a.request() == b.request() && left.store().view(a.colors) == right.store().view(b.colors)
    }

    fn hash(value: &Self, list: &DisplayList, state: &mut impl Hasher) {
        value.request().hash(state);
        list.store().view(value.colors).hash(state);
    }
}

//
// requests and runs
//

/// cached text geometry
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct TextRun(pub u64);

blit::builder! {
    /// placed text for text system queries such as cursor and hit testing
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct TextRequest {
        new(text: TextRun),
        offset: LogicalPoint = LogicalPoint::new(0.0, 0.0),
        options: TextOptions = TextOptions::new(),
    }
}

impl Hash for TextRequest {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let float_bits = |value: f32| if value == 0.0 { 0 } else { value.to_bits() };
        self.text.hash(state);
        float_bits(self.offset.x).hash(state);
        float_bits(self.offset.y).hash(state);
        self.options.wrap.hash(state);
        self.options.overflow.hash(state);
        self.options.horizontal_align.hash(state);
        self.options.vertical_align.hash(state);
        self.options.max_lines.hash(state);
    }
}

//
// style and fonts
//

blit::builder! {
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct TextStyle<'a> {
        new(),
        font: FontId = FontId(0),
        size: f32 = 16.0,
        line_height: LineHeight = LineHeight::Metrics(1.0),
        weight: u16 = 400,
        stretch: u16 = 100,
        style: FontStyle = FontStyle::Normal,
        color: Color = Color::BLACK,
        settings: FontSettings<'a> = FontSettings::new(),
    }
}

blit::builder! {
    /// style overrides for a rich text span
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct SpanStyle<'a> {
        new(),
        #[into]
        font: Option<FontId> = None,
        #[into]
        size: Option<f32> = None,
        /// backends without per-span line height use the base style's
        #[into]
        line_height: Option<LineHeight> = None,
        #[into]
        weight: Option<u16> = None,
        #[into]
        stretch: Option<u16> = None,
        #[into]
        style: Option<FontStyle> = None,
        #[into]
        color: Option<Color> = None,
        #[into]
        settings: Option<FontSettings<'a>> = None,
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LineHeight {
    /// multiple of the font's natural line height
    Metrics(f32),
    /// fixed line height in logical pixels
    Absolute(f32),
}

blit::builder! {
    /// a styled byte range within a rich text string
    #[derive(Clone, Debug, PartialEq)]
    pub struct Span<'a> {
        new(range: Range<usize>),
        style: SpanStyle<'a> = SpanStyle::new(),
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FontId(pub u16);

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FontStyle {
    #[default]
    Normal,
    Italic,
    Oblique,
}

blit::builder! {
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct FontSettings<'a> {
        new(),
        features: &'a [([u8; 4], u32)] = &[],
        variations: &'a [([u8; 4], f32)] = &[],
        #[into]
        language: Option<&'a str> = None,
        optical_size: OpticalSize = OpticalSize::Auto,
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum OpticalSize {
    #[default]
    Auto,
    FontDefault,
    Fixed(f32),
}

//
// options
//

blit::builder! {
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct TextOptions {
        new(),
        wrap: TextWrap = TextWrap::None,
        overflow: TextOverflow = TextOverflow::Clip,
        horizontal_align: HorizontalAlign = HorizontalAlign::Left,
        vertical_align: VerticalAlign = VerticalAlign::Top,
        #[into]
        max_lines: Option<u16> = None,
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextOverflow {
    #[default]
    Clip,
    Ellipsis,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextWrap {
    #[default]
    None,
    Word,
    Character,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum HorizontalAlign {
    #[default]
    Left,
    Center,
    Right,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum VerticalAlign {
    #[default]
    Top,
    Center,
    Bottom,
}