Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Canvas, images and QR codes

A canvas is the surface an application draws on itself, an image shows a decoded picture, a QR code is a payload drawn as modules of whole device pixels, and an icon is one outline at whatever size its box is.

By the end of this chapter you can draw with paths, strokes, gradients and images on a canvas, hear the pointer and the keyboard on it, place a picture with one of four fit modes, put a scannable code in a dialog, and size an icon from the stylesheet.

The showcase's Drawing screen: a card of paths, strokes and a gradient, a pointer grid, a plan to drag and zoom, the image widget at four fits, the same picture decoded from five formats, and a sticky note with a caret

The showcase's Drawing screen. The drawings are a canvas each, the four photographs are image widgets, and each card links back to its section here.

canvas

An immediate-mode drawing surface: a box whose painter is handed the frame, translated to the box’s content corner and clipped to it.

canvas id="plot" class="chart"
import dev.goldberry.widgets.core.canvas.Canvas;

new Canvas((frame, size) -> {
    frame.fillRect(0, 0, size.width(), size.height() / 2, 0xFF88C0D0);
}, Attributes.NONE.id("plot").classes("chart"));

The painter is Java.“ with:

The painter is Java, so markup names one rather than writing it. painter= and input= name objects the application bound in its Named registry, as canvas3d renderer= does:

var named = Named.strict().bind("app.revenue", (Painter) chart::paint);

A canvas that names neither is a styled, sized surface that draws nothing.

The painter

A Painter is paint(Frame frame, LogicalSize size). The frame’s origin is the canvas’s top-left and the clip is its content box, so a painter cannot escape its bounds. The toolkit brackets the call in save and restore, so a painter may set a clip or a transform and leave it set. It runs on the UI thread inside the frame, so it must not block and must not keep the frame.

var hill = Path.builder()
        .moveTo(0, height)
        .lineTo(0, height * 0.55)
        .cubicTo(width * 0.25, height * 0.2, width * 0.45, height * 0.9, width * 0.6, height * 0.5)
        .lineTo(width, height)
        .close()
        .build();
frame.fillPath(hill, Gradient.fade(0, height * 0.2, 0, height, CssColor.fade(ink, 0.55)));
frame.strokePath(Path.circle(cx, cy, 14), Stroke.round(2), accent);
frame.strokePath(Path.line(0, y, width, y), Stroke.of(1).dashed(4, 4), muted);
frame.drawImage(logo, 16, 16);

Frame fills and strokes a Path, with a colour or a Gradient, draws an Image at its natural size or scaled and faded, clips with clipTo, and transforms with transform, concat and resetTransform. Path has a builder with moveTo, lineTo, quadTo, cubicTo, arcTo, close and append, and factories line, polyline, rect, roundRect, ellipse, circle and arc. A path is a value, so path.rotated(radians, cx, cy), translated, scaled and transformed(affine) make a turned copy, and frame.concat composes a transform onto the one the canvas already has. A Stroke is of(width) or round(width), with cap, join, dashed(on, off) and dash(Dash). The toolkit computes a dash itself and does not ask the rasterizer for one.

A three-parameter painter is a StyledPainter and is handed a CanvasStyle: the node’s resolved font and ink, this frame’s nowMillis, and reducedMotion. So canvas { color: var(--gb-text) } reaches the drawing.

new Canvas((frame, size, style) -> {
    Paragraph.of(style.font(), "Revenue").paint(frame, 0, 0, size.width(), style.ink());
});

A canvas is painted once and left there. animating asks for the next frame for as long as a predicate over the same CanvasStyle says so:

new Canvas(floor::paint).animating(style -> style.nowMillis() - mounted < SETTLE_MILLIS);

A picture cut in nine is drawn with drawNineSlice: its corners whole, its edges and middle stretched or tiled between them, the way a stylesheet’s border-image draws a box’s edge. The cut is a NinePatch, made once:

private static final NinePatch PLATE = NinePatch.of(22, 64, 22, 64);   // top, right, bottom, left

