v0.4.0
Projects · Lesson 27.17

System info

Source
Open a window that shows the Windows edition, version and build, the processor, and the memory. The values come from the Win32 calls in the Windows package, and the program draws them with GDI in a classic window with a message loop. Every Win32 call is extern, so each sits in an unsafe block under a // Safety: comment that says why it is sound there.
You'll need: Parts 1–24 — this project is a checkpoint for Platform, and leans on Extern, C interop, Target and Compile error.

Windows' own About page answers a simple question — which Windows is this, on what machine? This project answers it in a window of its own. It reads the edition, version and build of Windows, the processor and the memory, then opens a classic Win32 window and draws them:

Windows
  Edition             Windows 11 Pro
  Version             26H2
  OS build            26300.9711

Melody made one foreign call. This program makes dozens — the registry, the version, the processor, the memory, a window class, fonts, painting and a message loop — all from the Windows package, and every one of them through extern. That makes it the second checkpoint for Part 24: Platform, next to Melody: a whole Windows program, written the way a C program for Windows would be, but with every promise it makes to the system written down where you can see it. It builds and runs only on Windows.

Try it first

Before reading on, try a smaller version. Show a message box with MessageBoxW that says which build of Windows is running, read with RtlGetVersion. That is two foreign calls, a c16 literal and one struct — and once it works, a window that draws several lines is the same idea, repeated.

How it is put together

FunctionIts jobLessons it uses
when #target.osImports the Win32 names on Windows, stops the build elsewhereWhen, Target, Compile error
Widen, AddRowStores each line of the report as the UTF-16 Windows drawsEncoding, Writable slice
AddValueFormats a value into a fixed buffer, the way PrintLine doesVariadic, Format, Fail
ReadText, ReadNumberRead the registry, with a missing value as empty or noneC interop, Optional
CountCoresWalks the records Windows writes, one per corePointer, Pointer arithmetic
GatherReads everything the window shows, in orderPresence, Ternary
Procedure, PaintThe window procedure Windows calls, and the drawing it asks forCallback, Extern
MainRegisters the class, opens the window, runs the message loopLoop, Catch fallback

The program gathers the report first, then hands control to Windows. From then on Windows does the calling: the message loop takes each message from the queue, and DispatchMessageW passes it to Procedure:

flowchart LR
    main(["`Main`"]) -- "`Gather`" --> rows["`Rows`<br/>UTF-16 report"]
    main -- "`RegisterClassExW`<br/>`CreateWindowExW`" --> window["the window"]
    main -- "`GetMessageW`<br/>`DispatchMessageW`" --> proc["`Procedure`"]
    proc -- "`WM_PAINT`" --> paint["`Paint`<br/>`TextOutW`"]
    rows --> paint
    proc -- "`WM_DESTROY`" --> quit["`PostQuitMessage`<br/>the loop ends"]

Windows only, on purpose

Every Win32 name comes in through one import inside a compile-time when, and every other system gets a sentence instead of a wall of unknown names:

when #target.os {
    .Windows => import Windows::{ BeginPaint, CreateWindowExW, GetLastError, MessageBoxW, RtlGetVersion },
    _ => #Error("SystemInfo opens a Win32 window, so it builds only for Windows")
}

The real import names more than eighty functions, structs and constants. Checking for Linux shows the _ arm at work:

rux check --target linux-x86_64
error: SystemInfo opens a Win32 window, so it builds only for Windows

The Windows dependency in Rux.toml carries TargetOS = ["Windows"] too, so the package is not even resolved for another system.

Text the way Windows wants it

The functions whose names end in W take UTF-16 text with a NUL after it. A c16 literal is exactly that: UTF-16, with a NUL that .length does not count. So the names the program hands to Windows are c16 constants, and each call passes its .data, the address of the first unit:

const ClassName = c16"RuxSystemInfo";
const Title = c16"System Information";

Text the program builds at run time is UTF-8, as all Rux text is. Widen converts it with MultiByteToWideChar into a fixed char16 buffer in a Row, once, when the report is gathered, so painting converts nothing. The other way, ReadText turns a registry value back into UTF-8 with WideCharToMultiByte, and trims the spaces some processors pad their names with.

Every foreign call in unsafe

The compiler knows each Win32 function only by its declaration. It cannot see whether a buffer is as large as the size passed beside it, or whether a handle is still alive. So every extern call — and every cast of an integer to a pointer, and every field read through one — must sit in an unsafe block, and each block has a // Safety: comment that says why the call is sound there:

