teksilo-canvas 0.9.2

Canvas and geometry layer for Teksilo — RenderFrame, Path, Paint and the TextBackend trait.
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

/// A 2D point in logical pixels.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Point {
    pub x: f32,
    pub y: f32,
}

impl Point {
    pub const ZERO: Point = Point { x: 0.0, y: 0.0 };

    pub fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

/// A 2D vector.
#[derive(Debug, Clone, Copy, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct Vec2 {
    pub x: f32,
    pub y: f32,
}

impl Vec2 {
    pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };

    pub fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

/// A 2D size in logical pixels.
#[derive(Debug, Clone, Copy, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct Size {
    pub width: f32,
    pub height: f32,
}

/// Per-edge inset distances in logical pixels. RTL-aware (`leading` /
/// `trailing` instead of `left` / `right`).
///
/// Lives in teksilo-canvas (not teksilo-tokens) because it's a generic
/// geometry primitive, not a design token. Used by per-widget
/// recipes (`ButtonRecipe::padding`), the `Padding` widget
/// primitive in teksilo-widgets, and any caller that needs to describe
/// a rectangular inset. Pure data — `Send + Sync + Serialize`.
#[derive(Debug, Clone, Copy, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct EdgeInsets {
    pub top: f32,
    pub trailing: f32,
    pub bottom: f32,
    pub leading: f32,
}

impl EdgeInsets {
    pub const ZERO: EdgeInsets = EdgeInsets {
        top: 0.0,
        trailing: 0.0,
        bottom: 0.0,
        leading: 0.0,
    };

    pub const fn new(top: f32, trailing: f32, bottom: f32, leading: f32) -> Self {
        Self {
            top,
            trailing,
            bottom,
            leading,
        }
    }

    pub const fn uniform(value: f32) -> Self {
        Self {
            top: value,
            trailing: value,
            bottom: value,
            leading: value,
        }
    }

    /// `horizontal` applies to leading + trailing; `vertical` applies
    /// to top + bottom.
    pub const fn symmetric(horizontal: f32, vertical: f32) -> Self {
        Self {
            top: vertical,
            trailing: horizontal,
            bottom: vertical,
            leading: horizontal,
        }
    }

    pub fn horizontal(self) -> f32 {
        self.leading + self.trailing
    }

    pub fn vertical(self) -> f32 {
        self.top + self.bottom
    }
}

impl Size {
    pub const ZERO: Size = Size {
        width: 0.0,
        height: 0.0,
    };

    pub fn new(width: f32, height: f32) -> Self {
        Self { width, height }
    }
}

/// A rectangle defined by its origin (top-left) and size, in logical pixels.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Rect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

impl Rect {
    pub const ZERO: Rect = Rect {
        x: 0.0,
        y: 0.0,
        width: 0.0,
        height: 0.0,
    };

    pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    pub fn from_origin_size(origin: Point, size: Size) -> Self {
        Self {
            x: origin.x,
            y: origin.y,
            width: size.width,
            height: size.height,
        }
    }

    pub fn origin(&self) -> Point {
        Point::new(self.x, self.y)
    }

    pub fn size(&self) -> Size {
        Size::new(self.width, self.height)
    }

    pub fn center(&self) -> Point {
        Point::new(self.x + self.width / 2.0, self.y + self.height / 2.0)
    }

    pub fn right(&self) -> f32 {
        self.x + self.width
    }

    pub fn bottom(&self) -> f32 {
        self.y + self.height
    }

    pub fn contains(&self, point: Point) -> bool {
        point.x >= self.x
            && point.x <= self.right()
            && point.y >= self.y
            && point.y <= self.bottom()
    }

    pub fn expand(&self, amount: f32) -> Self {
        Self {
            x: self.x - amount,
            y: self.y - amount,
            width: self.width + amount * 2.0,
            height: self.height + amount * 2.0,
        }
    }

    pub fn inset(&self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
        Self {
            x: self.x + left,
            y: self.y + top,
            width: (self.width - left - right).max(0.0),
            height: (self.height - top - bottom).max(0.0),
        }
    }

    pub fn to_array(&self) -> [f32; 4] {
        [self.x, self.y, self.width, self.height]
    }
}

/// A size proposal from a parent to a child during layout negotiation.
/// `None` means "use your ideal size" for that dimension.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SizeProposal {
    pub width: Option<f32>,
    pub height: Option<f32>,
}

