gpui-cc Course handbook
CHAPTER 05 / STAGE 16COURSE

Measure a line before painting it

Give an ASCII label intrinsic size with FreeType.

text-measure
On this page

Learn: a space moves the pen without making a mark

A character code selects a glyph in a font. A glyph’s advance moves the pen for the next glyph; its bitmap width says how much ink it spans. They are different measurements. A baseline is the line that anchors glyph positions. This course supports one line of printable ASCII at a positive integer pixel size, with an explicit font. Reject other input with a useful diagnostic rather than silently advertising Unicode support.

Run it: compare advance and ink in a real font

Build inspect-font.cpp. Point it at a known font such as DejaVu Sans. fc-match reports the selected file if fontconfig is installed; inspect the path, since it can fall back when a family is missing. If needed, install your distribution’s FreeType development and DejaVu font packages. Record the chosen file and checksum for repeatable tests; do not silently accept a different face. Supplying a path is enough for this course; do not commit fonts without their redistribution license.

Terminal
mkdir -p build/examples
c++ -std=c++20 course/examples/inspect-font.cpp -o build/examples/inspect-font \
  $(pkg-config --cflags --libs freetype2)
font="$(fc-match -f '%{file}\n' 'DejaVu Sans' | head -n 1)"
./build/examples/inspect-font "$font"
C++ · inspect-font.cpp
#include <ft2build.h>
#include FT_FREETYPE_H
#include <iostream>

int main(int argc, char** argv) {
    if (argc != 2) {
        std::cerr << "usage: inspect-font FONT_FILE\n";
        return 2;
    }
    FT_Library library{};
    if (FT_Init_FreeType(&library)) return 1;
    FT_Face face{};
    if (FT_New_Face(library, argv[1], 0, &face)) {
        std::cerr << "Could not open font\n";
        FT_Done_FreeType(library);
        return 1;
    }
    bool ok = true;
    for (unsigned size : {16u, 32u}) {
        if (FT_Set_Pixel_Sizes(face, 0, size)) { ok = false; break; }
        for (char ch : {' ', 'A'}) {
            if (FT_Load_Char(face, ch, FT_LOAD_RENDER)) { ok = false; break; }
            const auto slot = face->glyph;
            std::cout << size << "px " << (ch == ' ' ? "space" : "A")
                      << " advance=" << slot->advance.x / 64.0
                      << " ink=" << (slot->bitmap.width != 0 && slot->bitmap.rows != 0 ? "yes" : "no")
                      << '\n';
        }
        if (!ok) break;
    }
    FT_Done_Face(face);
    FT_Done_FreeType(library);
    return ok ? 0 : 1;
}

Expect four lines: space has positive advance but ink=no; A has ink. The larger size should increase advances for the chosen face. Exact numbers vary by face and rasterizer version. The sample opens the library and face, selects a pixel size, loads a glyph, and reads the current glyph slot. A new load overwrites that slot. An advance in 26.6 fixed point is measured in sixty-fourths of a pixel; divide by 64 only at a defined rounding boundary. Try it: run with a nonexistent file and check the error/status.

Build it: let text give layout an intrinsic size

Your challenge: Add an ASCII measurement operation and use it to size a text leaf. No text drawing yet.

Keep the font face alive for measurement and painting, and destroy the face before its library. Take text, an explicit pixel size, and a face. For each byte, first ensure the supported ASCII range; select a glyph (FT_Get_Char_Index) and load it, reporting missing glyph or font errors. Accumulate horizontal advances in a checked, wide type. Read the face size’s ascent/descent/line metrics for your one-line box and record how you round. Keep a baseline offset for Stage 17. A zero-length string has zero advance; use one consistent decision for its line height (e.g. the selected font’s line height). Return plain measurements, not a borrowed FT_GlyphSlot.

Check it

At a fixed size compare "", "A", " A", and "A A". Adding a space increases advance without requiring visible ink. Increase the size for your known font and test that the intrinsic box changes. Test an absent font, unsupported byte, and nonpositive size. Confirm a label constrained by its parent doesn’t claim more than the allowed layout box.

Terminal
python3 course/check_core.py text-measure

Hints and troubleshooting

Hint: spaces vanish or 16px produces a giant box

Inspect advance and bitmap width separately. Check whether a value is in 26.6 units or integer pixels. Never use bitmap width as pen advance. See the FreeType glyph metrics guide.