frame.drawNineSlice(namePlate, PLATE, 0, 0, size.width(), 40);
frame.drawNineSlice(namePlate, PLATE.withWidths(8, 24, 8, 24).withRepeat(Repeat.ROUND, Repeat.STRETCH),
        0, 48, size.width(), 40);

The slice lines are in the picture’s pixels, and atDensity(2) reads them in a @2x picture’s. Each side is drawn at its slice’s size unless withWidths says otherwise. When two opposite sides do not fit, all four shrink by the same factor, so a corner keeps its shape. withFill(false) leaves the middle out, and withRepeat tiles the edges and the middle, at their own scale (REPEAT) or a whole number of times (ROUND). Every seam is on a whole device pixel, so nothing behind shows between a corner and its edge.

Input

An Input beside the painter makes the canvas hear the pointer and the keyboard. The events are the toolkit’s own PointerEvent and KeyEvent, and event.content() is measured from the corner the painter draws at.

new Canvas(board::paint, new Input() {
    @Override
    public void onPointer(PointerEvent event) {
        var at = event.content();
        switch (event.kind()) {
            case PRESSED -> board.beginDrag(at.x(), at.y());
            case MOVED -> board.dragTo(at.x(), at.y());
            case WHEEL -> board.zoom(event.deltaY(), at.x(), at.y());
            default -> { }
        }
    }
});

A drag that leaves the canvas keeps reporting, because the router captures the pointer on press. event.consume() keeps a wheel from scrolling the pane the canvas sits in. onKey, onText and onPreedit arrive when the canvas has focus, and wantsText() turns the platform’s input method on for a canvas that holds an Editor. accessibleName() names the figure for a reader.

path.contains(x, y) says whether a point is inside a path’s fill, by the nonzero rule a fill uses, or path.contains(x, y, true) for evenodd. A board hit-tests what it drew with it: a click lands in a note’s rounded outline, not its bounding box, and not in the hole of a ring. A box with a clip-path: path(…) is hit by the pointer the same way.

Widgets over the drawing

A painted rectangle has no focus ring, no name a reader can announce and no place in the Tab order. Where something drawn has to have all three, such as the events on a week grid, overlay places a real widget over it:

new Canvas(week::paint, week).overlay(size -> week.layout(size).blocks().stream()
        .map(block -> new Positioned(
                new Pressable(block.title(), () -> open(block.event())).keyed(block.event().id()),
                block.rect()
        ))
        .toList());

The function is handed the size of the content box, the rectangle the painter is told about, and answers with Positioned widgets, each at a rectangle in the painter’s own coordinates. Each widget fills its rectangle. They are ordinary widgets inside the canvas’s box:

  • drawn over the painting and clipped to the content box, and scrolled with the canvas when a scroll moves it;
  • hit-tested before the painting, so a press on one goes to it and not to the canvas’s Input, and a press beside it reaches Input as before;
  • focusable in the order of the list, so a list in visual order is a Tab order in visual order;
  • listed in the semantics tree under the canvas, with their own roles and names.

The list is asked for again whenever the content box changes size and whenever the canvas is rebuilt. A widget whose key comes back keeps its element, and with it its focus and its state, so key each one by what it shows. The widgets arrive one frame after the canvas is first laid out, because the size they are placed by is the one that frame measured.

A positioned widget can be draggable like any other, and the canvas can be a drop target: an event dragged to another day lands on the canvas with the point in the painter’s coordinates. See Dragging between widgets.

Attributes

AttributeTypeDefaultWhat it does
idstringnoneThe canvas’s id
classstringnoneClasses on its box
painternamenoneA Painter or StyledPainter the application bound
inputnamenoneAn Input the application bound

Styling

The CSS type is canvas. It is a box first: background, border, border-radius, padding, width, height and every layout property are the stylesheet’s, and the painter draws inside the padding. A canvas has no size of its own, so one in a row with nothing to size it is zero wide. cursor works as on any box. Its role is figure.

isolation: isolate keeps what the painter drew: the canvas becomes a group with a raster of its own, and while nothing about it changes later frames copy the raster instead of calling the painter. An animating canvas is drawn on every frame either way.

The widgets of an overlay sit in a canvas-layer covering the content box, each in a canvas-item at its rectangle.