var version: OsVersionInfoEx;
version.size = sizeof(OsVersionInfoEx) as uint32;
// Safety: `version` is a local `OsVersionInfoEx` whose size field says how large it is.
let versionStatus = unsafe { RtlGetVersion(@version) };

unsafe { … } is a value block, so a single call is one line. The comment is the program's side of the bargain, and rux lint holds it to it — leave one out and it warns:

warning: 'unsafe' block has no '// Safety:' comment on the line above it
help: say why the operations inside are sound in a '// Safety:' comment directly above it

Most comments here say one of three things: the buffer is a local of the size Windows is told, the text is a NUL-terminated c16 literal, or the handle was just created and checked. Reading them in order is a tour of what Win32 expects of a caller.

Reading the machine

Each value comes from the call that knows it best:

ShownComes from
Edition, versionthe registry, under SOFTWARE\Microsoft\Windows NT\CurrentVersion
OS build, kernel versionRtlGetVersion, plus the registry's update build revision
ArchitectureGetNativeSystemInfo
Processor name, base speedthe registry, under HARDWARE\DESCRIPTION\System\CentralProcessor\0
Cores, logical processorsGetLogicalProcessorInformationEx, GetActiveProcessorCount
MemoryGetPhysicallyInstalledSystemMemory, GlobalMemoryStatusEx

RtlGetVersion is used rather than the better-known GetVersionExW, which tells a program without a manifest that it runs on Windows 8. Even the true version says 10 on Windows 11, so the program tells the two apart by the build, which starts at 22000 — and corrects the registry's edition name, which says "Windows 10" there too.

A registry value that is missing is not a failure. ReadNumber returns uint32?, and Gather matches it with a .Some arm and a none arm:

match ReadNumber(CurrentVersion, UpdateBuildRevision) {
    .Some(revision) => try AddValue("OS build", "{}.{}", version.buildNumber, revision),
    none => try AddValue("OS build", "{}", version.buildNumber)
}

ReadText returns an empty slice instead, and the row shows "unknown" with an if value: if release.length > 0 { release } else { "unknown" }.

The window and its procedure

A Win32 window is three pieces. A window class names a procedure; the window is created from the class; and a message loop takes messages from the queue and hands each to the procedure until the window is closed. The procedure is an ordinary Rux function, named in the class like any callback:

let windowClass = WindowClassEx {
    size: sizeof(WindowClassEx) as uint32,
    style: CS_HREDRAW | CS_VREDRAW,
    windowProcedure: Procedure,
    // …
};

Windows calls Procedure with a message number and two words of data. WM_PAINT asks it to draw, WM_DPICHANGED says the window moved to a monitor with another scale, and WM_DESTROY says the window is closing, so it posts the quit message that ends the loop. Every other message goes to DefWindowProcW, which knows how to move, minimize and close a window.

Windows hands the procedure nothing of the program's own, so the report and the fonts live in module variables — Rows, RowCount and the three font handles — which Gather fills before the window exists and Paint reads each time Windows asks.

Sharp at every scale

A window that ignores scaling is stretched by Windows, and its text goes blurry at 150%. This one declares itself aware of each monitor's scale with SetProcessDpiAwarenessContext, and keeps its layout in units of a 96-DPI pixel, which Scale multiplies out by the window's DPI:

func Scale(value: int32, dpi: uint32) -> int32 {
    return (value * (dpi as int32) + 48) / 96;
}

The DPI is known only once the window exists on a monitor, so Main creates the window first, then sizes it with AdjustWindowRectExForDpi and SetWindowPos. When it moves to another monitor, WM_DPICHANGED makes the fonts again and takes the size Windows suggests.

When something fails

A Win32 call reports failure its own way — a zero, a null handle, a nonzero status — never by throwing, so the program checks each result by hand. A window program has no console to print to (it lets go of the one every Rux program starts with, through FreeConsole), so Fail names the call and the Windows error code in a message box, and Main returns 1:

// Safety: `windowClass` is a complete local `WindowClassEx` whose size field says how large it is.
let registered = unsafe { RegisterClassExW(@windowClass) };
if registered == 0 {
    return Fail("RegisterClassExW");
}

