Task 17: The Wayland backend and the ztk program
Goal
ztk script.tcl opens a real window on a Wayland compositor, draws it with the Vulkan renderer, and sends the keyboard and the pointer to the widgets.
Files
src/platform/wayland.zigsrc/render/vulkan.zig: the surface and the swapchainsrc/main.zig: the flags of theztkprogrambuild.zig:wayland-scanner, the system librariestests/wayland-smoke.shdocs/references/dependencies.md
Interfaces
// src/platform/wayland.zig
pub const Wayland = struct {
/// Connects to the compositor of WAYLAND_DISPLAY.
pub fn init(gpa: std.mem.Allocator, vk: *Vulkan) !*Wayland;
pub fn platform(w: *Wayland) Platform;
/// The instance extensions that `Vulkan.init` needs for this backend.
pub const instance_extensions: []const [*:0]const u8;
};
// added to src/render/vulkan.zig
/// A target with a swapchain on a Wayland surface.
pub fn createWaylandTarget(v: *Vulkan, display: *anyopaque, surface: *anyopaque, width: u32, height: u32) !*Target;
pub fn resizeTarget(v: *Vulkan, t: *Target, width: u32, height: u32) !void;
/// Presents the last draw of a swapchain target.
pub fn present(v: *Vulkan, t: *Target) !void;
The ztk program:
ztk [flags] script.tcl [arguments]
--headless use the headless backend and the CPU renderer
--cpu use the CPU renderer on Wayland (a shared-memory buffer)
--exit-after-frames N exit with status 0 after N frames
--screenshot FILE.png with --headless: write the last frame at the exit
--scale N with --headless: the scale of the window
--dark the dark color scheme
--version
Steps
build.ziglinkswayland-client,xkbcommon, and libc, only for this backend. These are the only libraries that Stage 1 links. Vulkan needs the Wayland client library for its surface, and the compositor sends its key map in the XKB format. It runswayland-scanner(client-headerandprivate-code) for these files of/usr/share/wayland-protocols, and compiles the C output withaddCSourceFile:stable/xdg-shell/xdg-shell.xml(required)unstable/xdg-decoration/xdg-decoration-unstable-v1.xml(used when the compositor has it)stable/viewporter/viewporter.xmlandstaging/fractional-scale/fractional-scale-v1.xml(used when the compositor has both)staging/cursor-shape/cursor-shape-v1.xml(used when the compositor has it) Find the folder withpkg-config --variable=pkgdatadir wayland-protocols.
- The connection: bind
wl_compositor,xdg_wm_base, andwl_seat, and the optional globals. Answer thepingofxdg_wm_base. - The window: a
wl_surfacewith anxdg_surfaceand anxdg_toplevel. Set the title and the app id (ztk). Ask for server-side decorations whenxdg-decorationexists. With no decoration protocol, the window has no title bar in Stage 1. Record that indocs/stage1-limits.md. - Size: the first
configureof the toplevel with a size of 0 means "the client selects". Use the size that the App asked for. Aconfigurewith a size gives aresizeevent. Acknowledge each configure before the next commit.requestSizechanges the size only when the compositor did not fix it. - Scale: with
fractional-scaleandviewporter, use the preferred scale (a count of 120ths), make the buffersize * scalerounded to the nearest integer, and set the viewport destination to the logical size. Without them, use the integer scale ofwl_surface.preferred_buffer_scale, or of the outputs that the surface is on, andwl_surface.set_buffer_scale. A change gives ascaleevent. - The Vulkan surface:
VK_KHR_wayland_surface. The swapchain has the present mode FIFO, so a present waits for the display. Select an 8-bit UNORM format (BGRA or RGBA), and not an sRGB format, because the blend is in sRGB space. When the surface gives only an sRGB format, stop with a clear error and record it. - Frames:
requestFrameasks for awl_surface.framecallback, when none is pending, and commits. The callback gives aframeevent.drawrenders the scene and presents. The first frame after the first configure needs no callback. - A resize makes a new swapchain with the new size before the next draw.
VK_ERROR_OUT_OF_DATE_KHRandVK_SUBOPTIMAL_KHRdo the same. - The keyboard:
wl_keyboardgives a keymap. Load it withxkb_keymap_new_from_stringand keep anxkb_state. A key gives akeyevent withxkb_state_key_get_one_sym, the key code plus 8, and the UTF-8 ofxkb_state_key_get_utf8. Update the state on amodifiersevent. The modifiers of the event come from the state: Shift, Lock, Control, Mod1, Mod4. Key repeat: the client repeats. Use the rate and the delay ofrepeat_infowithLoop.addNative, and stop at the release, at a focus loss, and at another key press. - The pointer:
enter,leave,motion,button, andaxis. The positions are logical pixels. The Linux button codes map to the Tk numbers:BTN_LEFT(0x110) is 1,BTN_MIDDLE(0x112) is 2,BTN_RIGHT(0x111) is 3. Anaxisevent gives ascrollevent. No widget of Stage 1 uses it. - The cursor: on each pointer
enter, set the default shape withcursor-shapewhen it exists. With no such protocol, the cursor is the one the compositor shows. Record that indocs/stage1-limits.md. - Keyboard focus:
wl_keyboard.enterandleavegivefocusevents. - Close:
xdg_toplevel.closegives acloseevent. wait(timeout): usewl_display_prepare_read, flush,pollon the descriptor of the display with the timeout, thenwl_display_read_eventsorwl_display_cancel_read.poll(of the backend interface) callswl_display_dispatch_pendingand moves the events to the list.--cpuuses the CPU renderer with awl_shmbuffer. It is the fallback whenVulkan.initfails: print one line to stderr that says so. It reports only the rows ofchangedRows(task 06) as damage, withwl_surface.damage_buffer. A frame with no changed row commits no buffer.src/main.zig: without--headless, connect to Wayland. WhenWAYLAND_DISPLAYis not set, printztk: no Wayland display. Use --headless, or run in a Wayland session.and exit with status 1. SetApp.Options.style_rootto the folder of the script. Run the script, thenApp.run. Exit with status 0 when.is deleted, and with status 1 after a script error before the loop starts.- Fonts: Stage 1 uses the fonts of the repository on each backend. The fonts of the system are Stage 2.
tests/wayland-smoke.shstarts a private compositor and runs the program in it:
The script stops the compositor by its PID at the end. It exits with status 77 whenexport XDG_RUNTIME_DIR="$(mktemp -d)" weston --backend=headless --renderer=gl --socket=ztk-test --width=800 --height=600 & WAYLAND_DISPLAY=ztk-test zig-out/bin/ztk --exit-after-frames 5 tests/scripts/smoke.tclwestonis not on the path. First try the Vulkan renderer. When the surface or the swapchain fails in the headless compositor, the script runs the program again with--cpuand prints which renderer passed. Record the result in the commit message. If neither works in the headless compositor, write the errors indocs/tasks/BLOCKED.mdand do the manual check of step 19.- One manual check on the live session of the development machine, when
WAYLAND_DISPLAYis set:zig-out/bin/ztk --exit-after-frames 180 tests/scripts/smoke.tcl. The window shows for about three seconds. Run it one time only, and only for this task, because the machine is shared. Record the exit status and the frame count.
Tests
zig build
zig build test
tests/wayland-smoke.sh
zig-out/bin/ztk --headless --exit-after-frames 1 --screenshot /tmp/ztk-smoke.png tests/scripts/smoke.tcl
zig-out/bin/ztk --version
tests/scripts/smoke.tcl makes one label, one button, and one entry in a grid.
- The smoke script exits with status 0 and the program printed
frames: 5. - The headless command writes a PNG that is equal to the golden image
smoke.png. env -u WAYLAND_DISPLAY zig-out/bin/ztk tests/scripts/smoke.tclexits with status 1 and prints the message of step 16.zig-out/bin/ztk --headless nosuch.tclexits with status 1 and names the file.- A script with a syntax error exits with status 1 and prints the error.
tools/oracle.shnow useszig-out/bin/ztk --headless. The oracle runner of task 10 is removed. The two oracle commands of task 10 still pass.
Acceptance
- All commands above pass, or
BLOCKED.mdhas the exact reason for the smoke script. - The manual check of step 19 ran one time, with status 0 and 180 frames in 3.0 to 3.5 seconds on a 60 Hz display.
- No Wayland object and no Vulkan object stays alive at the exit: run the smoke script with
ZTK_VK_VALIDATE=1when the layer exists. src/app.zighas no Wayland name and no Vulkan name.
Out of scope
- X11. Stage 2.
- Client-side decorations, the clipboard, drag and drop, input methods, touch, and tablet input.
- More than one window, popups, and the window position.
- The cursor shapes of
-cursor. - Multiple monitors with different scales, beyond the
scaleevent.