Keyboard

A canvas is focusable exactly when it has an Input whose focusable() is true. Keys reach onKey. A canvas with no input is not a Tab stop.

The widgets of an overlay are Tab stops of their own, after the canvas and in the order of the list.

image

A picture, loaded off the frame on a virtual thread and drawn at its natural size until a stylesheet says otherwise.

Three images in a column, each drawn as its alt text because nothing supplies the pixelsThree images in a column, each drawn as its alt text because nothing supplies the pixels

With no image source bound, each image is its alt text.

column {
    image src="photos/harbour.jpg" alt="The harbour at dusk" fit="cover"
    image srcset="classpath:logo.png 1x, classpath:logo@2x.png 2x" alt="Goldberry"
    image src="classpath:divider.png" decorative=#true
}
import dev.goldberry.widgets.core.image.ImageView;
import dev.goldberry.widgets.core.image.ImageSource;
import dev.goldberry.widgets.core.image.Fit;

new ImageView(ImageSource.file(path), "The harbour at dusk").fit(Fit.COVER);
new ImageView(ImageSource.resource(App.class, "logo.png"), "Goldberry").variant(2, ImageSource.resource(App.class, "logo@2x.png"));
ImageView.decorative(ImageSource.resource(App.class, "divider.png"));

An ImageSource is a file(path), a resource(anchor, name), bytes(data), an Image already decoded with of(image), or supplied(key, supplier) for a thumbnail generator or an HTTP fetch run on a virtual thread. The shared loader decodes each source once per process, so ten thumbnails of one file decode once. While the pixels are on their way the box carries .loading. When they cannot be decoded it carries .error and shows a broken-image icon with the alt text.

The record is ImageView. The Java name differs from the markup name because Image is the decoded value in dev.goldberry.image, which an application holds, pastes and encodes without a widget. The format comes from the bytes: PNG, JPEG, QOI, WebP and GIF decode, and an animated GIF decodes to its first frame. SVG decodes with goldberry-vector on the module path and its native library for the platform. The image has the document’s natural dimensions. A larger box or a higher display scale requests a raster at the new device size. This also applies to CSS url() images and to images in HTML and Markdown. In these contexts currentColor defaults to black.

Important

An image needs alt text or decorative=#true, and is refused when it has neither. A picture a reader is told is a figure and nothing more is worse than one they are not told about.

Fit modes

fitWhat is drawn
containThe whole image, as large as fits, letterboxed. The default
coverThe box filled, the image cropped to the box’s shape
fillThe box filled, the image stretched to its shape
noneThe image at its natural size, centred, cropped if larger

The image is always centred. cover crops rather than clips, so it needs no overflow: hidden and cannot paint over a neighbour.

Attributes

AttributeTypeDefaultWhat it does
srcstringnoneOne path. classpath: names a resource on the application’s class loader. Exactly one of src and srcset is required
srcsetstringnoneSeveral paths with scales: logo.png 1x, logo@2x.png 2x
altstring""What the picture shows, for a reader. Required unless decorative
decorativeboolean#falseThe picture shows nothing a reader needs, and leaves the semantics
fitcontain, cover, fill, nonecontainHow the picture fills a box of another shape. A misspelt value is refused
idstringnoneThe image’s id
classstringnoneClasses on its box

Styling

The CSS type is image. With no width and height the box is the picture’s natural size, one image pixel per device pixel, and max-width shrinks it in proportion. With one of them the other follows the picture’s shape. With both, fit decides. The classes loading and error are added while a load stands there, and image-alt is the part that shows the alt text on failure.

Keyboard

None. An image is not focusable.

Vector animations

A Lottie document, the format of a Telegram tgs sticker, is a description rather than a picture: shapes, colours and easing curves. VectorAnimation reads one, gzipped or plain JSON, and draws it at whatever size it is asked for. AnimationView plays one on the frame loop, the way image shows a picture.

import dev.goldberry.image.anim.VectorAnimation;
import dev.goldberry.widgets.core.image.AnimationView;