The one Rux error in the program is the formatter's. AddValue writes into a fixed buffer, so it is declared throws FormatError, and so is Gather, which calls it with try. Main catches it once, with a message box of its own. Fail itself cannot throw — it is already reporting a failure — so its one WriteFormat has a catch { _ => {} } that keeps whatever fitted.

The program

The whole lesson is one package in the Examples repository. Its comments explain every step.

Src/Main.rux
// Showing what a Windows machine is, in a window of its own: the edition, version and build of
// Windows, the processor, and the memory.
//
// Every value comes from Windows itself, through the Windows package. `RtlGetVersion` gives the
// true version and build, because `GetVersionExW` tells a program without a manifest that it runs
// on Windows 8. The registry gives the names — the edition, the release, the processor — and
// `GlobalMemoryStatusEx` and `GetLogicalProcessorInformationEx` give the numbers. Windows 11 still
// calls itself version 10, so it is told apart by its build, which starts at 22000; the registry's
// edition name says "Windows 10" there too, and is corrected the same way.
//
// The window is the classic Win32 shape. A window class names a procedure, Windows calls that
// procedure with every message for the window, and a loop takes messages from the queue and hands
// them over until the window is closed. The procedure here is an ordinary Rux function. It draws
// the report when asked to paint, makes its fonts again when the window moves to a monitor with
// another scale, and ends the loop when the window is destroyed.
//
// Two details keep it looking like a Windows 11 program. It declares itself aware of each
// monitor's scale, and sizes everything in units of a 96-DPI pixel multiplied out by the window's
// DPI, so text stays sharp at 150%. And it is built as a console program, as every Rux program is
// today, so it lets go of its console first.
//
// Every Win32 call is `extern`, so the compiler cannot check what it does with its arguments.
// Each one sits in an `unsafe` block under a `// Safety:` comment that says why the call is
// sound there, which keeps every promise the program makes to Windows in plain sight.
//
// A Win32 call reports failure its own way. A call that fails shows a message box naming the call
// and the Windows error code, and the program exits with 1. A registry value that is missing is
// not a failure: it is shown as "unknown".
import Core::{ #Error, #target };
import Format::WriteFormat;
import Text::{ BufferWriter, Display, FormatError, TextWriter };

when #target.os {
    .Windows => import Windows::{ ALL_PROCESSOR_GROUPS, AdjustWindowRectExForDpi, BeginPaint, CLEARTYPE_QUALITY,
                                  CLIP_DEFAULT_PRECIS, COLOR_GRAYTEXT, COLOR_WINDOW, COLOR_WINDOWTEXT, CS_HREDRAW,
                                  CS_VREDRAW, CW_USEDEFAULT, CreateFontW, CreateWindowExW, DEFAULT_CHARSET,
                                  DEFAULT_PITCH, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, DefWindowProcW,
                                  DeleteObject, DispatchMessageW, EndPaint, FW_NORMAL, FW_SEMIBOLD, FreeConsole,
                                  GetActiveProcessorCount, GetDpiForWindow, GetLastError,
                                  GetLogicalProcessorInformationEx, GetMessageW, GetModuleHandleW, GetNativeSystemInfo,
                                  GetPhysicallyInstalledSystemMemory, GetSysColor, GlobalMemoryStatusEx,
                                  HKEY_LOCAL_MACHINE, IDC_ARROW, IDI_APPLICATION, InvalidateRect, LoadCursorW,
                                  LoadIconW, MB_ICONERROR, MB_OK, MemoryStatusEx, Message, MessageBoxW,
                                  MultiByteToWideChar, OUT_DEFAULT_PRECIS, OsVersionInfoEx,
                                  PROCESSOR_ARCHITECTURE_AMD64, PROCESSOR_ARCHITECTURE_ARM64,
                                  PROCESSOR_ARCHITECTURE_INTEL, PaintStruct, PostQuitMessage,
                                  ProcessorRelationshipHeader, RRF_RT_REG_DWORD, RRF_RT_REG_SZ, Rect, RegGetValueW,
                                  RegisterClassExW, RelationProcessorCore, RtlGetVersion, SWP_NOACTIVATE, SWP_NOMOVE,
                                  SWP_NOZORDER, SW_SHOW, SelectObject, SetBkMode, SetProcessDpiAwarenessContext,
                                  SetTextColor, SetWindowPos, ShowWindow, SystemInfo, TRANSPARENT, TextOutW,
                                  TranslateMessage, UpdateWindow, WM_DESTROY, WM_DPICHANGED, WM_PAINT, WS_CAPTION,
                                  WS_MINIMIZEBOX, WS_OVERLAPPED, WS_SYSMENU, WideCharToMultiByte, WindowClassEx },
    _ => #Error("SystemInfo opens a Win32 window, so it builds only for Windows")
}