impl SizeProposal {
    pub fn exact(width: f32, height: f32) -> Self {
        Self {
            width: Some(width),
            height: Some(height),
        }
    }

    pub fn unspecified() -> Self {
        Self {
            width: None,
            height: None,
        }
    }

    pub fn with_width(width: f32) -> Self {
        Self {
            width: Some(width),
            height: None,
        }
    }

    pub fn with_height(height: f32) -> Self {
        Self {
            width: None,
            height: Some(height),
        }
    }

    /// Resolve to a concrete size, using the provided defaults for unspecified dimensions.
    pub fn resolve(&self, default_width: f32, default_height: f32) -> Size {
        Size::new(
            self.width.unwrap_or(default_width),
            self.height.unwrap_or(default_height),
        )
    }
}

/// A 2D affine transform stored as a 3×2 matrix: `[a, b, c, d, tx, ty]`.
///
/// The transform maps a point `(x, y)` to:
///   `(a*x + c*y + tx, b*x + d*y + ty)`
///
/// This is the standard 2D affine matrix layout compatible with GPU uniform buffers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Transform2D {
    /// Matrix entries: [a, b, c, d, tx, ty].
    pub m: [f32; 6],
}

impl Transform2D {
    pub const IDENTITY: Transform2D = Transform2D {
        m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
    };

    pub fn identity() -> Self {
        Self::IDENTITY
    }

    pub fn translate(dx: f32, dy: f32) -> Self {
        Self {
            m: [1.0, 0.0, 0.0, 1.0, dx, dy],
        }
    }

    pub fn rotate(angle_radians: f32) -> Self {
        let (s, c) = angle_radians.sin_cos();
        Self {
            m: [c, s, -s, c, 0.0, 0.0],
        }
    }

    pub fn scale(sx: f32, sy: f32) -> Self {
        Self {
            m: [sx, 0.0, 0.0, sy, 0.0, 0.0],
        }
    }

    /// Compose: apply `self` then `other` (i.e. `other * self`).
    pub fn then(&self, other: &Transform2D) -> Transform2D {
        let [a1, b1, c1, d1, tx1, ty1] = self.m;
        let [a2, b2, c2, d2, tx2, ty2] = other.m;
        Transform2D {
            m: [
                a2 * a1 + c2 * b1,
                b2 * a1 + d2 * b1,
                a2 * c1 + c2 * d1,
                b2 * c1 + d2 * d1,
                a2 * tx1 + c2 * ty1 + tx2,
                b2 * tx1 + d2 * ty1 + ty2,
            ],
        }
    }

    pub fn apply_point(&self, p: Point) -> Point {
        let [a, b, c, d, tx, ty] = self.m;
        Point::new(a * p.x + c * p.y + tx, b * p.x + d * p.y + ty)
    }

    /// Compute the axis-aligned bounding box of a transformed rectangle.
    pub fn apply_rect(&self, r: Rect) -> Rect {
        let corners = [
            self.apply_point(Point::new(r.x, r.y)),
            self.apply_point(Point::new(r.right(), r.y)),
            self.apply_point(Point::new(r.right(), r.bottom())),
            self.apply_point(Point::new(r.x, r.bottom())),
        ];
        let min_x = corners.iter().map(|p| p.x).fold(f32::INFINITY, f32::min);
        let min_y = corners.iter().map(|p| p.y).fold(f32::INFINITY, f32::min);
        let max_x = corners
            .iter()
            .map(|p| p.x)
            .fold(f32::NEG_INFINITY, f32::max);
        let max_y = corners
            .iter()
            .map(|p| p.y)
            .fold(f32::NEG_INFINITY, f32::max);
        Rect::new(min_x, min_y, max_x - min_x, max_y - min_y)
    }

    /// Convert to GPU-friendly layout: two columns of a 3×2 matrix.
    pub fn to_mat3x2(&self) -> [[f32; 2]; 3] {
        let [a, b, c, d, tx, ty] = self.m;
        [[a, b], [c, d], [tx, ty]]
    }

    pub fn is_identity(&self) -> bool {
        *self == Self::IDENTITY
    }