var sticker = VectorAnimation.of(Files.readAllBytes(path));       // .tgs or .json
new AnimationView(sticker, "🎉");
AnimationView.decorative(sticker.loops(1)).autoplay(false);

Image still = sticker.imageAt(500, 128, 128);                      // half a second in
new Canvas((frame, size) -> sticker.paint(frame, elapsed, 0, 0, size.width(), size.height()));

The view starts from the first frame when it is first drawn, and asks for frames only while the animation moves. With autoplay(false), or when the platform says its user wants less movement, it shows the first frame and the loop stays idle. An animation plays for ever unless loops(n) says otherwise, and then holds its last frame. Its CSS type is image, it is sized like an image (the animation’s canvas in logical pixels until a stylesheet says otherwise), and it takes the same Fit and the same alt-text rule.

What is drawn is the subset Telegram allows in a sticker, and somewhat more: shape, null, solid and precomp layers with parents; groups and their transforms; rectangles, ellipses, stars, polygons and paths; flat and gradient fills and strokes, dashed or not; trims, mattes and masks; held, eased and curved keyframes, and paths that change shape. A document with an expression or an image layer in it is refused with an ImageDecodeException, as bytes that are not a Lottie document are. Anything else unknown, such as a text layer or a layer effect, is passed over, and the rest is drawn.

There is no markup node for an animation yet: the document is bytes the application has, not a path a page names.

After the paragraph that introduces AnimationView:

AnimationView plays any MovingPicture, the interface VectorAnimation implements. goldberry-media’s VideoAnimation is the other one: a WebM sticker, drawn with its transparency (see the media chapter).

svg-view

Use svg-view for a diagram or icon whose ink follows the surrounding text. This leaf takes its fill from the view’s CSS color. Changing the theme or a :hover rule updates the drawing. Colours written directly in the SVG keep their values.

A leaf silhouette drawn from an inline SVGA leaf silhouette drawn from an inline SVG

An inline SVG whose fill follows the view's text colour.

svg-view alt="Leaf" "<svg viewBox='0 0 48 48'><path fill='currentColor' d='M6 41Q5 9 41 6Q42 40 11 37Z'/></svg>"

A src can name a file or a classpath resource. Supply either the inline document or the source. Give each figure alt text describing its content. Use decorative=#true when the surrounding text already conveys it.

svg-view src="classpath:/art/hills.svg" alt="Sun over two hills" fit="contain"
import dev.goldberry.vector.view.SvgSource;
import dev.goldberry.vector.view.SvgView;

var hills = new SvgView(SvgSource.resource(App.class, "/art/hills.svg"), "Sun over two hills");

If the resource belongs to a package in a named module, open that package to dev.goldberry.vector for the Java anchor. The classpath: form uses the class loader, which needs that package to be open unconditionally.

Add dev.goldberry:goldberry-vector and its matching natives-<target> classifier to the application. For example, on Linux x64 the classifier is natives-linux-x64. A modular application requires dev.goldberry.vector and grants it native access with --enable-native-access=dev.goldberry.vector. Add VectorStyles.stylesheet() beside the controls’ stylesheets to style the loading placeholder and the error icon and alt text.

A Gradle build using the Goldberry BOM can declare the Linux x64 dependencies together.

implementation 'dev.goldberry:goldberry-vector'
runtimeOnly 'dev.goldberry:goldberry-vector::natives-linux-x64'

CSS width or height sets one dimension and the other follows the document’s proportions. With both set, contain fits the whole drawing, cover crops to the box, none keeps the natural size and fill gives the document that viewport, respecting its own preserveAspectRatio.

Paths, gradients, clips, masks, references within the document and embedded PNG or JPEG data URIs are supported. Convert lettering to paths when it must appear in the artwork. SVG text, external references, scripts and animation are unsupported. Documents are limited to 16 MiB and a raster to 8192 pixels per side and 64 million pixels overall.

qr-code

A QR code for a payload, drawn in modules of whole device pixels so a phone camera reads it at any scale.

A QR code for goldberry.dev with a quiet zone around itA QR code for goldberry.dev with a quiet zone around it

A code at error-correction level M.