// The names handed to Windows. A `c16` literal is UTF-16 with a NUL after it, which is exactly the
// string a `W` function takes, so its `.data` is passed as it is.
const ClassName = c16"RuxSystemInfo";
const Title = c16"System Information";
const FaceName = c16"Segoe UI";
const CurrentVersion = c16"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
const CentralProcessor = c16"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0";
const ProductName = c16"ProductName";
const DisplayVersion = c16"DisplayVersion";
const UpdateBuildRevision = c16"UBR";
const ProcessorNameString = c16"ProcessorNameString";
const Megahertz = c16"~MHz";
const Overflow = c16"The report did not fit its buffers.";

// The UTF-8 code page, for converting between the text Rux formats and the text Windows draws.
const Utf8: uint32 = 65001;

// The layout, in pixels at 96 DPI, which is 100% scaling.
const Margin: int32 = 24;
const Indent: int32 = 12;
const ValueColumn: int32 = 176;
const ClientWidth: int32 = 600;
const HeadingHeight: int32 = 30;
const RowHeight: int32 = 22;
const SectionGap: int32 = 14;

// One line of the report, kept as the UTF-16 Windows draws, so painting converts nothing.
const MaxRows: uint = 16;
const LabelUnits: uint = 32;
const ValueUnits: uint = 96;

struct Row {
    heading: bool;
    label: char16[LabelUnits];
    labelLength: int32;
    value: char16[ValueUnits];
    valueLength: int32;
}

// The report and the fonts live in module variables, because the window procedure is called by
// Windows and can be handed nothing of its own.
const EmptyRow = Row {
    heading: false,
    label: [0 as char16; LabelUnits],
    labelLength: 0,
    value: [0 as char16; ValueUnits],
    valueLength: 0
};

var Rows: Row[MaxRows] = [EmptyRow; MaxRows];
var RowCount: uint = 0;
var HeadingFont: *var opaque = null;
var LabelFont: *var opaque = null;
var ValueFont: *var opaque = null;

// A length at 96 DPI, at the window's DPI instead, rounded to the nearest pixel.
func Scale(value: int32, dpi: uint32) -> int32 {
    return (value * (dpi as int32) + 48) / 96;
}

// UTF-8 text as UTF-16, into a fixed buffer. Returns how many units were written.
func Widen(text: char8[..], into: var char16[..]) -> int32 {
    if text.length == 0 {
        return 0;
    }
    // Safety: both views are live for the lengths Windows is given, and `into` is writable.
    return unsafe { MultiByteToWideChar(Utf8, 0, text.data, text.length as int32, into.data, into.length as int32) };
}

func AddRow(heading: bool, label: char8[..], value: char8[..]) {
    if RowCount == MaxRows {
        return;
    }
    Rows[RowCount].heading = heading;
    Rows[RowCount].labelLength = Widen(label, Rows[RowCount].label[..]);
    Rows[RowCount].valueLength = Widen(value, Rows[RowCount].value[..]);
    RowCount += 1;
}

// A row whose value is formatted from a pattern, the way PrintLine formats.
func AddValue(label: char8[..], #Format format: char8[..], args: &Display...) throws FormatError {
    var room: char8[160] = [0 as char8; 160];
    var writer = BufferWriter(room[..]);
    let sink: &var TextWriter = writer;
    try WriteFormat(sink, format, args...);
    AddRow(false, label, writer.Written());
}

