sequoia-view 0.1.4

Sequoia GUI framework — view tree and runtime
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
#![forbid(unsafe_code)]

use std::rc::Rc;

use sequoia_core::{BlendMode, Color, Dirty, Fill, Length, Point, Rect, Size, TexInput, Vec2};
use sequoia_input::{
    CursorIcon, Event, EventPhase, Key, KeyEvent, Modifiers, PointerButton, PointerEvent,
};
use sequoia_layout::LayoutStyle;

use crate::painter::Painter;
use crate::shader_pass::{ShaderChain, ShaderPass};
use crate::view::{EventCtx, PaintCtx, View};

#[derive(Clone)]
pub struct KeyBinding {
    pub key: Key,

    pub modifiers: Modifiers,
    action: Rc<dyn Fn()>,
}

impl KeyBinding {
    pub fn new(key: Key, modifiers: Modifiers, action: impl Fn() + 'static) -> Self {
        Self {
            key,
            modifiers,
            action: Rc::new(action),
        }
    }

    pub fn fire(&self) {
        (self.action)();
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Camera {
    pub pos: Vec2,
    pub zoom: f32,
}

impl Camera {
    pub fn new(pos: Vec2, zoom: f32) -> Self {
        let zoom = if zoom.is_finite() && zoom > 0.0 {
            zoom
        } else {
            1.0
        };
        Self { pos, zoom }
    }

    pub fn identity() -> Self {
        Self {
            pos: Vec2::ZERO,
            zoom: 1.0,
        }
    }
}

#[derive(Clone)]
pub struct Canvas {
    background: Option<Fill>,
    focusable: bool,
    capturable: bool,
    cursor: CursorIcon,
    style: LayoutStyle,
    draw: Rc<dyn Fn(&mut Painter)>,
    on_pointer: Option<Rc<dyn Fn(Point, &PointerEvent, &mut EventCtx)>>,
    bindings: Vec<KeyBinding>,
    on_key: Option<Rc<dyn Fn(&KeyEvent) -> bool>>,
    track: Option<Rc<dyn Fn()>>,
    clip: bool,

    overflow: f32,

    grid: Option<(f32, Color)>,

    axes: Option<Color>,

    snap: Option<f32>,

    camera: Option<Camera>,
}

impl Default for Canvas {
    fn default() -> Self {
        Self::new()
    }
}

impl Canvas {
    pub fn new() -> Self {
        Self {
            background: None,
            focusable: true,
            capturable: true,
            cursor: CursorIcon::Default,
            style: LayoutStyle {
                width: Length::Fill(1.0),
                height: Length::Fill(1.0),
                ..LayoutStyle::default()
            },
            draw: Rc::new(|_| {}),
            on_pointer: None,
            bindings: Vec::new(),
            on_key: None,
            track: None,
            clip: true,
            overflow: 0.0,
            grid: None,
            axes: None,
            snap: None,
            camera: None,
        }
    }

    pub fn background(mut self, fill: impl Into<Fill>) -> Self {
        self.background = Some(fill.into());
        self
    }

    pub fn no_background(mut self) -> Self {
        self.background = None;
        self
    }

    pub fn focusable(mut self, focusable: bool) -> Self {
        self.focusable = focusable;
        self
    }

    pub fn capture(mut self, capturable: bool) -> Self {
        self.capturable = capturable;
        self
    }

    pub fn cursor(mut self, cursor: CursorIcon) -> Self {
        self.cursor = cursor;
        self
    }

    pub fn width(mut self, width: impl Into<Length>) -> Self {
        self.style = self.style.width(width.into());
        self
    }

    pub fn height(mut self, height: impl Into<Length>) -> Self {
        self.style = self.style.height(height.into());
        self
    }

    pub fn min_width(mut self, v: f32) -> Self {
        self.style = self.style.min_width(v);
        self
    }

    pub fn max_width(mut self, v: f32) -> Self {
        self.style = self.style.max_width(v);
        self
    }

    pub fn min_height(mut self, v: f32) -> Self {
        self.style = self.style.min_height(v);
        self
    }

    pub fn max_height(mut self, v: f32) -> Self {
        self.style = self.style.max_height(v);
        self
    }

    pub fn flex(mut self, weight: f32) -> Self {
        self.style = self.style.flex(weight);
        self
    }

    pub fn expand(self) -> Self {
        self.flex(1.0)
    }

    pub fn fill_width(mut self) -> Self {
        self.style = self.style.width(Length::Fill(1.0));
        self
    }

    pub fn fill_height(mut self) -> Self {
        self.style = self.style.height(Length::Fill(1.0));
        self
    }

    pub fn fill_size(self) -> Self {
        self.fill_width().fill_height()
    }

    pub fn on_draw(mut self, draw: impl Fn(&mut Painter) + 'static) -> Self {
        self.draw = Rc::new(draw);
        self
    }

    /// Replaces the canvas draw with `content` piped through `shader`.
    ///
    /// `content` renders into an offscreen target and `shader` is drawn over the
    /// whole canvas with that target bound as its `content` input. The shader
    /// must be registered (see `App::shader_type`).
    #[must_use]
    pub fn with_effect<E>(mut self, shader: E, content: impl Fn(&mut Painter) + 'static) -> Self
    where
        E: sequoia_shader::SequoiShader + Copy + 'static,
    {
        self.draw = Rc::new(move |g: &mut Painter| {
            let rect = g.rect();
            let (target, ()) = g.group(rect.size, sequoia_core::BlendMode::Normal, |inner| {
                content(inner)
            });
            g.shader(
                shader,
                rect,
                &[("content", sequoia_core::TexInput::Target(target))],
            );
        });
        self
    }

    /// Replaces the canvas draw with a configured shader pass.
    ///
    /// The pass draws over the canvas bounds unless [`ShaderPass::at`] was
    /// used. Missing registrations log a warning and skip the draw.
    #[must_use]
    pub fn with_shader_pass<S>(mut self, pass: ShaderPass<S>) -> Self
    where
        S: sequoia_shader::SequoiShader + Copy + 'static,
    {
        self.draw = Rc::new(move |g: &mut Painter| {
            pass.draw(g);
        });
        self
    }

    /// Replaces the canvas draw with `content` piped through a configured pass.
    ///
    /// The pass's first declared texture is bound to the captured content unless
    /// the pass already binds it explicitly. Use this instead of `with_effect`
    /// when the effect has extra uniforms, a blend mode, or a UV window.
    #[must_use]
    pub fn with_effect_pass<S>(
        mut self,
        pass: ShaderPass<S>,
        content: impl Fn(&mut Painter) + 'static,
    ) -> Self
    where
        S: sequoia_shader::SequoiShader + Copy + 'static,
    {
        self.draw = Rc::new(move |g: &mut Painter| {
            let rect = g.rect();
            let (target, ()) = g.group(rect.size, BlendMode::Normal, |inner| content(inner));
            pass.clone()
                .at(rect)
                .primary_input(TexInput::Target(target))
                .draw(g);
        });
        self
    }

    /// Captures two layers and feeds them to the pass in declaration order.
    ///
    /// This is the convenient form of a transition or a two-input composite:
    /// the first shader texture receives `first`, the second receives `second`.
    #[must_use]
    pub fn with_layer_effect<S>(
        mut self,
        pass: ShaderPass<S>,
        first: impl Fn(&mut Painter) + 'static,
        second: impl Fn(&mut Painter) + 'static,
    ) -> Self
    where
        S: sequoia_shader::SequoiShader + Copy + 'static,
    {
        self.draw = Rc::new(move |g: &mut Painter| {
            let rect = g.rect();
            let (first_target, ()) = g.group(rect.size, BlendMode::Normal, |inner| first(inner));
            let (second_target, ()) = g.group(rect.size, BlendMode::Normal, |inner| second(inner));
            pass.clone()
                .at(rect)
                .layers(
                    TexInput::Target(first_target),
                    TexInput::Target(second_target),
                )
                .draw(g);
        });
        self
    }

    /// Pipes `content` through every pass in `chain`.
    ///
    /// Intermediate results live in offscreen targets; the final pass draws
    /// into the canvas. A pass that is not registered is skipped and its input
    /// is forwarded, so an optional effect does not blank the layer.
    #[must_use]
    pub fn with_effect_chain(
        mut self,
        content: impl Fn(&mut Painter) + 'static,
        chain: ShaderChain,
    ) -> Self {
        self.draw = Rc::new(move |g: &mut Painter| {
            if chain.is_empty() {
                content(g);
                return;
            }
            let rect = g.rect();
            let (mut target, ()) = g.group(rect.size, BlendMode::Normal, |inner| content(inner));
            let count = chain.len();
            for (index, pass) in chain.passes().iter().enumerate() {
                if index + 1 == count {
                    if !(pass)(g, rect, TexInput::Target(target)) {
                        g.blit(target, rect, [0.0, 0.0, 1.0, 1.0]);
                    }
                } else {
                    let (next, drawn) = g.group(rect.size, BlendMode::Normal, |inner| {
                        (pass)(inner, rect, TexInput::Target(target))
                    });
                    if drawn {
                        target = next;
                    }
                }
            }
        });
        self
    }

    /// Replaces the canvas draw with `content` masked by `mask`.
    ///
    /// Both closures render into their own offscreen target; the built-in
    /// `apply_mask` shader keeps the layer color and multiplies its alpha by the
    /// mask alpha.
    #[must_use]
    pub fn with_mask(
        mut self,
        mask: impl Fn(&mut Painter) + 'static,
        content: impl Fn(&mut Painter) + 'static,
    ) -> Self {
        self.draw = Rc::new(move |g: &mut Painter| {
            let rect = g.rect();
            let (mask_target, ()) = g.group(rect.size, sequoia_core::BlendMode::Normal, |inner| {
                mask(inner)
            });
            let (layer_target, ()) = g.group(rect.size, sequoia_core::BlendMode::Normal, |inner| {
                content(inner)
            });
            g.shader(
                sequoia_shader::ApplyMask,
                rect,
                &[
                    ("mask", sequoia_core::TexInput::Target(mask_target)),
                    ("layer", sequoia_core::TexInput::Target(layer_target)),
                ],
            );
        });
        self
    }

    pub fn on_pointer(
        mut self,
        handler: impl Fn(Point, &PointerEvent, &mut EventCtx) + 'static,
    ) -> Self {
        self.on_pointer = Some(Rc::new(handler));
        self
    }

    pub fn key(mut self, key: Key, modifiers: Modifiers, action: impl Fn() + 'static) -> Self {
        self.bindings.push(KeyBinding::new(key, modifiers, action));
        self
    }

    pub fn on_key(mut self, handler: impl Fn(&KeyEvent) -> bool + 'static) -> Self {
        self.on_key = Some(Rc::new(handler));
        self
    }

    pub fn track(mut self, track: impl Fn() + 'static) -> Self {
        self.track = Some(Rc::new(track));
        self
    }

    pub fn clip(mut self, clip: bool) -> Self {
        self.clip = clip;
        self
    }

    pub fn allow_overflow(mut self, px: f32) -> Self {
        self.overflow = if px.is_finite() { px.max(0.0) } else { 0.0 };
        self
    }

    pub fn overflow_px(self, px: f32) -> Self {
        self.allow_overflow(px)
    }

    pub fn paint_overflow(&self) -> f32 {
        self.overflow
    }

    pub fn grid(mut self, step: f32) -> Self {
        self.grid = Some((step, Color::rgba(0.5, 0.5, 0.5, 0.08)));
        self
    }

    pub fn grid_colored(mut self, step: f32, color: Color) -> Self {
        self.grid = Some((step, color));
        self
    }

    pub fn axes(mut self) -> Self {
        self.axes = Some(Color::rgba(0.5, 0.5, 0.5, 0.25));
        self
    }

    pub fn axes_colored(mut self, color: Color) -> Self {
        self.axes = Some(color);
        self
    }

    pub fn snap_every(mut self, step: f32) -> Self {
        self.snap = Some(step);
        self
    }

    pub fn snap_step(&self) -> Option<f32> {
        self.snap
    }

    pub fn snap_value(&self, value: f32) -> f32 {
        match self.snap {
            Some(step) => Self::snap(value, step),
            None => value,
        }
    }

    pub fn camera(mut self, pos: Vec2, zoom: f32) -> Self {
        self.camera = Some(Camera::new(pos, zoom));
        self
    }

    pub fn no_camera(mut self) -> Self {
        self.camera = None;
        self
    }

    pub fn camera_value(&self) -> Option<Camera> {
        self.camera
    }

    pub fn background_fill(&self) -> Option<&Fill> {
        self.background.as_ref()
    }

    pub fn is_focusable(&self) -> bool {
        self.focusable
    }

    pub fn cursor_icon_value(&self) -> CursorIcon {
        self.cursor
    }

    pub fn binding_count(&self) -> usize {
        self.bindings.len()
    }

    pub fn world_to_local(world: Point, cam: Vec2, zoom: f32) -> Point {
        let zoom = if zoom.is_finite() && zoom > 0.0 {
            zoom
        } else {
            1.0
        };
        Point::new((world.x - cam.x) * zoom, (world.y - cam.y) * zoom)
    }

    pub fn local_to_world(local: Point, cam: Vec2, zoom: f32) -> Point {
        let zoom = if zoom.is_finite() && zoom > 0.0 {
            zoom
        } else {
            1.0
        };
        Point::new(cam.x + local.x / zoom, cam.y + local.y / zoom)
    }

    pub fn view_bounds(size: Size, cam: Vec2, zoom: f32) -> Rect {
        let zoom = if zoom.is_finite() && zoom > 0.0 {
            zoom
        } else {
            1.0
        };
        Rect::from_xywh(cam.x, cam.y, size.width / zoom, size.height / zoom)
    }

    pub fn fit_view(content: Rect, size: Size, padding: f32) -> (Vec2, f32) {
        if size.width <= 0.0 || size.height <= 0.0 {
            return (Vec2::new(content.left(), content.top()), 1.0);
        }
        let pad = padding.max(0.0);
        let cw = (content.size.width + pad * 2.0).max(1.0);
        let ch = (content.size.height + pad * 2.0).max(1.0);
        let zoom = (size.width / cw).min(size.height / ch).clamp(0.01, 100.0);
        let cx = content.left() + content.size.width * 0.5;
        let cy = content.top() + content.size.height * 0.5;
        let cam = Vec2::new(
            cx - size.width / (2.0 * zoom),
            cy - size.height / (2.0 * zoom),
        );
        (cam, zoom)
    }

    pub fn snap(value: f32, step: f32) -> f32 {
        if !(step > 0.0) || !value.is_finite() {
            return value;
        }
        (value / step).round() * step
    }

    pub fn snap_point(p: Point, step: f32) -> Point {
        Point::new(Self::snap(p.x, step), Self::snap(p.y, step))
    }

    pub fn lod_banded(zoom: f32, breaks: &[f32]) -> usize {
        if !(zoom > 0.0) {
            return breaks.len();
        }
        for (i, b) in breaks.iter().enumerate() {
            if zoom >= *b {
                return i;
            }
        }
        breaks.len()
    }

    pub fn show_detail(zoom: f32, world: f32, min_px: f32) -> bool {
        if !(zoom > 0.0) || !(world > 0.0) || !(min_px > 0.0) {
            return false;
        }
        world * zoom >= min_px
    }

    pub fn detail_alpha(zoom: f32, world: f32, min_px: f32, fade_px: f32) -> f32 {
        if !(zoom > 0.0) || !(world > 0.0) || !(min_px > 0.0) {
            return 0.0;
        }
        let px = world * zoom;
        if px <= min_px {
            return 0.0;
        }
        if !(fade_px > 0.0) {
            return 1.0;
        }
        ((px - min_px) / fade_px).clamp(0.0, 1.0)
    }
}

impl View for Canvas {
    fn body(&self) -> impl View + 'static {
        if let Some(track) = &self.track {
            track();
        }
        crate::views::Unit
    }

    fn is_leaf(&self) -> bool {
        true
    }

    fn focusable(&self) -> bool {
        self.focusable
    }

    fn captures_pointer(&self) -> bool {
        self.capturable
    }

    fn has_visual_state(&self) -> bool {
        true
    }

    fn cursor_icon(&self, _state: sequoia_style::VisualState) -> sequoia_input::CursorIcon {
        self.cursor
    }

    fn layout_style(&self) -> LayoutStyle {
        self.style
    }

    fn signal_dirty(&self) -> Dirty {
        Dirty::CANVAS
    }

    fn clip_self(&self) -> bool {
        self.clip && self.overflow <= 0.0
    }

    fn on_event(&self, event: &Event, ctx: &mut EventCtx) {
        if ctx.phase != EventPhase::Target {
            return;
        }
        match event {
            Event::Pointer(ev) => {
                if self.focusable
                    && let PointerEvent::Down {
                        button: PointerButton::Left,
                        ..
                    } = ev
                {
                    ctx.request_focus();
                }
                if let Some(handler) = &self.on_pointer {
                    let screen = match *ev {
                        PointerEvent::Down { pos, .. }
                        | PointerEvent::Move { pos, .. }
                        | PointerEvent::Up { pos, .. }
                        | PointerEvent::Wheel { pos, .. }
                        | PointerEvent::PenMove { pos, .. }
                        | PointerEvent::PenDown { pos, .. }
                        | PointerEvent::PenUp { pos, .. }
                        | PointerEvent::TouchDown { pos, .. }
                        | PointerEvent::TouchMove { pos, .. }
                        | PointerEvent::TouchUp { pos, .. }
                        | PointerEvent::Pinch { pos, .. } => pos,

                        _ => ctx.pos,
                    };

                    let mut local =
                        Point::new(screen.x - ctx.rect.left(), screen.y - ctx.rect.top());
                    if let Some(step) = self.snap {
                        local = Self::snap_point(local, step);
                    }
                    handler(local, ev, ctx);
                }
            }
            Event::Key(key) => {
                for b in &self.bindings {
                    if b.key == key.key && b.modifiers == key.modifiers {
                        b.fire();
                        ctx.handled();
                        return;
                    }
                }
                if let Some(handler) = &self.on_key
                    && handler(key)
                {
                    ctx.handled();
                }
            }
            Event::Ime(_) => {}
            Event::FilesHovered { .. } | Event::FilesDropped { .. } | Event::FilesCancelled => {}

            _ => {}
        }
    }

    fn paint_self(&self, ctx: &mut PaintCtx) {
        if self.clip && self.overflow > 0.0 && !ctx.rect.is_empty() {
            ctx.push_clip(ctx.rect.inflate(self.overflow, self.overflow));
        }
        let mut g = Painter::new(ctx);
        if let Some(bg) = &self.background {
            let rect = g.rect();
            g.fill(rect, bg.clone());
        }

        if let Some((step, color)) = self.grid {
            match self.camera {
                Some(cam) => {
                    let s = step * cam.zoom;
                    let off = Vec2::new(-cam.pos.x * cam.zoom, -cam.pos.y * cam.zoom);
                    g.grid_offset(s, off, color);
                }
                None => {
                    g.grid(step, color);
                }
            }
        }
        if let Some(color) = self.axes {
            let origin = match self.camera {
                Some(cam) => Self::world_to_local(Point::ZERO, cam.pos, cam.zoom),
                None => Point::new(g.size().width * 0.5, g.size().height * 0.5),
            };
            g.axes(origin, color, 1.0);
        }
        (self.draw)(&mut g);
    }
}

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

    fn vp(x: f32, y: f32, w: f32, h: f32) -> Rect {
        Rect::from_xywh(x, y, w, h)
    }

    #[test]
    fn fill_helpers_override_canvas_size() {
        let c = Canvas::new()
            .width(10.0)
            .height(20.0)
            .fill_width()
            .fill_height();
        let style = c.layout_style();
        assert_eq!(style.width, Length::Fill(1.0));
        assert_eq!(style.height, Length::Fill(1.0));
    }

    #[test]
    fn overflow_disables_exact_clip() {
        use crate::view::View;
        assert_eq!(Canvas::new().paint_overflow(), 0.0);
        assert!(Canvas::new().clip_self());
        let c = Canvas::new().allow_overflow(7.0);
        assert!((c.paint_overflow() - 7.0).abs() < 1e-6);
        assert!(!c.clip_self(), "z overflow clip idzie w paint_self");
        assert!(Canvas::new().allow_overflow(f32::NAN).clip_self());
        assert!(Canvas::new().allow_overflow(-5.0).clip_self());
        assert!(!Canvas::new().clip(false).clip_self());
    }

    #[test]
    fn camera_roundtrip_local() {
        let cam = Vec2::new(100.0, 200.0);
        let world = Point::new(150.0, 260.0);
        let local = Canvas::world_to_local(world, cam, 2.0);
        assert_eq!(local, Point::new(100.0, 120.0));
        assert_eq!(Canvas::local_to_world(local, cam, 2.0), world);
        assert_eq!(
            Canvas::local_to_world(local, cam, 0.0),
            Point::new(cam.x + local.x, cam.y + local.y)
        );
    }

    #[test]
    fn view_bounds_matches_camera() {
        let size = Size::new(200.0, 100.0);
        let cam = Vec2::new(0.0, 0.0);
        let world = Canvas::view_bounds(size, cam, 2.0);
        assert_eq!(world.size, Size::new(100.0, 50.0));
        assert!((world.left() - cam.x).abs() < 1e-4);
        assert!((world.top() - cam.y).abs() < 1e-4);
        let flat = Canvas::view_bounds(size, cam, 0.0);
        assert!((flat.size.width - 200.0).abs() < 1e-4);
    }

    #[test]
    fn fit_view_centers_content() {
        let content = vp(0.0, 0.0, 400.0, 200.0);
        let size = Size::new(800.0, 600.0);
        let (cam, zoom) = Canvas::fit_view(content, size, 0.0);
        assert_eq!(zoom, 2.0);
        let center = Canvas::world_to_local(Point::new(200.0, 100.0), cam, zoom);
        assert_eq!(center, Point::new(400.0, 300.0));
        assert_eq!(
            Canvas::fit_view(content, Size::ZERO, 0.0),
            (Vec2::new(0.0, 0.0), 1.0)
        );
    }

    #[test]
    fn snap_rounds_to_grid() {
        assert_eq!(Canvas::snap(13.0, 10.0), 10.0);
        assert_eq!(Canvas::snap(17.0, 10.0), 20.0);
        assert_eq!(Canvas::snap(-3.0, 10.0), 0.0);
        assert_eq!(Canvas::snap(13.0, 0.0), 13.0);
        assert_eq!(Canvas::snap(13.0, -5.0), 13.0);
        let p = Canvas::snap_point(Point::new(13.0, 27.0), 10.0);
        assert_eq!(p, Point::new(10.0, 30.0));
    }

    #[test]
    fn lod_bands_from_full_to_coarse() {
        let breaks = [1.0, 0.55, 0.3];
        assert_eq!(Canvas::lod_banded(2.0, &breaks), 0);
        assert_eq!(Canvas::lod_banded(1.0, &breaks), 0);
        assert_eq!(Canvas::lod_banded(0.7, &breaks), 1);
        assert_eq!(Canvas::lod_banded(0.55, &breaks), 1);
        assert_eq!(Canvas::lod_banded(0.4, &breaks), 2);
        assert_eq!(Canvas::lod_banded(0.1, &breaks), 3);
        assert_eq!(Canvas::lod_banded(0.1, &[]), 0);
        assert_eq!(Canvas::lod_banded(0.0, &breaks), 3);
        assert_eq!(Canvas::lod_banded(-1.0, &breaks), 3);
        assert_eq!(Canvas::lod_banded(f32::NAN, &breaks), 3);
    }

    #[test]
    fn show_detail_hides_subpixel_stuff() {
        assert!(Canvas::show_detail(1.0, 100.0, 6.0));
        assert!(Canvas::show_detail(0.06, 100.0, 6.0));
        assert!(!Canvas::show_detail(0.05, 100.0, 6.0));
        assert!(!Canvas::show_detail(1.0, 100.0, 0.0));
        assert!(!Canvas::show_detail(0.0, 100.0, 6.0));
        assert!(!Canvas::show_detail(f32::NAN, 100.0, 6.0));
    }

    #[test]
    fn detail_alpha_ramps_without_popping() {
        assert_eq!(Canvas::detail_alpha(0.05, 100.0, 6.0, 4.0), 0.0);
        assert_eq!(Canvas::detail_alpha(0.08, 100.0, 6.0, 4.0), 0.5);
        assert_eq!(Canvas::detail_alpha(1.0, 100.0, 6.0, 4.0), 1.0);
        assert_eq!(Canvas::detail_alpha(1.0, 100.0, 6.0, 0.0), 1.0);
        assert_eq!(Canvas::detail_alpha(0.0, 100.0, 6.0, 4.0), 0.0);
    }

    #[test]
    fn default_cursor_is_default() {
        assert_eq!(
            Canvas::new().cursor_icon_value(),
            sequoia_input::CursorIcon::Default
        );
        assert_eq!(
            Canvas::new()
                .cursor(sequoia_input::CursorIcon::Crosshair)
                .cursor_icon_value(),
            sequoia_input::CursorIcon::Crosshair
        );
    }
}