    /// Overall scale magnitude of the linear part: `sqrt(|det|)`, the
    /// geometric mean of the two axis scales. Rotation-invariant (a pure
    /// rotation returns `1.0`); anisotropic scales average. Used by the
    /// paint walker to derive the glyph raster densification for content
    /// under a scale transform — area is what determines how many screen
    /// pixels a glyph covers, so the geometric mean is the right single
    /// number for an anisotropic transform too.
    pub fn geometric_scale(&self) -> f32 {
        let [a, b, c, d, _, _] = self.m;
        let det = (a * d - c * b).abs();
        if det.is_finite() { det.sqrt() } else { 1.0 }
    }

    /// Inverse of the affine transform, or `None` if the linear part is
    /// singular (determinant zero — a degenerate scale that collapses an
    /// axis). Used by hit-testing to map a screen-space point back into a
    /// transformed widget's pre-transform bounds.
    pub fn inverse(&self) -> Option<Transform2D> {
        let [a, b, c, d, tx, ty] = self.m;
        let det = a * d - c * b;
        if det == 0.0 || !det.is_finite() {
            return None;
        }
        let inv_det = 1.0 / det;
        let ia = d * inv_det;
        let ib = -b * inv_det;
        let ic = -c * inv_det;
        let id = a * inv_det;
        let itx = (c * ty - d * tx) * inv_det;
        let ity = (b * tx - a * ty) * inv_det;
        Some(Transform2D {
            m: [ia, ib, ic, id, itx, ity],
        })
    }
}