// A string value from the machine's registry, as UTF-8 in `room` with the spaces around it
// removed. Empty when the value is missing.
func ReadText(subKey: char16[..], name: char16[..], room: var char8[..]) -> char8[..] {
    var wide: char16[256] = [0 as char16; 256];
    var size: uint32 = 512;
    // Safety: both names are NUL-terminated `c16` literals, and `wide` is a local buffer of the
    // 512 bytes that `size` tells Windows it may write.
    let status = unsafe {
        RegGetValueW(HKEY_LOCAL_MACHINE as *var opaque, subKey.data, name.data, RRF_RT_REG_SZ, null,
                     @wide[0] as *var opaque, @size)
    };
    if status != 0 {
        return room[..0];
    }
    // The size counts bytes, terminator included.
    let units = (size / 2) as int32 - 1;
    if units <= 0 {
        return room[..0];
    }
    // Safety: `wide` holds `units` units written by Windows, and `room` is writable for its length.
    let bytes = unsafe { WideCharToMultiByte(Utf8, 0, @wide[0], units, room.data, room.length as int32, null, null) };
    if bytes <= 0 {
        return room[..0];
    }
    var start: uint = 0;
    var end = bytes as uint;
    while start < end && room[start] == c8' ' {
        start += 1;
    }
    while end > start && room[end - 1] == c8' ' {
        end -= 1;
    }
    return room[start..end];
}

// A number value from the machine's registry, or none when it is missing.
func ReadNumber(subKey: char16[..], name: char16[..]) -> uint32? {
    var value: uint32 = 0;
    var size: uint32 = 4;
    // Safety: both names are NUL-terminated `c16` literals, and `value` is a local `uint32`, the
    // 4 bytes that `size` tells Windows it may write.
    let status = unsafe {
        RegGetValueW(HKEY_LOCAL_MACHINE as *var opaque, subKey.data, name.data, RRF_RT_REG_DWORD, null,
                     @value as *var opaque, @size)
    };
    if status != 0 {
        return none;
    }
    return value;
}

// How many physical cores the machine has: Windows writes one record per core, each starting
// with its own size, so counting them means walking the buffer record by record.
func CountCores() -> uint32 {
    var records: uint64[4096] = [0; 4096];
    var length: uint32 = 32768;
    // Safety: `records` is a local buffer of the 32768 bytes that `length` tells Windows it may write.
    let succeeded = unsafe {
        GetLogicalProcessorInformationEx(RelationProcessorCore, @records[0] as *var opaque, @length)
    };
    if succeeded == 0 {
        return 0;
    }
    let start = (@records[0]) as uint;
    var cores: uint32 = 0;
    var offset: uint32 = 0;
    while offset < length {
        // Safety: `offset` is below `length`, the bytes Windows wrote into `records`, and it lands on
        // the start of a record, each of which begins with its header.
        let size = unsafe {
            let header = (start + offset as uint) as *ProcessorRelationshipHeader;
            header.size
        };
        if size == 0 {
            break;
        }
        offset += size;
        cores += 1;
    }
    return cores;
}

func StartsWith(text: char8[..], prefix: char8[..]) -> bool {
    if text.length < prefix.length {
        return false;
    }
    for index in 0..prefix.length {
        if text[index] != prefix[index] {
            return false;
        }
    }
    return true;
}

func Gibibytes(bytes: uint64) -> float64 {
    return (bytes as float64) / 1073741824.0;
}

