Text, fonts and icons
Two embedded typefaces, an optional emoji face, bundled stroked icons, and an image that is a value: what an application needs from the text and picture stack, one sample each.
By the end of this chapter you can open a font and measure a string, ship a face of your own, name an icon from markup, draw emoji, put a caret on a canvas, and decode, scale, copy and encode an image.
try (var fonts = Fonts.bundled()) {
Font body = fonts.of(BundledFont.UI, 13);
double width = body.widthOf("Goldberry"); // what layout will ask
body.draw(frame, 16, 16 + body.ascent(), "Goldberry", 0xFFECEFF4);
}
The y of a draw is the baseline. The top of a line is
baseline - ascent().
Faces, fonts and the book
A FontFace is a typeface parsed once. A Font is one size of it. Fonts
is the book that caches both, keyed by family, weight and style, then by
size.
try (var face = FontFace.bundled(BundledFont.UI);
var title = Font.on(face, 24);
var body = Font.on(face, 16)) {
// two sizes, one parse of Inter
}
A second size over a shared face costs microseconds and no memory. The face
must outlive every font over it. Font.bundled(BundledFont.UI, 16) parses a
face of its own, which is right for exactly one size.
Shaping runs in the face’s own design units and the size is applied once, in
the font matrix, so a shaped run is correct at every size. Font exists to
make applying it twice unrepresentable.
A running application does not open a book of its own. The launcher opens one
and hands it to the renderer, and a widget asks Paints.Context.font(style)
for the font its resolved typography names. A canvas that measures its own
labels asks host.fonts().
The bundled faces
BundledFont | File | Family | Weight | Style |
|---|---|---|---|---|
UI | Inter variable | Inter | 400 | upright |
UI_STRONG | Inter SemiBold | Inter | 600 | upright |
UI_ITALIC | Inter Italic | Inter | 400 | italic |
UI_STRONG_ITALIC | Inter SemiBold Italic | Inter | 600 | italic |
CODE | JetBrains Mono | JetBrains Mono | 400 | upright |
EMOJI | Noto Color Emoji | Noto Color Emoji | 400 | upright |
A weight is a face and so is an italic: Inter’s italic is drawn, not
sheared, and font-weight: 600; font-style: italic resolves to a file rather
than to the nearer of three.
A weight is a CSS number, though, and a stylesheet may write any of them: the
face is chosen by CSS’s own nearest-weight rule over the faces the family has,
so over Inter’s two font-weight: 500 is the 400 and bold (700) is the 600,
as a browser draws them.
There is no variable wght axis: Inter’s 500 is not instanced from its
variable file, and an application that wants a 500 ships one. A glyph
neither family has draws .notdef: there is no fallback cascade beyond the
emoji slot, so font-family: Inter, sans-serif keeps the first name only.
Shipping a face
@Override public List<FontSource> fonts() {
return List.of(
forum(400, "fonts/Forum-Regular.ttf"),
forum(700, "fonts/Forum-Bold.ttf")
);
}
private static FontSource forum(int weight, String file) {
return FontSource.stream("Forum", weight, BundledFont.Style.UPRIGHT, () -> MyApp.class.getResourceAsStream(file));
}
Application.fonts() is read once, before start, when the window’s book
opens. A face named here reaches the cascade, paragraph layout, a field’s
caret and the glyph cache together, and a stylesheet names it with
font-family: Forum. The bundled families are searched first, so a file
called Inter cannot replace the face the design system was drawn against.
The weight is any CSS number, 1 to 1000. A family shipped at 500, 600, 700
and 800 gives each of them to the stylesheet that asks, and a weight it does
not have is the nearest one it does, by the rule Inter answers by. The two
named weights, Weight.REGULAR and Weight.SEMI_BOLD, are 400 and 600.
Read the file with your own code. The supplier in FontSource.stream is
the application’s lambda, so it reads a resource with the application’s own
access, and a modular application opens nothing for it.
FontSource.resource(family, weight, style, MyApp.class, name) reads it with
the toolkit’s module instead, and on the module path that needs the package
holding the file opened to dev.goldberry.core (opens com.example.app.fonts to dev.goldberry.core; for fonts/ beside com.example.app.MyApp). A
resource directory is a package of its own, so it is that package, not the
class’s, that has to be opened.
A missing file is said at start. The book looks for every file as it
opens, before the window shows: a resource or a stream is opened and closed
unread. One that is not there is a warning naming the face and why, a
package nobody opened told apart from a file that is missing, and text in it
is drawn in the UI face. Nothing is parsed until something is drawn in the
face. fonts.unreadable() lists them, for an application that would rather
refuse to start.
FontSource.of(family, weight, style, bytes) takes bytes already in hand.
A stylesheet may ship a face too, with @font-face:
@font-face {
font-family: "Forum";
src: url("fonts/Forum-Regular.ttf") format("truetype");
font-weight: 400;
}
A renderer adds the faces its sheets name to the window’s book when it is
built, as if Application.fonts() had answered them, and font-family: Forum then finds them. In a sheet read with Stylesheet.resource, src is a
file beside the sheet; otherwise it is a classpath: address or a file path.
TrueType and OpenType files are read; local() and WOFF are passed over for
the next source in the list. font-weight is a number, normal or bold,
and font-style is normal or italic.
Fallback faces
@Override public List<FallbackSource> fallbacks() {
return List.of(
FallbackSource.of(face("Noto Sans SC", "fonts/NotoSansSC-Regular.otf"),
UnicodeScript.HAN, UnicodeScript.HIRAGANA, UnicodeScript.KATAKANA
),
FallbackSource.of(face("Noto Sans Arabic", "fonts/NotoSansArabic-Regular.ttf"),
UnicodeScript.ARABIC
),
FallbackSource.of(face("Noto Sans Math", "fonts/NotoSansMath-Regular.ttf"))
);
}
private static FontSource face(String family, String file) {
return FontSource.stream(family, 400, BundledFont.Style.UPRIGHT, () -> MyApp.class.getResourceAsStream(file));
}
A name typed in a script the design system’s faces lack is drawn in the
first fallback that has its characters, at the size and on the line of the
text around it. Without one it is a row of .notdef boxes. A fallback is not
a family a stylesheet names: font-family: Inter stays Inter for every
character Inter has, and only the characters it lacks look further.
The face’s own cmap decides. Every face’s characters are read once, when
it opens, and a paragraph checks its text against them before shaping. Text
the face covers is shaped exactly as it was, and a paragraph with no
uncovered character never opens a fallback. The scripts after the source are
a hint read before the face is opened, so an Arabic name does not open a Han
face to learn that it has no Arabic. Characters in no script of their own,
such as punctuation, digits and the mathematical letters, are never ruled out
by a hint, and a source with no scripts is opened for anything.
A run stays whole. A letter and the marks on it go to one face, and a word of Arabic or a name in Han is shaped as one run, spaces included, so it joins and spaces as it should. Right-to-left text is still shaped in logical order and drawn mirrored, as in any other face.
The line is the font’s. Line height, ascent and underlines are the font’s that the stylesheet chose. A fallback glyph that is taller may reach past the line box, as it can in a browser. Carets, selection and clicks work across a fallback run as across any other.
Order, weight and style. Fallbacks are searched in the order given. Several
sources with one family name are one fallback at several weights, and bold
text takes the nearest weight by the rule font-family uses. Nothing is
emboldened or slanted by the toolkit: a family shipped only in regular draws
bold text in regular. An artifact can bring fallback faces as a
dev.goldberry.assets.FallbackFont provider, searched after the
application’s. A font collection (.ttc) is not read: ship one face of it.
A book opened by hand takes the list as Fonts.bundled(shipped, fallbacks).
Paragraphs
A paragraph has a base direction, and text in a right-to-left script is split
into runs that each read their own way, placed in reading order on every
line. Paragraph.of(font, text) takes each paragraph’s direction from its
first letter that has one; a widget’s paragraph takes its style’s direction
and unicode-bidi.
var label = Paragraph.of(font, "שלום, world", 0, 0, Directionality.RTL);
double x = label.caretX(line.start(), line.end(), offset); // where the caret is drawn
List<Stretch> lit = label.stretchesOf(line.start(), line.end(), from, to);
A width is the same whichever way the runs are placed, so widthBetween
sizes a box; where a caret or a highlight goes on a line is caretX and
stretchesOf, and offsetAt is the caret nearest a click.
Text scale
Text scales from 90% to 150% without the boxes around it moving, which is the condition every control is built to survive.
renderer.textScale(1.5); // clamped to WidgetRenderer.MINIMUM_TEXT_SCALE..MAXIMUM_TEXT_SCALE
The factor is applied where a resolved style becomes a Font, nowhere in
the cascade. It is a switch on WidgetRenderer, which the low-level path
builds itself. The launcher does not expose it.
Icons
row {
button icon="plus" press="app.create" "New"
button icon="palette" press="app.toggle-theme" "Switch"
}
@Override public void start(Host host) {
plus = Icon.bundled("plus", Icons.SLOT); // 16, a button's lead slot
icons = Icons.strict().bind("plus", plus).bind("palette", Icon.bundled("palette", Icons.SLOT));
}
The bundled icon set’s 1,870 icons ship in goldberry-core as path data on a 24 by 24 grid.
They are strokes, not fills: 2 px round-capped outlines, so an Icon carries
a stroke width as well as a shape, and it is built pre-scaled to one size so
nothing is transformed at draw time.
BundledAssets.iconNames() lists the set, and Icon.of(name, pathData, size)
builds one from your own SVG path data on the same grid. Icon.bundled throws
for a name the set does not have. Icon.find(name, size) returns an
Optional<Icon> instead, for a name that comes from outside the program.
Markup names an icon and never builds one. icon="plus" resolves against
the Icons registry the application owns, because a document reloaded on
every keystroke would otherwise rebuild one per reload. An Icon is an
immutable value, and its close() does nothing.
An icon is tinted by color, like text. Inside a widget that takes icon= it is
drawn at the size it was built at. The standalone icon
node is the other way round: the stylesheet sizes its box and the outline is
scaled to fit, so icon "plus" at 11 px and at 24 px is one line of CSS each.
It looks the name up in the registry first and then in the bundled set, so it
needs no registration. An icon-only button has an empty label and needs
name= for its accessible name.
Emoji
implementation 'dev.goldberry:goldberry-emoji:<version>'
Noto Color Emoji ships as its own artifact, because five megabytes of
paint graphs should not be inherited by an application that never draws one.
With the module on the path, nothing else changes: the itemizer splits an
emoji sequence out of a line and shapes it in the emoji face, and the rest of
the line stays in the family the cascade chose.
It is the COLRv1 build, drawn from its paint graphs, so an emoji is as sharp
at 400% as at 100%.
A stylesheet reaches the face by name as font-family: "Noto Color Emoji".
Without the module, Font.bundled(BundledFont.EMOJI, size) throws a
MissingEmojiFontException whose message names the artifact, and
BundledAssets.hasEmojiFont() answers false.
Selection and editing
text-input and text-area are controls. Underneath them is an Editor
that is none of those things, and it is reachable on its own: a caret in a
sticky on a board, a label on a shape, anything drawn on a canvas.
var editor = new Editor(font).multiline(true).wrapWidth(240).clipboard(host.clipboard());
new Canvas((frame, size) -> editor.paint(frame, 8, 8, Editor.Ink.of(ink, selection), focused),
new Input() {
@Override public boolean wantsText() { return true; } // turns the keyboard on
@Override public void onKey(KeyEvent e) { if (editor.onKey(e)) e.consume(); }
@Override public void onText(TextEvent e) { if (editor.onText(e.text())) e.consume(); }
@Override public void onPointer(PointerEvent e) {
if (e.kind() == PointerEvent.Kind.PRESSED) {
editor.pointerAt(e.content().x() - 8, e.content().y() - 8, false, e.clickCount());
}
}
});
wantsText() is not optional. The platform produces no characters until
something says it is being typed into, so an editor that has not said so gets
arrow keys and nothing else.
The editor is text-input’s key map, key for key: arrows and Ctrl+arrows,
Home and End on the visual line, Shift to extend, undo and redo with a
typing run folded into one step, and cut, copy and paste. A key it does not
handle is not consumed, so Tab still moves focus. TextGeometry beside it
answers where a caret is on a wrapped paragraph, what a click landed on, what
Up means when lines differ in length, and what shape a selection is across
a break. An input method’s composition arrives through onPreedit and is
drawn beside the document, not in it.
A text-area is also an editor. gutter=#true numbers the hard lines at
the positions the wrap put them, and .onEdit(...) and .edit(...) hand a
shortcut the caret as well as the text.
Tell an editor how tall its box is with viewportHeight and it scrolls: a
keystroke, a click or a drag that carries the caret past the box’s edge moves the
text by the least that shows the caret’s line, and paint draws from there,
clipped to the box. A wheel is scrollBy(dy), which answers whether anything
moved. Points stay in the text’s own space, so a pointer handler adds
scrollTop() to the pointer’s y before calling pointerAt.
(For book/src/guide/text.md, ## Selection and editing.)
Text can carry marks. A MarkedText is a string and its marks, each a kind
over a range; MarkedEdit is the same value with a caret, the marked twin of
TextEdit. Hand the canvas Editor a MarkStyles and it shapes marked words
in their own fonts and takes the formatting keys; without one it keeps the
marks and draws them as plain text.
Images
Image logo = Image.decode(Files.readAllBytes(file)); // or Image.decode(file)
frame.drawImage(logo, 16, 16); // natural size
frame.drawImage(logo, 16, 96, 240, 120, 0.4); // scaled, and faded
byte[] png = logo.scaled(64, 64).encodePng();
Encoded bytes become an Image: PNG, JPEG and QOI through the rasterizer’s
codecs, WebP through the native library, and GIF through a decoder written in Java. The
format comes from the bytes, never from a file name: ImageFormat.of(bytes)
says which. Image.decodeAnimation(bytes) returns every frame of an animated
GIF or WebP with its delay; decode returns the first.
An image has nothing to close. The decoder copies its pixels into a
Java-owned buffer before decode returns, so an image is a value to keep in
a field, a record or a cache. Natural size is one image pixel per device
pixel, so a 96 by 64 image is 96 logical points wide at 100% and 48 at 200%.
encodePng() writes one back out in java.base, and encodeWebp(quality)
through the native library.
In markup an image node takes src=, srcset=, alt=, decorative= and
fit=, and is in Canvas, images and QR codes.
Image.decodeInto decodes into memory the caller owns instead, such as a GPU
transfer buffer or an atlas page being built, and returns the size. The
function is asked for the memory once the size is known. ChannelOrder.RGBA
swaps red and blue in the same pass; BGRA is an image’s own order. Both are
premultiplied.
var size = Image.decodeInto(bytes, ChannelOrder.RGBA,
decoded -> PixelTarget.packed(transfer.map(decoded), decoded.width()));
The clipboard
Image.fromClipboard(host.clipboard()).ifPresent(board::add); // Ctrl+V
picture.toClipboard(host.clipboard()); // Ctrl+C
Underneath is Clipboard’s other half, has, read and write over a
MIME type. One write offers several types in order, so pasting into your
own application keeps a document’s format and pasting into a chat gets a
picture. A write is an offer: the platform asks for the bytes when somebody
pastes.
Subscription watching = host.clipboard().onChange(() -> paste.disabled(!host.clipboard().hasText()));
onChange says that the clipboard changed, whoever changed it, your own
copies included. It does not say what to: ask hasText() or types(). A
platform that cannot tell never calls it.
A picture with no window
byte[] png = Offscreen.of(1200, 900) // physical pixels
.scale(1.5f)
.stylesheets(Controls.stylesheets(Theme.NORD_DARK))
.render(new DocumentPreview(document)) // or .paint(painter)
.encodePng();
Offscreen runs the window’s own sequence with no display, no windowing
layer and no compositor: mount, lay out, tell each widget what size it came out as,
advance a virtual clock past the arrival transitions, and paint what settled.
Two renders of one document are the same bytes. It is what
Testing an application builds on.
Words in the user’s language
dev.goldberry.i18n has CLDR’s plural rules for every locale and ICU’s
message syntax, so a count reads right in any language:
var files = IcuMessage.parse(
"{count, plural, one {# файл} few {# файла} many {# файлов} other {# файла}}"
);
files.format(Locale.forLanguageTag("ru"), Map.of("count", 21)); // "21 файл"
PluralRules.of(Locale.ENGLISH, PluralType.ORDINAL).select(22); // TWO: "22nd"
A message takes {name}, {name, number}, plural and selectordinal
with =0 cases, offset: and #, and select. Every plural and select
needs an other case, and a message without one is refused when it is
parsed.
The toolkit’s own words, a text field’s Cut, Copy and Paste and the names a screen reader hears for close and dismiss buttons, are English until an application gives it a translation:
Labels.use(ResourceBundle.getBundle("app.messages", locale));
// app/messages_ru.properties: goldberry.copy=Копировать
Each ToolkitLabel names its key. A word the bundle lacks stays English.
Call it again when the user switches language, and restyle so open menus
are rebuilt.
Read more
- Text and links: the
textandlinkwidgets