impl Default for Transform2D {
    fn default() -> Self {
        Self::IDENTITY
    }
}

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

    #[test]
    fn rect_contains_point_inside() {
        let r = Rect::new(10.0, 10.0, 100.0, 50.0);
        assert!(r.contains(Point::new(50.0, 30.0)));
    }

    #[test]
    fn rect_does_not_contain_point_outside() {
        let r = Rect::new(10.0, 10.0, 100.0, 50.0);
        assert!(!r.contains(Point::new(5.0, 5.0)));
        assert!(!r.contains(Point::new(200.0, 30.0)));
    }

    #[test]
    fn rect_contains_point_on_edge() {
        let r = Rect::new(10.0, 10.0, 100.0, 50.0);
        assert!(r.contains(Point::new(10.0, 10.0))); // top-left
        assert!(r.contains(Point::new(110.0, 60.0))); // bottom-right
    }

    #[test]
    fn rect_center() {
        let r = Rect::new(0.0, 0.0, 100.0, 50.0);
        assert_eq!(r.center(), Point::new(50.0, 25.0));
    }

    #[test]
    fn rect_center_with_offset() {
        let r = Rect::new(10.0, 20.0, 100.0, 50.0);
        assert_eq!(r.center(), Point::new(60.0, 45.0));
    }

    #[test]
    fn rect_expand() {
        let r = Rect::new(10.0, 10.0, 100.0, 50.0);
        let expanded = r.expand(5.0);
        assert_eq!(expanded.x, 5.0);
        assert_eq!(expanded.y, 5.0);
        assert_eq!(expanded.width, 110.0);
        assert_eq!(expanded.height, 60.0);
    }

    #[test]
    fn rect_inset() {
        let r = Rect::new(0.0, 0.0, 100.0, 50.0);
        let inset = r.inset(10.0, 10.0, 10.0, 10.0);
        assert_eq!(inset.x, 10.0);
        assert_eq!(inset.y, 10.0);
        assert_eq!(inset.width, 80.0);
        assert_eq!(inset.height, 30.0);
    }

    #[test]
    fn rect_inset_clamped_to_zero() {
        let r = Rect::new(0.0, 0.0, 10.0, 10.0);
        let inset = r.inset(20.0, 20.0, 20.0, 20.0);
        assert_eq!(inset.width, 0.0);
        assert_eq!(inset.height, 0.0);
    }

    #[test]
    fn size_proposal_resolve_with_defaults() {
        let p = SizeProposal::with_width(200.0);
        let size = p.resolve(100.0, 50.0);
        assert_eq!(size.width, 200.0);
        assert_eq!(size.height, 50.0);
    }

    #[test]
    fn transform_identity() {
        let t = Transform2D::identity();
        assert!(t.is_identity());
        let p = t.apply_point(Point::new(3.0, 4.0));
        assert_eq!(p, Point::new(3.0, 4.0));
    }

    #[test]
    fn transform_translate() {
        let t = Transform2D::translate(10.0, 20.0);
        let p = t.apply_point(Point::new(3.0, 4.0));
        assert_eq!(p, Point::new(13.0, 24.0));
    }

    #[test]
    fn transform_scale() {
        let t = Transform2D::scale(2.0, 3.0);
        let p = t.apply_point(Point::new(5.0, 10.0));
        assert_eq!(p, Point::new(10.0, 30.0));
    }

    #[test]
    fn transform_rotate_90() {
        let t = Transform2D::rotate(std::f32::consts::FRAC_PI_2);
        let p = t.apply_point(Point::new(1.0, 0.0));
        assert!((p.x - 0.0).abs() < 1e-5);
        assert!((p.y - 1.0).abs() < 1e-5);
    }

    #[test]
    fn transform_compose_translate_then_scale() {
        let translate = Transform2D::translate(10.0, 0.0);
        let scale = Transform2D::scale(2.0, 2.0);
        // apply translate first, then scale: result = scale(translate(point))
        let composed = translate.then(&scale);
        let p = composed.apply_point(Point::new(5.0, 3.0));
        assert_eq!(p, Point::new(30.0, 6.0)); // (5+10)*2, 3*2
    }

    #[test]
    fn transform_apply_rect() {
        let t = Transform2D::translate(100.0, 200.0);
        let r = t.apply_rect(Rect::new(10.0, 20.0, 30.0, 40.0));
        assert!((r.x - 110.0).abs() < 1e-5);
        assert!((r.y - 220.0).abs() < 1e-5);
        assert!((r.width - 30.0).abs() < 1e-5);
        assert!((r.height - 40.0).abs() < 1e-5);
    }

    #[test]
    fn transform_inverse_identity() {
        let t = Transform2D::IDENTITY;
        assert_eq!(t.inverse().unwrap(), Transform2D::IDENTITY);
    }

    #[test]
    fn transform_inverse_translate_roundtrip() {
        let t = Transform2D::translate(10.0, 20.0);
        let inv = t.inverse().unwrap();
        let p = Point::new(3.0, 4.0);
        let q = inv.apply_point(t.apply_point(p));
        assert!((q.x - p.x).abs() < 1e-5);
        assert!((q.y - p.y).abs() < 1e-5);
    }

    #[test]
    fn transform_inverse_scale_roundtrip() {
        let t = Transform2D::scale(2.0, 3.0);
        let inv = t.inverse().unwrap();
        let p = Point::new(5.0, 7.0);
        let q = inv.apply_point(t.apply_point(p));
        assert!((q.x - p.x).abs() < 1e-5);
        assert!((q.y - p.y).abs() < 1e-5);
    }

    #[test]
    fn transform_inverse_rotation_roundtrip() {
        let t = Transform2D::rotate(std::f32::consts::FRAC_PI_3);
        let inv = t.inverse().unwrap();
        let p = Point::new(1.0, 2.0);
        let q = inv.apply_point(t.apply_point(p));
        assert!((q.x - p.x).abs() < 1e-4);
        assert!((q.y - p.y).abs() < 1e-4);
    }

    #[test]
    fn transform_inverse_compose_roundtrip() {
        // (translate then scale).inverse() should map any point back to itself.
        let t = Transform2D::translate(50.0, 0.0).then(&Transform2D::scale(2.0, 2.0));
        let inv = t.inverse().unwrap();
        let p = Point::new(7.5, -3.0);
        let q = inv.apply_point(t.apply_point(p));
        assert!((q.x - p.x).abs() < 1e-4);
        assert!((q.y - p.y).abs() < 1e-4);
    }

    #[test]
    fn transform_inverse_singular_returns_none() {
        // Scale by 0 collapses an axis: not invertible.
        let t = Transform2D::scale(0.0, 1.0);
        assert!(t.inverse().is_none());
    }

    #[test]
    fn transform_to_mat3x2() {
        let t = Transform2D::translate(10.0, 20.0);
        let m = t.to_mat3x2();
        assert_eq!(m, [[1.0, 0.0], [0.0, 1.0], [10.0, 20.0]]);
    }

    #[test]
    fn transform_not_identity() {
        let t = Transform2D::translate(1.0, 0.0);
        assert!(!t.is_identity());
    }
}