// Reads everything the window shows, in the order it shows it.
func Gather() throws FormatError {
    var version: OsVersionInfoEx;
    version.size = sizeof(OsVersionInfoEx) as uint32;
    // Safety: `version` is a local `OsVersionInfoEx` whose size field says how large it is.
    let versionStatus = unsafe { RtlGetVersion(@version) };
    if versionStatus != 0 {
        version.majorVersion = 0;
        version.minorVersion = 0;
        version.buildNumber = 0;
    }

    AddRow(true, "Windows", "");
    var productRoom: char8[128] = [0 as char8; 128];
    let product = ReadText(CurrentVersion, ProductName, productRoom[..]);
    let windows10 = "Windows 10";
    if version.buildNumber >= 22000 && StartsWith(product, windows10) {
        try AddValue("Edition", "Windows 11{}", product[windows10.length..]);
    } else if product.length > 0 {
        AddRow(false, "Edition", product);
    } else {
        AddRow(false, "Edition", "unknown");
    }
    var releaseRoom: char8[32] = [0 as char8; 32];
    let release = ReadText(CurrentVersion, DisplayVersion, releaseRoom[..]);
    AddRow(false, "Version", if release.length > 0 { release } else { "unknown" });
    match ReadNumber(CurrentVersion, UpdateBuildRevision) {
        .Some(revision) => try AddValue("OS build", "{}.{}", version.buildNumber, revision),
        none => try AddValue("OS build", "{}", version.buildNumber)
    }
    try AddValue("Kernel version", "{}.{}.{}", version.majorVersion, version.minorVersion, version.buildNumber);
    var system: SystemInfo;
    // Safety: `system` is a local `SystemInfo` for Windows to fill in.
    unsafe { GetNativeSystemInfo(@system); }
    let architecture = (system.processorArchitecture & 0xFFFF) as uint16;
    if architecture == PROCESSOR_ARCHITECTURE_AMD64 {
        AddRow(false, "Architecture", "64-bit, x64");
    } else if architecture == PROCESSOR_ARCHITECTURE_ARM64 {
        AddRow(false, "Architecture", "64-bit, Arm64");
    } else if architecture == PROCESSOR_ARCHITECTURE_INTEL {
        AddRow(false, "Architecture", "32-bit, x86");
    } else {
        AddRow(false, "Architecture", "unknown");
    }

    AddRow(true, "Processor", "");
    var processorRoom: char8[128] = [0 as char8; 128];
    let processor = ReadText(CentralProcessor, ProcessorNameString, processorRoom[..]);
    AddRow(false, "Name", if processor.length > 0 { processor } else { "unknown" });
    match ReadNumber(CentralProcessor, Megahertz) {
        .Some(megahertz) => try AddValue("Base speed", "{:.2} GHz", (megahertz as float64) / 1000.0),
        none => AddRow(false, "Base speed", "unknown")
    }
    let cores = CountCores();
    if cores > 0 {
        try AddValue("Cores", "{}", cores);
    } else {
        AddRow(false, "Cores", "unknown");
    }
    // Safety: the call takes a plain group number and touches no memory of ours.
    let logical = unsafe { GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) };
    try AddValue("Logical processors", "{}", logical);

    AddRow(true, "Memory", "");
    var installed: uint64 = 0;
    // Safety: `installed` is a local `uint64` for Windows to write.
    let installedKnown = unsafe { GetPhysicallyInstalledSystemMemory(@installed) };
    if installedKnown != 0 {
        try AddValue("Installed", "{:.1} GB", Gibibytes(installed * 1024));
    }
    var memory: MemoryStatusEx;
    memory.length = sizeof(MemoryStatusEx) as uint32;
    // Safety: `memory` is a local `MemoryStatusEx` whose length field says how large it is.
    let memoryKnown = unsafe { GlobalMemoryStatusEx(@memory) };
    if memoryKnown != 0 {
        try AddValue("Usable", "{:.1} GB", Gibibytes(memory.totalPhysical));
        try AddValue("Available", "{:.1} GB", Gibibytes(memory.availablePhysical));
        try AddValue("In use", "{}%", memory.memoryLoad);
    } else {
        AddRow(false, "Usable", "unknown");
    }
}

// The client area's height at 96 DPI: every row, the headings and the gaps between sections.
func ClientHeight() -> int32 {
    var height: int32 = Margin * 2;
    for index in 0..RowCount {
        if Rows[index].heading {
            height += HeadingHeight;
            if index > 0 {
                height += SectionGap;
            }
        } else {
            height += RowHeight;
        }
    }
    return height;
}

// A Segoe UI font of a size in points. A negative height asks for that many pixels of character
// height, and a point is 1/72 of an inch, of which the window has `dpi` pixels.
func MakeFont(points: int32, weight: int32, dpi: uint32) -> *var opaque {
    let pixels = (points * (dpi as int32) + 36) / 72;
    // Safety: every argument is a plain value except the face name, a NUL-terminated `c16` literal.
    return unsafe {
        CreateFontW(-pixels, 0, 0, 0, weight, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
                    CLEARTYPE_QUALITY, DEFAULT_PITCH, FaceName.data)
    };
}

func DeleteFonts() {
    if HeadingFont != null {
        // Safety: `HeadingFont` is a font CreateFontW made that nothing has deleted yet.
        unsafe { DeleteObject(HeadingFont); }
        HeadingFont = null;
    }
    if LabelFont != null {
        // Safety: `LabelFont` is a font CreateFontW made that nothing has deleted yet.
        unsafe { DeleteObject(LabelFont); }
        LabelFont = null;
    }
    if ValueFont != null {
        // Safety: `ValueFont` is a font CreateFontW made that nothing has deleted yet.
        unsafe { DeleteObject(ValueFont); }
        ValueFont = null;
    }
}