qr-code value="https://goldberry.dev" level="M" quiet-zone=4 name="Scan to open goldberry.dev"
import dev.goldberry.widgets.core.qrcode.QrCode;
import dev.goldberry.image.qr.Level;

new QrCode("https://goldberry.dev").level(Level.H).withAttributes(Attributes.NONE.name("Scan to open goldberry.dev"));
new QrCode(link, Level.L, 4, Attributes.NONE.id("qr-low"));

The encoder is the toolkit’s own, in dev.goldberry.image.qr beside the image codecs, and QrEncoder.encode(payload, level) returns the same QrMatrix with no widget. The widget divides its box into a whole number of device pixels per module and turns the remainder into margin, so what changes between 100 % and 200 % is how many pixels a module is, never whether its edge lands on one. A box too small for one pixel per module draws nothing. A payload no version holds is refused when the widget is built. Rebuilding with the same payload does not re-encode.

The payload is not part of the accessible name, because a sign-in token is a credential. Give the widget a name that says what the code is for.

Attributes

AttributeTypeDefaultWhat it does
valuestring""The payload, encoded as UTF-8
levelL, M, Q, HMHow much of the code may be destroyed and still read. Anything else falls back to M
quiet-zonenumber4The light margin around the code, in modules. Four is the standard’s
namestringnoneWhat a reader is told the code is
idstringnoneThe code’s id
classstringnoneClasses on its box

Styling

The CSS type is qr-code. The default sheet makes it 160 by 160 with flex-shrink: 0, and an application sets width and height like anything else. The ink is --gb-qr-ink and the paper is --gb-qr-paper, and both are the same near-black on white in the dark theme as in the light one, because many scanners will not read an inverted code. The quiet zone is painted in the paper colour.

Keyboard

None. A code is a figure.

icon

One icon on its own, as big as the stylesheet makes its box and in the box’s colour.

The cloud-upload icon at three sizes, 11, 16 and 24 pixels, and a circle-alert icon in the warning colourThe cloud-upload icon at three sizes, 11, 16 and 24 pixels, and a circle-alert icon in the warning colour

One icon at three sizes the stylesheet chose, and one coloured.

row class="icon-sizes" {
  icon "cloud-upload" class="small"
  icon "cloud-upload"
  icon "cloud-upload" class="large"
  icon "circle-alert" class="warn" name="Not signed in"
}
import dev.goldberry.widgets.core.icon.IconView;

new IconView("cloud-upload").styled("small");
new IconView(Icon.bundled("circle-alert", 24)).withAttributes(Attributes.NONE.classes("warn").name("Not signed in"));
icon.small { width: 11px; height: 11px; }
icon.large { width: 24px; height: 24px; }
icon.warn { color: var(--gb-warning); }

Inside a button an icon is drawn at the size it was built at. Here the box decides: width and height, 16 by default, and the outline is scaled to the smaller of the two and centred along the other. The bundled set is drawn on a 24-unit grid with a 2-unit stroke, and the stroke scales with it, so an 11 px icon is the same drawing as a 24 px one, thinner. width: 1em; height: 1em sizes an icon to the text beside it. Nothing native is held, so a document reloaded on every keystroke builds nothing that has to be closed.

The argument is looked up in the application’s Icons registry first, so icon "home" draws whatever the application registered as home, and then in the bundled set. A name that neither has is an empty box of the same size with the class missing, rather than an error. A stylesheet may draw a fallback on it:

icon.missing { background: currentColor; border-radius: 9999px; width: 6px; height: 6px; }

In Java, Icon.find(name, size) is the same lookup for a name that comes from outside the program. It returns an Optional<Icon>, where Icon.bundled throws.

Attributes

AttributeTypeDefaultWhat it does
argumentstringnoneThe icon’s name: a registered one, or one from the bundled set
namestringnoneWhat a reader is told. Without one the icon is decorative
id, classstringThe usual

Styling

The CSS type is icon, with the class missing when the name found nothing. The default sheet makes it 16 by 16 with flex-shrink: 0. The stroke is the box’s color, which it inherits like text.

Keyboard

None. A named icon is a figure, and an unnamed one is decoration.