ui_controls

source of pkg::alloy::ui::painting

1// Painting: each element a canvas node under its parent's, moved by its2// position and painted again only when marked. Its edges are snapped to3// device pixels as browsers snap boxes: each rounded where it lies on the4// window, its size following, so nothing starts between two pixel rows5// while layout, hit tests and the accessibility tree keep fractions.67import std::string;8import std::vector;9import std::option;10import std::math;11import std::time;12import pkg::alloy::window;13import pkg::alloy::gpu;14import pkg::alloy::draw;1516import ui;17import tree;18import motion;19import extensions;2021// The device, surface and canvas a Ui draws with: the app's own device,22// or an engine's, which a Hud is lent while it handles an event or23// draws.24exp type Scene = struct {25    pub own: Option<Device>,26    pub lent: Option<&var Device> = ::None,27    pub surface: Option<Surface>, // None drawing offscreen or over an engine's frame28    exp canvas: Canvas,29    pub target: Option<Texture>, // what offscreen frames are drawn into30    pub over: bool = false, // drawn over an engine's frame, its background transparent31    pub unreleased: Vector<Picture> = Vector<Picture>::empty(), // freed with no device lent32};3334// The device the scene draws with.35exp fn device(self scene: &var Scene) -> &var Device {36    if (scene.lent is ::Some |&var d|) {37        return &var d;38    }39    if (scene.own is ::Some |&var d|) {40        return &var d;41    }42    panic "pkg::alloy::ui: a HUD's device used outside its calls";43}4445// Whether the scene has a device now: a HUD's only while lent one.46exp fn has_device(self scene: &Scene) -> bool => scene.lent is ::Some || scene.own is ::Some;4748// Brings the canvas up to the tree: new nodes added, moved ones moved,49// marked ones painted.50pub fn paint_all(self ui: &var Ui) {51    if (!ui.paint_pending) {52        return;53    }54    ui.paint_pending = false;55    const root = if (ui.root is ::Some |r|) r else {56        return;57    };58    ui.make_pictures();59    if (ui.scene is ::Some |&scene|) {60        const parent = scene.canvas.root();61        ui.sync_node(root, parent, true, ORIGIN, false);62        // each layer over the content, in the order they opened63        for ([..ui.layers.length()]) |k| {64            ui.sync_node(ui.layers.get(k).host.index, parent, true, ORIGIN, false);65        }66    }67    ui.snapped_scale = ui.scale;68}6970// Brings the node to the canvas, `above` its parent's residue and71// `refit` whether the parent's changed, which snaps the node again.72fn sync_node(73    self ui: &var Ui,74    index: u32,75    parent: NodeId,76    root: bool,77    above: Point,78    refit: bool79) {80    const scene = if (ui.scene is ::Some |&var s|) &var s else {81        return;82    };83    if (!ui.node(index).pending && !refit) {84        return;85    }86    // an element with a transition placed anew, which may move there87    if (ui.node(index).moving && ui.node(index).moved) {88        ui.extensions_placed(index);89    }90    const node = &var ui.node_var(index);91    node.pending = false;92    var clips = false;93    var radii = Radii::none();94    if (node.widget is ::Some |&widget|) {95        clips = widget.clips() && !node.transparent;96        if (clips) {97            radii = widget.clip_radii();98        }99    }100    if (node.draw is ::None) {101        const made = scene.canvas.add(parent);102        node.draw = ::Some(made);103        if (clips) {104            node.content = ::Some(scene.canvas.add(made));105        }106        node.moved = true;107        node.needs_paint = !node.transparent;108    }109    const id = if (node.draw is ::Some |d|) d else parent;110    // a hidden view keeps its canvas nodes and what they draw111    scene.canvas.set_hidden(id, node.hidden);112    if (node.hidden) {113        node.residue = ::None;114        return;115    }116    const x = snap(above.x, node.position.x, node.size.width, ui.scale);117    const y = snap(above.y, node.position.y, node.size.height, ui.scale);118    const at = Point { .x = x[0], .y = y[0] };119    const size = Extent { .width = x[1], .height = y[1] };120    const residue = Point { .x = x[2], .y = y[2] };121    const again = ui.snapped_scale != ui.scale || node.residue != ::Some(residue);122    node.residue = ::Some(residue);123    if (node.moved || at != node.shown_at) {124        node.moved = false;125        node.shown_at = at;126        const place = Transform::translate(at.x, at.y);127        const transform = if (root) place.then(&Transform::scale(ui.scale, ui.scale)) else place;128        scene.canvas.set_transform(id, transform);129    }130    if (size != node.shown_size) {131        node.shown_size = size;132        node.needs_paint = node.needs_paint || (!node.transparent && !node.laid_paint);133    }134    var over = Option<Paint>::None;135    if (node.needs_paint) {136        node.needs_paint = false;137        var paint = Paint::empty();138        if (node.widget is ::Some |&var widget|) {139            const focused = ui.focused == ::Some(index);140            const amounts = ui.amounts(index);141            const look = Look {142                .size = node.shown_size,143                .theme = &ui.theme,144                .hovered = node.hovered,145                .pressed = node.pressed,146                .hover = amounts[0],147                .press = amounts[1],148                .since = Duration::from_milliseconds((ui.clock_ms() -% node.changed) to u64),149                .focused = focused,150                .focus_ring = focused && ui.focus_ring,151                .marks = &ui.marks,152                .images = &ui.images.view(),153                .reduced = ui.reduced_motion(),154                .direction = node.direction155            };156            node.laid_paint = false;157            if (widget.take_paint() is ::Some |move made|) {158                paint = move made;159                node.laid_paint = true;160            } else {161                widget.paint(&look, &var paint);162            }163            // a widget whose drawing moves is painted again next frame164            if (widget.settling(look.since)) {165                ui.settling.push(index);166            }167            if (clips) {168                var above = Paint::empty();169                widget.overlay(&look, &var above);170                over = ::Some(move above);171            }172        }173        if (node.content is ::Some |content|) {174            scene.canvas.set_clip(175                id,176                ::Some(Clip {177                    .area = Rect::sized(node.shown_size.width, node.shown_size.height),178                    .radii = radii179                })180            );181            scene.canvas.paint(content, move paint);182        } else {183            scene.canvas.paint(id, move paint);184        }185    }186    const count = ui.node(index).children.length();187    for ([..count]) |k| {188        ui.sync_node(ui.node(index).children.get(k), id, false, residue, again);189    }190    // what a clipping element draws over its children, in a node after191    // theirs192    const after = &var ui.node_var(index);193    if (after.content is ::Some && after.overlay is ::None) {194        after.overlay = ::Some(scene.canvas.add(id));195    }196    if (over is ::Some |move above| && after.overlay is ::Some |o|) {197        scene.canvas.paint(o, move above);198    }199}200201// Along one axis, from the parent's residue and the node's position and202// size: its position snapped, its size from its far edge snapped, and its203// residue (where its near edge lies past the pixel it was rounded to).204fn snap(above: f32, position: f32, size: f32, scale: f32) -> [f32 : 3] {205    const start = above + position * scale;206    const near = floor(start + 0.5);207    const far = floor(start + size * scale + 0.5);208    return [near / scale, (far - near) / scale, start - near];209}210211// Makes the images not yet pictures into pictures on the canvas.212fn make_pictures(self ui: &var Ui) {213    const scene = if (ui.scene is ::Some |&var s|) &var s else {214        return;215    };216    for (ui.images.items()) |&var image| {217        if (image.alive && image.picture is ::None && image.pixels.length() != 0) {218            image.picture = ::Some(scene.canvas.picture(219                &var scene.device(),220                image.width,221                image.height,222                &image.pixels.view()223            ));224            image.pixels = Vector<u8>::empty();225        }226    }227}228229const MARK_SIZE: u64 = 32;230const MARK_BYTES: u64 = MARK_SIZE * MARK_SIZE;231232// A check mark's coverage, drawn as the mask the checkbox paints.233pub fn check_mark(canvas: &var Canvas, device: &var Device) -> Picture {234    return stroke_mark(&var canvas, &var device, &[235        Point { .x = 0.22, .y = 0.53 },236        Point { .x = 0.42, .y = 0.72 },237        Point { .x = 0.79, .y = 0.3 }238    ]);239}240241// A downward chevron's, which a Select paints.242exp fn chevron_mark(canvas: &var Canvas, device: &var Device) -> Picture {243    return stroke_mark(&var canvas, &var device, &[244        Point { .x = 0.2, .y = 0.36 },245        Point { .x = 0.5, .y = 0.66 },246        Point { .x = 0.8, .y = 0.36 }247    ]);248}249250// Chevrons to the left and to the right, a calendar's buttons.251exp fn previous_mark(canvas: &var Canvas, device: &var Device) -> Picture {252    return stroke_mark(&var canvas, &var device, &[253        Point { .x = 0.62, .y = 0.22 },254        Point { .x = 0.34, .y = 0.5 },255        Point { .x = 0.62, .y = 0.78 }256    ]);257}258259exp fn next_mark(canvas: &var Canvas, device: &var Device) -> Picture {260    return stroke_mark(&var canvas, &var device, &[261        Point { .x = 0.38, .y = 0.22 },262        Point { .x = 0.66, .y = 0.5 },263        Point { .x = 0.38, .y = 0.78 }264    ]);265}266267// The coverage of a line through the points, in a square from 0 to 1.268fn stroke_mark(canvas: &var Canvas, device: &var Device, points: &[Point]) -> Picture {269    const size = MARK_SIZE to f32;270    var coverage: [u8 : MARK_BYTES] = [0 : MARK_BYTES];271    for ([..MARK_SIZE]) |y| {272        for ([..MARK_SIZE]) |x| {273            const p = Point { .x = (x to f32 + 0.5) / size, .y = (y to f32 + 0.5) / size };274            var d: f32 = 1.0;275            for ([1..points.length()]) |k| {276                d = min(d, segment_distance(p, points[k - 1], points[k]));277            }278            const c = clamp((0.075 - d) * size + 0.5, 0.0, 1.0);279            coverage[y * MARK_SIZE + x] = (c * 255.0) to u8;280        }281    }282    return canvas.mask(&var device, MARK_SIZE to u32, MARK_SIZE to u32, &coverage);283}284285fn segment_distance(p: Point, a: Point, b: Point) -> f32 {286    const dx = b.x - a.x;287    const dy = b.y - a.y;288    const t = clamp(((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy), 0.0, 1.0);289    const ex = p.x - a.x - t * dx;290    const ey = p.y - a.y - t * dy;291    return sqrt(ex * ex + ey * ey);292}