func CreateFonts(dpi: uint32) {
    DeleteFonts();
    HeadingFont = MakeFont(12, FW_SEMIBOLD, dpi);
    LabelFont = MakeFont(10, FW_NORMAL, dpi);
    ValueFont = MakeFont(10, FW_SEMIBOLD, dpi);
}

// Draws the report: a heading per section, then each label in gray with its value beside it.
func Paint(window: *var opaque) {
    var paint: PaintStruct;
    // Safety: `window` is the window Windows asked to paint, and `paint` is a local for it to fill in.
    let context = unsafe { BeginPaint(window, @paint) };
    if context == null {
        return;
    }
    // Safety: `context` is the device context BeginPaint returned, valid until EndPaint below. The
    // fonts are ones CreateFonts made, and each row's buffers hold at least the lengths passed.
    unsafe {
        let dpi = GetDpiForWindow(window);
        SetBkMode(context, TRANSPARENT);
        let original = SelectObject(context, ValueFont);
        var y: int32 = Margin;
        for index in 0..RowCount {
            if Rows[index].heading {
                if index > 0 {
                    y += SectionGap;
                }
                SelectObject(context, HeadingFont);
                SetTextColor(context, GetSysColor(COLOR_WINDOWTEXT));
                TextOutW(context, Scale(Margin, dpi), Scale(y, dpi), @Rows[index].label[0], Rows[index].labelLength);
                y += HeadingHeight;
            } else {
                SelectObject(context, LabelFont);
                SetTextColor(context, GetSysColor(COLOR_GRAYTEXT));
                TextOutW(context, Scale(Margin + Indent, dpi), Scale(y, dpi), @Rows[index].label[0],
                         Rows[index].labelLength);
                SelectObject(context, ValueFont);
                SetTextColor(context, GetSysColor(COLOR_WINDOWTEXT));
                TextOutW(context, Scale(ValueColumn, dpi), Scale(y, dpi), @Rows[index].value[0],
                         Rows[index].valueLength);
                y += RowHeight;
            }
        }
        SelectObject(context, original);
        EndPaint(window, @paint);
    }
}

// The window procedure: Windows calls it with every message for the window.
func Procedure(window: *var opaque, message: uint32, wParam: uint, lParam: int) -> int {
    if message == WM_PAINT {
        Paint(window);
        return 0;
    }
    if message == WM_DPICHANGED {
        // The new DPI is in the low word, and lParam points to the size Windows suggests for it.
        CreateFonts((wParam & 0xFFFF) as uint32);
        // Safety: for WM_DPICHANGED, Windows documents lParam as the address of a live `Rect`, and
        // `window` is the window the message is for.
        unsafe {
            let suggested = (lParam as uint) as *Rect;
            SetWindowPos(window, null, suggested.left, suggested.top, suggested.right - suggested.left,
                         suggested.bottom - suggested.top, SWP_NOZORDER | SWP_NOACTIVATE);
            InvalidateRect(window, null, true);
        }
        return 0;
    }
    if message == WM_DESTROY {
        DeleteFonts();
        // Safety: the call takes a plain exit code and touches no memory of ours.
        unsafe { PostQuitMessage(0); }
        return 0;
    }
    // Safety: the arguments are exactly the ones Windows passed to this procedure.
    return unsafe { DefWindowProcW(window, message, wParam, lParam) };
}

// Tells the user which call failed and why, since a window program has no console to print to.
func Fail(call: char8[..]) -> int {
    // Safety: the call takes nothing and only reads this thread's last error code.
    let code = unsafe { GetLastError() };
    var room: char8[160] = [0 as char8; 160];
    var writer = BufferWriter(room[..]);
    let sink: &var TextWriter = writer;
    try WriteFormat(sink, "{} failed with Windows error {}.", call, code) catch { _ => {} };
    var text: char16[161] = [0 as char16; 161];
    Widen(writer.Written(), text[..160]);
    // Safety: `text` is a local buffer with a NUL after the widened text, and the title is a `c16` literal.
    unsafe { MessageBoxW(null, @text[0], Title.data, MB_OK | MB_ICONERROR); }
    return 1;
}

func Main() -> int {
    // Safety: neither call touches memory of ours; the awareness context is a constant Windows
    // defines. The second fails only when the awareness was already set, which leaves it as good.
    unsafe {
        FreeConsole();
        SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 as *var opaque);
    }

    try Gather() catch {
        _ => {
            // Safety: the text and the title are NUL-terminated `c16` literals.
            unsafe { MessageBoxW(null, Overflow.data, Title.data, MB_OK | MB_ICONERROR); }
            return 1;
        }
    };

    // Safety: a null name asks for this program's own module and touches no memory of ours.
    let instance = unsafe { GetModuleHandleW(null) };
    // Safety: the icon and cursor are the integer resource names Windows defines, passed as the
    // pointers its functions take for them.
    let icon = unsafe { LoadIconW(null, IDI_APPLICATION as *char16) };
    // Safety: as for the icon above.
    let cursor = unsafe { LoadCursorW(null, IDC_ARROW as *char16) };
    let windowClass = WindowClassEx {
        size: sizeof(WindowClassEx) as uint32,
        style: CS_HREDRAW | CS_VREDRAW,
        windowProcedure: Procedure,
        classExtra: 0,
        windowExtra: 0,
        instance: instance,
        icon: icon,
        cursor: cursor,
        background: ((COLOR_WINDOW + 1) as uint) as *var opaque,
        menuName: null,
        className: ClassName.data,
        smallIcon: null
    };
    // Safety: `windowClass` is a complete local `WindowClassEx` whose size field says how large it is.
    let registered = unsafe { RegisterClassExW(@windowClass) };
    if registered == 0 {
        return Fail("RegisterClassExW");
    }

    // A fixed-size window: a title bar, a close button and a minimize button, but no sizing border.
    let style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
    // Safety: the class name and title are NUL-terminated `c16` literals, and the class is registered.
    let window = unsafe {
        CreateWindowExW(0, ClassName.data, Title.data, style, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                        CW_USEDEFAULT, null, null, instance, null)
    };
    if window == null {
        return Fail("CreateWindowExW");
    }

    // Only now is the monitor known, so only now can the window be given its size.
    // Safety: `window` was just created and checked to be non-null.
    let dpi = unsafe { GetDpiForWindow(window) };
    CreateFonts(dpi);
    var frame = Rect { left: 0, top: 0, right: Scale(ClientWidth, dpi), bottom: Scale(ClientHeight(), dpi) };
    // Safety: `frame` is a local `Rect` for Windows to adjust, and `window` is the live window above.
    unsafe {
        AdjustWindowRectExForDpi(@frame, style, false, 0, dpi);
        SetWindowPos(window, null, 0, 0, frame.right - frame.left, frame.bottom - frame.top,
                     SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
        ShowWindow(window, SW_SHOW);
        UpdateWindow(window);
    }

    // The message loop. GetMessageW returns zero for the quit message and -1 for an error.
    var message: Message;
    loop {
        // Safety: `message` is a local `Message` for Windows to fill in.
        let result = unsafe { GetMessageW(@message, null, 0, 0) };
        if result == 0 {
            break;
        }
        if result == -1 {
            return Fail("GetMessageW");
        }
        // Safety: `message` holds the message GetMessageW just filled in.
        unsafe {
            TranslateMessage(@message);
            DispatchMessageW(@message);
        }
    }
    return 0;
}

Its Rux.toml lists Core, Format, Text and Windows under [Dependencies].

Run it

cd Examples/Projects/SystemInfo
rux run
Windows
  Edition             Windows 11 Pro
  Version             26H2
  OS build            26300.9711
  Kernel version      10.0.26300
  Architecture        64-bit, x64
Processor
  Name                11th Gen Intel(R) Core(TM) i9-11900KF @ 3.50GHz
  Base speed          3.50 GHz
  Cores               8
  Logical processors  16
Memory
  Installed           64.0 GB
  Usable              63.8 GB
  Available           51.1 GB
  In use              19%

The output above is what the window shows, not what the program prints: run it on Windows and a window titled "System Information" opens and stays until you close it. Your edition, build, processor and memory will differ. On Linux, macOS or FreeBSD the build stops with the #Error message shown above.

Common mistakes

Try it yourself

  1. Add a row under Windows for the computer's name, read from the registry under SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName. It is one more c16 constant and one more ReadText call.
  2. Add an "Uptime" row with GetTickCount64, shown as days, hours and minutes. Which // Safety: comment does that call need?
  3. Make Fail also show the Windows message for the code, with FormatMessageW. What does its // Safety: comment have to promise about the buffer?
  4. Put a button under the report that copies it to the clipboard. A button is a child window of the class BUTTON, and its click arrives in Procedure as WM_COMMAND.

Learn more